-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
selector.go
130 lines (105 loc) · 2.34 KB
/
selector.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// Copyright © by Jeff Foley 2022-2024. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// SPDX-License-Identifier: Apache-2.0
package resolve
import (
"math/rand"
"sync"
)
type selector interface {
// GetResolver returns a resolver managed by the selector.
GetResolver() *resolver
// LookupResolver returns the resolver with the matching address.
LookupResolver(addr string) *resolver
// AddResolver adds a resolver to the selector pool.
AddResolver(res *resolver)
// AllResolvers returns all the resolver objects currently managed by the selector.
AllResolvers() []*resolver
// Len returns the number of resolver objects currently managed by the selector.
Len() int
// Close releases all resources allocated by the selector.
Close()
}
type randomSelector struct {
sync.Mutex
list []*resolver
lookup map[string]*resolver
}
func newRandomSelector() *randomSelector {
return &randomSelector{lookup: make(map[string]*resolver)}
}
// GetResolver performs random selection on the pool of resolvers.
func (r *randomSelector) GetResolver() *resolver {
r.Lock()
defer r.Unlock()
if l := len(r.list); l == 0 {
return nil
} else if l == 1 {
return r.list[0]
}
var chosen *resolver
sel := rand.Intn(len(r.list))
loop:
for _, res := range r.list[sel:] {
select {
case <-res.done:
continue loop
default:
}
chosen = res
break
}
return chosen
}
func (r *randomSelector) LookupResolver(addr string) *resolver {
r.Lock()
defer r.Unlock()
return r.lookup[addr]
}
func (r *randomSelector) AddResolver(res *resolver) {
r.Lock()
defer r.Unlock()
if _, found := r.lookup[res.address.IP.String()]; !found {
r.list = append(r.list, res)
r.lookup[res.address.IP.String()] = res
}
}
func (r *randomSelector) AllResolvers() []*resolver {
r.Lock()
defer r.Unlock()
var active []*resolver
for _, res := range r.list {
select {
case <-res.done:
default:
active = append(active, res)
}
}
return active
}
func (r *randomSelector) Len() int {
r.Lock()
defer r.Unlock()
var count int
for _, res := range r.list {
select {
case <-res.done:
default:
count++
}
}
return count
}
func (r *randomSelector) Close() {
r.Lock()
defer r.Unlock()
r.list = nil
r.lookup = nil
}
func min(x, y int) int {
m := x
if y < m {
m = y
}
return m
}