This repository has been archived by the owner on Jan 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
port_pool.go
124 lines (94 loc) · 1.9 KB
/
port_pool.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
package port_pool
import (
"fmt"
"sync"
)
type PortPool struct {
start uint32
size uint32
pool []uint32
poolMutex sync.Mutex
state State
}
type PoolExhaustedError struct{}
func (e PoolExhaustedError) Error() string {
return "port pool is exhausted"
}
type PortTakenError struct {
Port uint32
}
func (e PortTakenError) Error() string {
return fmt.Sprintf("port already acquired: %d", e.Port)
}
func New(start, size uint32, state State) (*PortPool, error) {
if start+size > 65535 {
return nil, fmt.Errorf("port_pool: New: invalid port range: startL %d, size: %d", start, size)
}
if state.Offset >= size {
state.Offset = 0
}
pool := make([]uint32, size)
i := 0
for port := start + state.Offset; port < start+size; port++ {
pool[i] = port
i += 1
}
for port := start; port < start+state.Offset; port++ {
pool[i] = port
i += 1
}
return &PortPool{
start: start,
size: size,
pool: pool,
}, nil
}
func (p *PortPool) Acquire() (uint32, error) {
p.poolMutex.Lock()
defer p.poolMutex.Unlock()
if len(p.pool) == 0 {
return 0, PoolExhaustedError{}
}
port := p.pool[0]
p.pool = p.pool[1:]
return port, nil
}
func (p *PortPool) Remove(port uint32) error {
idx := 0
found := false
p.poolMutex.Lock()
defer p.poolMutex.Unlock()
for i, existingPort := range p.pool {
if existingPort == port {
idx = i
found = true
break
}
}
if !found {
return PortTakenError{port}
}
p.pool = append(p.pool[:idx], p.pool[idx+1:]...)
return nil
}
func (p *PortPool) Release(port uint32) {
if port < p.start || port >= p.start+p.size {
return
}
p.poolMutex.Lock()
defer p.poolMutex.Unlock()
for _, existingPort := range p.pool {
if existingPort == port {
return
}
}
p.pool = append(p.pool, port)
}
func (p *PortPool) RefreshState() State {
if len(p.pool) == 0 {
p.state.Offset = 0
} else {
p.state.Offset = p.pool[0] - p.start
}
return p.state
}