-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload_balancer.go
294 lines (231 loc) · 7.47 KB
/
load_balancer.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package scrimplb
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"log"
"sync"
"time"
"github.com/hashicorp/memberlist"
)
// LoadBalancerConfig describes configuration options specific to load balancers.
type LoadBalancerConfig struct {
PushPeriodRaw string `json:"push-period"`
PushJitterRaw string `json:"jitter"`
GeneratorType string `json:"generator"`
GeneratorTarget string `json:"generator-target"`
GeneratorPrintStdout bool `json:"generator-stdout"`
TLSChainLocation string `json:"tls-chain-location"`
TLSKeyLocation string `json:"tls-key-location"`
Generator Generator
PushPeriod time.Duration
PushJitter time.Duration
}
func initialiseLoadBalancerConfig(config *ScrimpConfig) error {
if config.LoadBalancerConfig == nil {
config.LoadBalancerConfig = &LoadBalancerConfig{
PushPeriodRaw: defaultPushPeriod,
PushJitterRaw: defaultPushJitter,
GeneratorType: "dummy",
GeneratorTarget: "",
GeneratorPrintStdout: false,
}
} else {
if config.LoadBalancerConfig.PushPeriodRaw == "" {
config.LoadBalancerConfig.PushPeriodRaw = defaultPushPeriod
}
if config.LoadBalancerConfig.PushJitterRaw == "" {
config.LoadBalancerConfig.PushJitterRaw = defaultPushJitter
}
if config.LoadBalancerConfig.GeneratorType == "" {
config.LoadBalancerConfig.GeneratorType = "dummy"
}
if config.LoadBalancerConfig.TLSChainLocation == "" {
config.LoadBalancerConfig.TLSChainLocation = defaultTLSChainLocation
}
if config.LoadBalancerConfig.TLSKeyLocation == "" {
config.LoadBalancerConfig.TLSKeyLocation = defaultTLSKeyLocation
}
}
pushPeriod, err := time.ParseDuration(config.LoadBalancerConfig.PushPeriodRaw)
if err != nil {
return fmt.Errorf("invalid push period for load balancer: %w", err)
}
config.LoadBalancerConfig.PushPeriod = pushPeriod
pushJitter, err := time.ParseDuration(config.LoadBalancerConfig.PushJitterRaw)
if err != nil {
return fmt.Errorf("invalid push jitter for load balancer: %w", err)
}
config.LoadBalancerConfig.PushJitter = pushJitter
switch config.LoadBalancerConfig.GeneratorType {
case "dummy":
config.LoadBalancerConfig.Generator = DummyGenerator{}
case "nginx":
config.LoadBalancerConfig.Generator = NginxGenerator{}
default:
err = fmt.Errorf("invalid generator type %s", config.LoadBalancerConfig.GeneratorType)
}
if err != nil {
return fmt.Errorf("couldn't create generator: %w", err)
}
return nil
}
// LoadBalancerDelegate listens for requests from backend instances for information and schedules replies
type LoadBalancerDelegate struct {
ch chan<- string
metadata []byte
}
// NewLoadBalancerDelegate creates a LoadBalancerDelegate from a channel which is used to receive work tasks
func NewLoadBalancerDelegate(ch chan<- string) (*LoadBalancerDelegate, error) {
rawMetadata := []byte(`{"type": "load-balancer"}`)
var buf bytes.Buffer
gzipWriter := gzip.NewWriter(&buf)
_, err := gzipWriter.Write(rawMetadata)
if err != nil {
return nil, fmt.Errorf("couldn't compress load balancer metadata: %w", err)
}
err = gzipWriter.Close()
if err != nil {
return nil, fmt.Errorf("couldn't close gzip writer: %w", err)
}
return &LoadBalancerDelegate{
ch,
buf.Bytes(),
}, nil
}
// NodeMeta returns metadata about this node
func (d *LoadBalancerDelegate) NodeMeta(limit int) []byte {
return d.metadata
}
// NotifyMsg receives messages from other cluster members. If the message was intended for a Load Balancer,
// it is processed and a reply is scheduled if needed.
func (d *LoadBalancerDelegate) NotifyMsg(msg []byte) {
fmt.Printf("%v\n", string(msg))
}
// GetBroadcasts is ignored for LoadBalancerDelegate
func (d *LoadBalancerDelegate) GetBroadcasts(overhead int, limit int) [][]byte {
return nil
}
// LocalState is ignored for LoadBalancerDelegate
func (d *LoadBalancerDelegate) LocalState(join bool) []byte {
return nil
}
// MergeRemoteState is ignored for LoadBalancerDelegate
func (d *LoadBalancerDelegate) MergeRemoteState(buf []byte, join bool) {
}
// LoadBalancerState provides state which is maintained by a load balancer
// relating to the nodes in the cluster that it might forward on to.
type LoadBalancerState struct {
MemberMap map[Upstream][]Application
memberLock sync.RWMutex
}
// NewLoadBalancerState creates a load balancer state
func NewLoadBalancerState() LoadBalancerState {
return LoadBalancerState{
make(map[Upstream][]Application),
sync.RWMutex{},
}
}
// LoadBalancerEventDelegate listens for events and updates load balancer state
// based on node metadata
type LoadBalancerEventDelegate struct {
State LoadBalancerState
UpstreamNotificationChannel chan<- *LoadBalancerState
}
// NewLoadBalancerEventDelegate creates a new LoadBalancerEventDelegate
func NewLoadBalancerEventDelegate(notificationChannel chan<- *LoadBalancerState) LoadBalancerEventDelegate {
return LoadBalancerEventDelegate{
State: NewLoadBalancerState(),
UpstreamNotificationChannel: notificationChannel,
}
}
func parseMetadata(node *memberlist.Node) (*BackendMetadata, error) {
buf := bytes.NewReader(node.Meta)
gzipReader, err := gzip.NewReader(buf)
if err != nil {
return nil, fmt.Errorf("couldn't create gzip reader: %w", err)
}
var rawMetadata bytes.Buffer
metadataWriter := bufio.NewWriter(&rawMetadata)
_, err = io.Copy(metadataWriter, gzipReader)
if err != nil {
return nil, fmt.Errorf("couldn't copy from gzip reader: %w", err)
}
err = gzipReader.Close()
if err != nil {
return nil, fmt.Errorf("couldn't close gzip reader: %w", err)
}
var otherMeta BackendMetadata
err = json.Unmarshal(rawMetadata.Bytes(), &otherMeta)
if err != nil {
return nil, err
}
return &otherMeta, nil
}
// NotifyJoin adds new nodes to load balancer state
func (d *LoadBalancerEventDelegate) NotifyJoin(node *memberlist.Node) {
d.State.memberLock.Lock()
defer d.State.memberLock.Unlock()
otherMeta, err := parseMetadata(node)
if err != nil {
log.Printf("couldn't parse node metadata: %v", err)
return
}
if otherMeta.Type == "backend" {
key := Upstream{
node.Name,
node.Addr.String(),
}
var apps []Application
for _, v := range otherMeta.Applications {
apps = append(apps, v.ToApplication())
}
delete(d.State.MemberMap, key)
d.State.MemberMap[key] = apps
d.UpstreamNotificationChannel <- &d.State
}
}
// NotifyLeave removes existing nodes from load balancer state
func (d *LoadBalancerEventDelegate) NotifyLeave(node *memberlist.Node) {
d.State.memberLock.Lock()
defer d.State.memberLock.Unlock()
otherMeta, err := parseMetadata(node)
if err != nil {
log.Printf("couldn't parse node metadata: %v", err)
return
}
if otherMeta.Type == "backend" {
key := Upstream{
node.Name,
node.Addr.String(),
}
delete(d.State.MemberMap, key)
d.UpstreamNotificationChannel <- &d.State
}
}
// NotifyUpdate updates existing nodes in load balancer state
func (d *LoadBalancerEventDelegate) NotifyUpdate(node *memberlist.Node) {
d.State.memberLock.Lock()
defer d.State.memberLock.Unlock()
otherMeta, err := parseMetadata(node)
if err != nil {
log.Printf("couldn't parse node metadata: %v", err)
return
}
if otherMeta.Type == "backend" {
key := Upstream{
node.Name,
node.Addr.String(),
}
var apps []Application
for _, v := range otherMeta.Applications {
apps = append(apps, v.ToApplication())
}
delete(d.State.MemberMap, key)
d.State.MemberMap[key] = apps
d.UpstreamNotificationChannel <- &d.State
}
}