1
0

port.go 2.1 KB

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