Improve concurrency and resource management #2
@ -5,10 +5,12 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"tunnel_pls/utils"
|
"tunnel_pls/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
type PortManager struct {
|
type PortManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
ports map[uint16]bool
|
ports map[uint16]bool
|
||||||
sortedPorts []uint16
|
sortedPorts []uint16
|
||||||
}
|
}
|
||||||
@ -37,6 +39,9 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pm *PortManager) AddPortRange(startPort, endPort uint16) error {
|
func (pm *PortManager) AddPortRange(startPort, endPort uint16) error {
|
||||||
|
pm.mu.Lock()
|
||||||
|
defer pm.mu.Unlock()
|
||||||
|
|
||||||
if startPort > endPort {
|
if startPort > endPort {
|
||||||
return fmt.Errorf("start port cannot be greater than end port")
|
return fmt.Errorf("start port cannot be greater than end port")
|
||||||
}
|
}
|
||||||
@ -53,8 +58,12 @@ func (pm *PortManager) AddPortRange(startPort, endPort uint16) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pm *PortManager) GetUnassignedPort() (uint16, bool) {
|
func (pm *PortManager) GetUnassignedPort() (uint16, bool) {
|
||||||
|
pm.mu.Lock()
|
||||||
|
defer pm.mu.Unlock()
|
||||||
|
|
||||||
for _, port := range pm.sortedPorts {
|
for _, port := range pm.sortedPorts {
|
||||||
if !pm.ports[port] {
|
if !pm.ports[port] {
|
||||||
|
pm.ports[port] = true
|
||||||
return port, true
|
return port, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -62,6 +71,9 @@ func (pm *PortManager) GetUnassignedPort() (uint16, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pm *PortManager) SetPortStatus(port uint16, assigned bool) error {
|
func (pm *PortManager) SetPortStatus(port uint16, assigned bool) error {
|
||||||
|
pm.mu.Lock()
|
||||||
|
defer pm.mu.Unlock()
|
||||||
|
|
||||||
if _, exists := pm.ports[port]; !exists {
|
if _, exists := pm.ports[port]; !exists {
|
||||||
return fmt.Errorf("port %d is not in the allowed range", port)
|
return fmt.Errorf("port %d is not in the allowed range", port)
|
||||||
}
|
}
|
||||||
@ -70,6 +82,9 @@ func (pm *PortManager) SetPortStatus(port uint16, assigned bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pm *PortManager) GetPortStatus(port uint16) (bool, bool) {
|
func (pm *PortManager) GetPortStatus(port uint16) (bool, bool) {
|
||||||
|
pm.mu.RLock()
|
||||||
|
defer pm.mu.RUnlock()
|
||||||
|
|
||||||
status, exists := pm.ports[port]
|
status, exists := pm.ports[port]
|
||||||
return status, exists
|
return status, exists
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user