port.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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.Int
  11. used sets.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.NewInt(),
  20. used: sets.NewInt(),
  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("127.0.0.1", 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("127.0.0.1", 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. return port
  71. }
  72. return 0
  73. }
  74. func (pa *Allocator) getByRange(from, to int) int {
  75. if from <= 0 {
  76. port, _ := pa.reserved.PopAny()
  77. return port
  78. }
  79. // choose a random port between from - to
  80. ports := pa.reserved.UnsortedList()
  81. for _, port := range ports {
  82. if port >= from && port <= to {
  83. return port
  84. }
  85. }
  86. return 0
  87. }
  88. func (pa *Allocator) Release(port int) {
  89. if port <= 0 {
  90. return
  91. }
  92. pa.mu.Lock()
  93. defer pa.mu.Unlock()
  94. if pa.used.Has(port) {
  95. pa.used.Delete(port)
  96. pa.reserved.Insert(port)
  97. }
  98. }