mirror of
https://github.com/fatedier/frp.git
synced 2026-01-11 22:23:12 +00:00
add e2e tests (#2334)
This commit is contained in:
@@ -3,6 +3,7 @@ package port
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
)
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
type Allocator struct {
|
||||
reserved sets.Int
|
||||
used sets.Int
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewAllocator return a port allocator for testing.
|
||||
@@ -29,8 +31,27 @@ func NewAllocator(from int, to int, mod int, index int) *Allocator {
|
||||
}
|
||||
|
||||
func (pa *Allocator) Get() int {
|
||||
return pa.GetByName("")
|
||||
}
|
||||
|
||||
func (pa *Allocator) GetByName(portName string) int {
|
||||
var builder *nameBuilder
|
||||
if portName == "" {
|
||||
builder = &nameBuilder{}
|
||||
} else {
|
||||
var err error
|
||||
builder, err = unmarshalFromName(portName)
|
||||
if err != nil {
|
||||
fmt.Println(err, portName)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
pa.mu.Lock()
|
||||
defer pa.mu.Unlock()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
port, _ := pa.reserved.PopAny()
|
||||
port := pa.getByRange(builder.rangePortFrom, builder.rangePortTo)
|
||||
if port == 0 {
|
||||
return 0
|
||||
}
|
||||
@@ -43,13 +64,49 @@ func (pa *Allocator) Get() int {
|
||||
continue
|
||||
}
|
||||
l.Close()
|
||||
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
// Maybe not controlled by us, mark it used.
|
||||
pa.used.Insert(port)
|
||||
continue
|
||||
}
|
||||
udpConn.Close()
|
||||
|
||||
pa.used.Insert(port)
|
||||
return port
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (pa *Allocator) getByRange(from, to int) int {
|
||||
if from <= 0 {
|
||||
port, _ := pa.reserved.PopAny()
|
||||
return port
|
||||
}
|
||||
|
||||
// choose a random port between from - to
|
||||
ports := pa.reserved.UnsortedList()
|
||||
for _, port := range ports {
|
||||
if port >= from && port <= to {
|
||||
return port
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (pa *Allocator) Release(port int) {
|
||||
if port <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
pa.mu.Lock()
|
||||
defer pa.mu.Unlock()
|
||||
|
||||
if pa.used.Has(port) {
|
||||
pa.used.Delete(port)
|
||||
pa.reserved.Insert(port)
|
||||
|
||||
Reference in New Issue
Block a user