-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclient_dns.go
112 lines (87 loc) · 1.89 KB
/
client_dns.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package resolvermt
import (
"sync/atomic"
"time"
)
type question struct {
question string
rrtype RRtype
channel chan []Record
}
type clientDNS struct {
resolver resolver
maxConcurrency int
queryChan chan question
queryCount int32
}
type resolver interface {
Resolve(query string, rrtype RRtype) []Record
Close()
}
func newClientDNS(resolver resolver, maxConcurrency int) *clientDNS {
client := clientDNS{
resolver: resolver,
maxConcurrency: maxConcurrency,
}
client.startThreads()
return &client
}
func (s *clientDNS) startThreads() {
s.queryChan = make(chan question, s.maxConcurrency)
for i := 0; i < s.maxConcurrency; i++ {
go func(queryChan chan question) {
for {
query, open := <-queryChan
if !open {
return
}
results := s.resolver.Resolve(query.question, query.rrtype)
query.channel <- results
}
}(s.queryChan)
}
}
func (s *clientDNS) Resolve(queries []string, rrtype RRtype) []Record {
records := []Record{}
queryCount := len(queries)
if queryCount == 0 {
return records
}
// Start result reader
var received int32
resultChan := make(chan []Record, s.maxConcurrency)
go func(resultChan chan []Record) {
for {
response, open := <-resultChan
if !open {
return
}
records = append(records, response...)
atomic.AddInt32(&received, 1)
}
}(resultChan)
// Send work to goroutines
for _, query := range queries {
question := question{
question: query,
rrtype: rrtype,
channel: resultChan,
}
s.queryChan <- question
}
// Wait for results
for int(atomic.LoadInt32(&received)) < queryCount {
time.Sleep(1 * time.Millisecond)
}
// Work done
close(resultChan)
atomic.AddInt32(&s.queryCount, int32(queryCount))
return records
}
func (s *clientDNS) QueryCount() int {
return int(atomic.LoadInt32(&s.queryCount))
}
func (s *clientDNS) Close() {
close(s.queryChan)
s.resolver.Close()
}