This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lb.go
81 lines (67 loc) · 1.58 KB
/
lb.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
package main
import (
"math/rand"
"time"
grpclb "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type lb struct {
b *broadcast
max int
}
func (l *lb) BalanceLoad(req grpclb.LoadBalancer_BalanceLoadServer) error {
if in, err := req.Recv(); err != nil {
return err
} else if init := in.GetInitialRequest(); init != nil {
err := req.Send(&grpclb.LoadBalanceResponse{
LoadBalanceResponseType: &grpclb.LoadBalanceResponse_InitialResponse{
InitialResponse: &grpclb.InitialLoadBalanceResponse{},
},
})
if err != nil {
return err
}
} else {
return status.Error(codes.InvalidArgument, "expected initial request")
}
ch := make(chan ServerList)
defer close(ch)
l.b.addListener(ch)
defer l.b.remListener(ch)
for {
select {
case <-req.Context().Done():
return nil
case msg := <-ch:
servers := convertServerList(msg, l.max)
err := req.Send(&grpclb.LoadBalanceResponse{
LoadBalanceResponseType: &grpclb.LoadBalanceResponse_ServerList{
ServerList: &grpclb.ServerList{
Servers: servers,
},
},
})
if err != nil {
return err
}
}
}
}
func convertServerList(l ServerList, max int) []*grpclb.Server {
n := len(l)
if max > n || max == 0 {
max = n
}
servers := make([]*grpclb.Server, max)
rand.Seed(time.Now().UnixNano())
for i := 0; i < max; i++ {
j := rand.Intn(n-i) + i
l[i], l[j] = l[j], l[i]
servers[i] = convertServer(l[i])
}
return servers
}
func convertServer(s Server) *grpclb.Server {
return &grpclb.Server{IpAddress: s.IP, Port: s.Port}
}