address.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package allregions
  2. // Region contains cloudflared edge addresses. The edge is partitioned into several regions for
  3. // redundancy purposes.
  4. type AddrSet map[*EdgeAddr]UsedBy
  5. // AddrUsedBy finds the address used by the given connection in this region.
  6. // Returns nil if the connection isn't using any IP.
  7. func (a AddrSet) AddrUsedBy(connID int) *EdgeAddr {
  8. for addr, used := range a {
  9. if used.Used && used.ConnID == connID {
  10. return addr
  11. }
  12. }
  13. return nil
  14. }
  15. // AvailableAddrs counts how many unused addresses this region contains.
  16. func (a AddrSet) AvailableAddrs() int {
  17. n := 0
  18. for _, usedby := range a {
  19. if !usedby.Used {
  20. n++
  21. }
  22. }
  23. return n
  24. }
  25. // GetUnusedIP returns a random unused address in this region.
  26. // Returns nil if all addresses are in use.
  27. func (a AddrSet) GetUnusedIP(excluding *EdgeAddr) *EdgeAddr {
  28. for addr, usedby := range a {
  29. if !usedby.Used && addr != excluding {
  30. return addr
  31. }
  32. }
  33. return nil
  34. }
  35. // Use the address, assigning it to a proxy connection.
  36. func (a AddrSet) Use(addr *EdgeAddr, connID int) {
  37. if addr == nil {
  38. return
  39. }
  40. a[addr] = InUse(connID)
  41. }
  42. // GetAnyAddress returns an arbitrary address from the region.
  43. func (a AddrSet) GetAnyAddress() *EdgeAddr {
  44. for addr := range a {
  45. return addr
  46. }
  47. return nil
  48. }
  49. // GiveBack the address, ensuring it is no longer assigned to an IP.
  50. // Returns true if the address is in this region.
  51. func (a AddrSet) GiveBack(addr *EdgeAddr) (ok bool) {
  52. if _, ok := a[addr]; !ok {
  53. return false
  54. }
  55. a[addr] = Unused()
  56. return true
  57. }