-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanager.go
258 lines (210 loc) · 5.94 KB
/
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
package pool
import (
"errors"
"log"
"net"
"sync"
"sync/atomic"
"time"
)
type (
// Manager responsible for managing pool of connections
Manager struct {
config ManagerConfig
callback func(conn net.Conn, requestBody []byte, requestBodyLen int)
pool workersPool
killCleaner chan bool
isStop bool
}
// ManagerConfig represents struct for configuration parameters
ManagerConfig struct {
Debug bool // if you want to log debug messages
BufferSize int // buffer size when reading clients connections (in bytes), by default it is 5120
MinWorkersCount int32 // min number of pool workers - can be 0
MaxWorkersCount int32 // max number of pool workers - can be 0, it means then that there is no max number of workers
ClientsDeadline time.Duration // interval from Now() in nanoseconds when connection will timeout if there is no activity, by default it is 3s
}
)
// CreateManager creates new pool manager
func CreateManager(config ManagerConfig, callback func(conn net.Conn, requestBody []byte, requestBodyLen int)) Manager {
return Manager{
config: checkConfig(config),
callback: callback,
killCleaner: make(chan bool),
isStop: true,
pool: workersPool{
workersMux: new(sync.RWMutex),
workersChn: make(chan net.Conn),
},
}
}
// Start fiers up workers and initialize pool
func (m *Manager) Start() error {
if m.isStop == false {
return errors.New("pool manager is already running")
}
m.isStop = false
// start pool workers
n := int32(0)
for ; n < m.config.MinWorkersCount; n++ {
m.spawnWorker()
}
m.pool.workersCount = m.config.MinWorkersCount
go m.cleaner()
return nil
}
// Put used to add new connection to the pool
func (m *Manager) Put(conn net.Conn) error {
if m.config.Debug == true {
log.Println("[pool]: Put new connection")
}
if m.isStop == true {
return errors.New("pool manager is not running, please use Start() method to run")
} else if m.config.MaxWorkersCount > 0 && m.pool.workersBusyCount >= m.config.MaxWorkersCount {
return errors.New("can't put, pool is busy")
} else if (m.config.MaxWorkersCount > 0 && m.pool.workersBusyCount >= m.pool.workersCount) || (m.config.MaxWorkersCount < 1 && m.pool.workersBusyCount >= m.config.MinWorkersCount) {
m.spawnWorker()
}
atomic.AddInt32(&m.pool.workersBusyCount, 1)
m.pool.workersChn <- m.setDeadline(conn, m.config.ClientsDeadline)
return nil
}
// Config return current pool manager config values. It will return ManagerConfig struct.
func (m *Manager) Config() ManagerConfig {
return m.config
}
// SetConfig will set new configuration for pool manager
func (m *Manager) SetConfig(config ManagerConfig) {
m.config = checkConfig(config)
}
// Stop will gracefully stop pool manager - will wait for all busy workers to finish their job and then will kill all of them
func (m *Manager) Stop() {
m.isStop = true
allKilled := make(chan bool)
// kill all workers
go func(allKiled chan bool, workers []*worker) {
killed := 0
toKill := len(workers)
for {
for _, worker := range workers {
if worker.getState() != WorkerStateBusy {
worker.shutdown()
killed++
}
}
if killed < toKill {
continue
}
break
}
allKiled <- true
}(allKilled, m.pool.workers)
<-allKilled
m.killCleaner <- true
}
func (m *Manager) spawnWorker() {
worker := &worker{
handler: m.worker,
state: WorkerStateInit,
mux: new(sync.Mutex),
kill: make(chan bool),
}
m.pool.workersMux.RLock()
m.pool.workers = append(m.pool.workers, worker)
m.pool.workersMux.RUnlock()
atomic.AddInt32(&m.pool.workersCount, 1)
go worker.handler(worker, m.pool.workersChn)
}
func (m *Manager) worker(w *worker, conns chan net.Conn) {
workToDo := func(w *worker, conns chan net.Conn) bool {
for {
select {
case <-w.kill:
w.setState(WorkerStateKilled)
return true
case conn := <-conns:
w.setState(WorkerStateBusy)
errConn := m.checkConnection(conn)
if errConn != nil {
conn.Close()
w.setState(WorkerStateIdle)
continue
}
for {
// pseudo rate limiter - this could be extended to allow to limit rate of reuqests
time.Sleep(100 * time.Nanosecond)
connBody, err := m.readConn(conn, m.config.ClientsDeadline)
if err != nil {
conn.Close()
break
}
// send body request to callback
m.callback(conn, connBody, len(connBody))
}
w.setState(WorkerStateIdle)
atomic.AddInt32(&m.pool.workersBusyCount, -1)
}
}
}
workToDo(w, conns)
}
// cleaner runs every 2s
func (m *Manager) cleaner() {
for {
time.Sleep(2 * time.Second)
if m.pool.workersCount > m.config.MinWorkersCount && m.pool.workersBusyCount < m.config.MinWorkersCount {
toDelete := m.pool.workersCount - m.config.MinWorkersCount
deleted := int32(0)
i := len(m.pool.workers) - 1
for ; i >= 0; i-- {
if deleted >= toDelete {
break
}
worker := m.pool.workers[i]
if worker.state == WorkerStateIdle {
worker.shutdown()
m.pool.workers = append(m.pool.workers[:i], m.pool.workers[i+1:]...)
atomic.AddInt32(&m.pool.workersCount, -1)
deleted++
}
}
continue
}
select {
case <-m.killCleaner:
return
default:
continue
}
}
}
func (m *Manager) readConn(client net.Conn, deadline time.Duration) ([]byte, error) {
var (
tmpBuffer = make([]byte, m.config.BufferSize)
clientData = make([]byte, 0)
err error
n int
)
for {
m.setDeadline(client, deadline)
n, err = client.Read(tmpBuffer)
if err != nil {
return clientData, err
}
clientData = append(clientData, tmpBuffer[:n]...)
if n < m.config.BufferSize {
return clientData, nil
}
}
}
func (m *Manager) setDeadline(conn net.Conn, deadline time.Duration) net.Conn {
conn.SetDeadline(time.Now().Add(deadline * time.Nanosecond))
return conn
}
func (m *Manager) checkConnection(conn net.Conn) error {
_, err := conn.Read(emptyByte)
if err != nil {
return err
}
return nil
}