forked from abh/geodns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
picker.go
68 lines (51 loc) · 1.18 KB
/
picker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"math/rand"
"github.com/miekg/dns"
)
func (label *Label) Picker(qtype uint16, max int) Records {
if qtype == dns.TypeANY {
var result []Record
for rtype := range label.Records {
rtypeRecords := label.Picker(rtype, max)
tmpResult := make(Records, len(result)+len(rtypeRecords))
copy(tmpResult, result)
copy(tmpResult[len(result):], rtypeRecords)
result = tmpResult
}
return result
}
if labelRR := label.Records[qtype]; labelRR != nil {
// not "balanced", just return all
if label.Weight[qtype] == 0 {
return labelRR
}
if qtype == dns.TypeCNAME || qtype == dns.TypeMF {
max = 1
}
rrCount := len(labelRR)
if max > rrCount {
max = rrCount
}
servers := make([]Record, len(labelRR))
copy(servers, labelRR)
result := make([]Record, max)
sum := label.Weight[qtype]
for si := 0; si < max; si++ {
n := rand.Intn(sum + 1)
s := 0
for i := range servers {
s += int(servers[i].Weight)
if s >= n {
sum -= servers[i].Weight
result[si] = servers[i]
// remove the server from the list
servers = append(servers[:i], servers[i+1:]...)
break
}
}
}
return result
}
return nil
}