port.go 2.0 KB

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