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