-
Notifications
You must be signed in to change notification settings - Fork 4
/
lb.go
77 lines (62 loc) · 1.56 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
package main
import (
"github.com/joa/jawlb/internal/atomic"
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
rr int64
}
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)
offset := int(atomic.IncWrapInt64(&l.rr))
for {
select {
case <-req.Context().Done():
return nil
case msg := <-ch:
servers := convertServerList(msg, offset)
err := req.Send(&grpclb.LoadBalanceResponse{
LoadBalanceResponseType: &grpclb.LoadBalanceResponse_ServerList{
ServerList: &grpclb.ServerList{
Servers: servers,
},
},
})
if err != nil {
return err
}
}
}
}
func convertServerList(l ServerList, offset int) []*grpclb.Server {
var servers []*grpclb.Server
n := len(l)
for i := 0; i < n; i++ {
server := l[(i+offset)%n]
servers = append(servers, convertServer(server))
}
return servers
}
func convertServer(s Server) *grpclb.Server {
return &grpclb.Server{IpAddress: s.IP, Port: s.Port}
}