port.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. // TODO: Distinguish between TCP and UDP
  51. l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", 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", fmt.Sprintf("127.0.0.1:%d", 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. }