gateway.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package routing
  2. import (
  3. "fmt"
  4. "net/netip"
  5. )
  6. const (
  7. // Sentinal value
  8. BucketNotCalculated = -1
  9. )
  10. type Gateways []Gateway
  11. func (g Gateways) String() string {
  12. str := ""
  13. for i, gw := range g {
  14. str += gw.String()
  15. if i < len(g)-1 {
  16. str += ", "
  17. }
  18. }
  19. return str
  20. }
  21. type Gateway struct {
  22. addr netip.Addr
  23. weight int
  24. bucketUpperBound int
  25. }
  26. func NewGateway(addr netip.Addr, weight int) Gateway {
  27. return Gateway{addr: addr, weight: weight, bucketUpperBound: BucketNotCalculated}
  28. }
  29. func (g *Gateway) BucketUpperBound() int {
  30. return g.bucketUpperBound
  31. }
  32. func (g *Gateway) Addr() netip.Addr {
  33. return g.addr
  34. }
  35. func (g *Gateway) String() string {
  36. return fmt.Sprintf("{addr: %s, weight: %d}", g.addr, g.weight)
  37. }
  38. // Divide and round to nearest integer
  39. func divideAndRound(v uint64, d uint64) uint64 {
  40. var tmp uint64 = v + d/2
  41. return tmp / d
  42. }
  43. // Implements Hash-Threshold mapping, equivalent to the implementation in the linux kernel.
  44. // After this function returns each gateway will have a
  45. // positive bucketUpperBound with a maximum value of 2147483647 (INT_MAX)
  46. func CalculateBucketsForGateways(gateways []Gateway) {
  47. var totalWeight int = 0
  48. for i := range gateways {
  49. totalWeight += gateways[i].weight
  50. }
  51. var loopWeight int = 0
  52. for i := range gateways {
  53. loopWeight += gateways[i].weight
  54. gateways[i].bucketUpperBound = int(divideAndRound(uint64(loopWeight)<<31, uint64(totalWeight))) - 1
  55. }
  56. }