forked from panjf2000/gnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load_balancing.go
230 lines (195 loc) · 6.42 KB
/
load_balancing.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Copyright (c) 2019 Andy Pan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package gnet
import (
"container/heap"
"sync"
"sync/atomic"
)
// LoadBalancing represents the the type of load-balancing algorithm.
type LoadBalancing int
const (
// RoundRobin assigns the next accepted connection to the event-loop by polling event-loop list.
RoundRobin LoadBalancing = iota
// LeastConnections assigns the next accepted connection to the event-loop that is
// serving the least number of active connections at the current time.
LeastConnections
// SourceAddrHash assignes the next accepted connection to the event-loop by hashing socket fd.
SourceAddrHash
)
type (
// loadBalancer is a interface which manipulates the event-loop set.
loadBalancer interface {
register(*eventloop)
next(int) *eventloop
iterate(func(int, *eventloop) bool)
len() int
calibrate(*eventloop, int32)
}
// roundRobinEventLoopSet with Round-Robin algorithm.
roundRobinEventLoopSet struct {
nextLoopIndex int
eventLoops []*eventloop
size int
}
// leastConnectionsEventLoopSet with Least-Connections algorithm.
leastConnectionsEventLoopSet struct {
sync.RWMutex
minHeap minEventLoopHeap
cachedRoot *eventloop
threshold int32
calibrateConnsThreshold int32
}
// sourceAddrHashEventLoopSet with Hash algorithm.
sourceAddrHashEventLoopSet struct {
eventLoops []*eventloop
size int
}
)
// ==================================== Implementation of Round-Robin load-balancer ====================================
func (set *roundRobinEventLoopSet) register(el *eventloop) {
el.idx = set.size
set.eventLoops = append(set.eventLoops, el)
set.size++
}
// next returns the eligible event-loop based on Round-Robin algorithm.
func (set *roundRobinEventLoopSet) next(_ int) (el *eventloop) {
el = set.eventLoops[set.nextLoopIndex]
if set.nextLoopIndex++; set.nextLoopIndex >= set.size {
set.nextLoopIndex = 0
}
return
}
func (set *roundRobinEventLoopSet) iterate(f func(int, *eventloop) bool) {
for i, el := range set.eventLoops {
if !f(i, el) {
break
}
}
}
func (set *roundRobinEventLoopSet) len() int {
return set.size
}
func (set *roundRobinEventLoopSet) calibrate(el *eventloop, delta int32) {
atomic.AddInt32(&el.connCount, delta)
}
// ================================= Implementation of Least-Connections load-balancer =================================
// Leverage min-heap to optimize Least-Connections load-balancing.
type minEventLoopHeap []*eventloop
// Implement heap.Interface: Len, Less, Swap, Push, Pop.
func (h minEventLoopHeap) Len() int {
return len(h)
}
func (h minEventLoopHeap) Less(i, j int) bool {
// return (*h)[i].loadConnCount() < (*h)[j].loadConnCount()
return h[i].connCount < h[j].connCount
}
func (h minEventLoopHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].idx, h[j].idx = i, j
}
func (h *minEventLoopHeap) Push(x interface{}) {
el := x.(*eventloop)
el.idx = len(*h)
*h = append(*h, el)
}
func (h *minEventLoopHeap) Pop() interface{} {
old := *h
i := len(old) - 1
x := old[i]
old[i] = nil // avoid memory leak
x.idx = -1 // for safety
*h = old[:i]
return x
}
func (set *leastConnectionsEventLoopSet) register(el *eventloop) {
set.Lock()
heap.Push(&set.minHeap, el)
if el.idx == 0 {
set.cachedRoot = el
}
set.calibrateConnsThreshold = int32(set.minHeap.Len())
set.Unlock()
}
// next returns the eligible event-loop by taking the root node from minimum heap based on Least-Connections algorithm.
func (set *leastConnectionsEventLoopSet) next(_ int) (el *eventloop) {
// set.RLock()
// el = set.minHeap[0]
// set.RUnlock()
// return
// In most cases, `next` method returns the cached event-loop immediately and it only reconstructs the minimum heap
// every `calibrateConnsThreshold` times for reducing locks to global mutex.
if atomic.LoadInt32(&set.threshold) >= set.calibrateConnsThreshold {
set.Lock()
heap.Init(&set.minHeap)
set.cachedRoot = set.minHeap[0]
atomic.StoreInt32(&set.threshold, 0)
set.Unlock()
}
return set.cachedRoot
}
func (set *leastConnectionsEventLoopSet) iterate(f func(int, *eventloop) bool) {
set.RLock()
for i, el := range set.minHeap {
if !f(i, el) {
break
}
}
set.RUnlock()
}
func (set *leastConnectionsEventLoopSet) len() (size int) {
set.RLock()
size = set.minHeap.Len()
set.RUnlock()
return
}
func (set *leastConnectionsEventLoopSet) calibrate(el *eventloop, delta int32) {
// set.Lock()
// el.connCount += delta
// heap.Fix(&set.minHeap, el.idx)
// set.Unlock()
set.RLock()
atomic.AddInt32(&el.connCount, delta)
atomic.AddInt32(&set.threshold, 1)
set.RUnlock()
}
// ======================================= Implementation of Hash load-balancer ========================================
func (set *sourceAddrHashEventLoopSet) register(el *eventloop) {
el.idx = set.size
set.eventLoops = append(set.eventLoops, el)
set.size++
}
// next returns the eligible event-loop by taking the remainder of a given fd as the index of event-loop list.
func (set *sourceAddrHashEventLoopSet) next(hashCode int) *eventloop {
return set.eventLoops[hashCode%set.size]
}
func (set *sourceAddrHashEventLoopSet) iterate(f func(int, *eventloop) bool) {
for i, el := range set.eventLoops {
if !f(i, el) {
break
}
}
}
func (set *sourceAddrHashEventLoopSet) len() int {
return set.size
}
func (set *sourceAddrHashEventLoopSet) calibrate(el *eventloop, delta int32) {
atomic.AddInt32(&el.connCount, delta)
}