| 9 | "k8s.io/apimachinery/pkg/util/sets" |
| 10 | ) |
| 11 |
| 12 | type Allocator struct { |
| 13 | reserved sets.Set[int] |
| 14 | used sets.Set[int] |
| 15 | mu sync.Mutex |
| 16 | } |
| 17 |
| 18 | // NewAllocator return a port allocator for testing. |
| 19 | // Example: from: 10, to: 20, mod 4, index 1 |
| 20 | // Reserved ports: 13, 17 |
| 21 | func NewAllocator(from int, to int, mod int, index int) *Allocator { |
| 22 | pa := &Allocator{ |
| 23 | reserved: sets.New[int](), |
| 24 | used: sets.New[int](), |
| 25 | } |
| 26 |
| 27 | for i := from; i <= to; i++ { |
| 28 | if i%mod == index { |
| 29 | pa.reserved.Insert(i) |
| 30 | } |
| 31 | } |
| 32 | return pa |
| 33 | } |
| 34 |
| 35 | func (pa *Allocator) Get() int { |
| 36 | return pa.GetByName("") |
| 37 | } |
| 38 |
| 39 | func (pa *Allocator) GetByName(portName string) int { |
| 40 | var builder *nameBuilder |
| 41 | if portName == "" { |
| 42 | builder = &nameBuilder{} |
| 43 | } else { |
| 44 | var err error |
| 45 | builder, err = unmarshalFromName(portName) |
| 46 | if err != nil { |
| 47 | fmt.Println(err, portName) |
| 48 | return 0 |
| 49 | } |
| 50 | } |
| 51 |
| 52 | pa.mu.Lock() |
| 53 | defer pa.mu.Unlock() |
| 54 |
| 55 | for range 20 { |
| 56 | port := pa.getByRange(builder.rangePortFrom, builder.rangePortTo) |
| 57 | if port == 0 { |
| 58 | return 0 |
| 59 | } |
| 60 |
| 61 | l, err := net.Listen("tcp", net.JoinHostPort("0.0.0.0", strconv.Itoa(port))) |
| 62 | if err != nil { |
| 63 | // Maybe not controlled by us, mark it used. |
| 64 | pa.used.Insert(port) |
| 65 | continue |
| 66 | } |
| 67 | l.Close() |
| 68 |
| 69 | udpAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort("0.0.0.0", strconv.Itoa(port))) |
| 70 | if err != nil { |
| 71 | continue |
| 72 | } |
| 73 | udpConn, err := net.ListenUDP("udp", udpAddr) |
| 74 | if err != nil { |
| 75 | // Maybe not controlled by us, mark it used. |
| 76 | pa.used.Insert(port) |
| 77 | continue |
| 78 | } |
| 79 | udpConn.Close() |
| 80 |
| 81 | pa.used.Insert(port) |
| 82 | pa.reserved.Delete(port) |
| 83 | return port |
| 84 | } |
| 85 | return 0 |
| 86 | } |
| 87 |
| 88 | func (pa *Allocator) getByRange(from, to int) int { |
| 89 | if from <= 0 { |
| 90 | port, _ := pa.reserved.PopAny() |
| 91 | return port |
| 92 | } |
| 93 |
| 94 | // choose a random port between from - to |
| 95 | ports := pa.reserved.UnsortedList() |
| 96 | for _, port := range ports { |
| 97 | if port >= from && port <= to { |
| 98 | return port |
| 99 | } |
| 100 | } |
| 101 | return 0 |
| 102 | } |
| 103 |
| 104 | func (pa *Allocator) Release(port int) { |
| 105 | if port <= 0 { |
| 106 | return |
| 107 | } |
| 108 |
| 109 | pa.mu.Lock() |
| 110 | defer pa.mu.Unlock() |
| 111 |
| 112 | if pa.used.Has(port) { |
| 113 | pa.used.Delete(port) |
| 114 | pa.reserved.Insert(port) |
| 115 | } |
| 116 | } |