Skip to content

Commit c73e016

Browse files
authored
Update grpclb proto and move grpclb into package grpc (#1186)
1 parent 38df39b commit c73e016

File tree

5 files changed

+481
-248
lines changed

5 files changed

+481
-248
lines changed

grpclb/grpclb.go renamed to grpclb.go

Lines changed: 83 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,7 @@
3131
*
3232
*/
3333

34-
// Package grpclb implements the load balancing protocol defined at
35-
// https://github.com/grpc/grpc/blob/master/doc/load-balancing.md.
36-
// The implementation is currently EXPERIMENTAL.
37-
package grpclb
34+
package grpc
3835

3936
import (
4037
"errors"
@@ -45,14 +42,50 @@ import (
4542
"time"
4643

4744
"golang.org/x/net/context"
48-
"google.golang.org/grpc"
4945
"google.golang.org/grpc/codes"
5046
lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1"
5147
"google.golang.org/grpc/grpclog"
5248
"google.golang.org/grpc/metadata"
5349
"google.golang.org/grpc/naming"
5450
)
5551

52+
// Client API for LoadBalancer service.
53+
// Mostly copied from generated pb.go file.
54+
// To avoid circular dependency.
55+
type loadBalancerClient struct {
56+
cc *ClientConn
57+
}
58+
59+
func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...CallOption) (*balanceLoadClientStream, error) {
60+
desc := &StreamDesc{
61+
StreamName: "BalanceLoad",
62+
ServerStreams: true,
63+
ClientStreams: true,
64+
}
65+
stream, err := NewClientStream(ctx, desc, c.cc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...)
66+
if err != nil {
67+
return nil, err
68+
}
69+
x := &balanceLoadClientStream{stream}
70+
return x, nil
71+
}
72+
73+
type balanceLoadClientStream struct {
74+
ClientStream
75+
}
76+
77+
func (x *balanceLoadClientStream) Send(m *lbpb.LoadBalanceRequest) error {
78+
return x.ClientStream.SendMsg(m)
79+
}
80+
81+
func (x *balanceLoadClientStream) Recv() (*lbpb.LoadBalanceResponse, error) {
82+
m := new(lbpb.LoadBalanceResponse)
83+
if err := x.ClientStream.RecvMsg(m); err != nil {
84+
return nil, err
85+
}
86+
return m, nil
87+
}
88+
5689
// AddressType indicates the address type returned by name resolution.
5790
type AddressType uint8
5891

@@ -63,18 +96,18 @@ const (
6396
GRPCLB
6497
)
6598

66-
// Metadata contains the information the name resolution for grpclb should provide. The
99+
// AddrMetadataGRPCLB contains the information the name resolution for grpclb should provide. The
67100
// name resolver used by grpclb balancer is required to provide this type of metadata in
68101
// its address updates.
69-
type Metadata struct {
102+
type AddrMetadataGRPCLB struct {
70103
// AddrType is the type of server (grpc load balancer or backend).
71104
AddrType AddressType
72105
// ServerName is the name of the grpc load balancer. Used for authentication.
73106
ServerName string
74107
}
75108

76-
// Balancer creates a grpclb load balancer.
77-
func Balancer(r naming.Resolver) grpc.Balancer {
109+
// NewGRPCLBBalancer creates a grpclb load balancer.
110+
func NewGRPCLBBalancer(r naming.Resolver) Balancer {
78111
return &balancer{
79112
r: r,
80113
}
@@ -86,13 +119,16 @@ type remoteBalancerInfo struct {
86119
name string
87120
}
88121

89-
// addrInfo consists of the information of a backend server.
90-
type addrInfo struct {
91-
addr grpc.Address
122+
// grpclbAddrInfo consists of the information of a backend server.
123+
type grpclbAddrInfo struct {
124+
addr Address
92125
connected bool
93-
// dropRequest indicates whether a particular RPC which chooses this address
94-
// should be dropped.
95-
dropRequest bool
126+
// dropForRateLimiting indicates whether this particular request should be
127+
// dropped by the client for rate limiting.
128+
dropForRateLimiting bool
129+
// dropForLoadBalancing indicates whether this particular request should be
130+
// dropped by the client for load balancing.
131+
dropForLoadBalancing bool
96132
}
97133

98134
type balancer struct {
@@ -101,9 +137,9 @@ type balancer struct {
101137
mu sync.Mutex
102138
seq int // a sequence number to make sure addrCh does not get stale addresses.
103139
w naming.Watcher
104-
addrCh chan []grpc.Address
140+
addrCh chan []Address
105141
rbs []remoteBalancerInfo
106-
addrs []*addrInfo
142+
addrs []*grpclbAddrInfo
107143
next int
108144
waitCh chan struct{}
109145
done bool
@@ -119,7 +155,7 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn
119155
b.mu.Lock()
120156
defer b.mu.Unlock()
121157
if b.done {
122-
return grpc.ErrClientConnClosing
158+
return ErrClientConnClosing
123159
}
124160
for _, update := range updates {
125161
switch update.Op {
@@ -135,7 +171,7 @@ func (b *balancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerIn
135171
if exist {
136172
continue
137173
}
138-
md, ok := update.Metadata.(*Metadata)
174+
md, ok := update.Metadata.(*AddrMetadataGRPCLB)
139175
if !ok {
140176
// TODO: Revisit the handling here and may introduce some fallback mechanism.
141177
grpclog.Printf("The name resolution contains unexpected metadata %v", update.Metadata)
@@ -206,18 +242,19 @@ func (b *balancer) processServerList(l *lbpb.ServerList, seq int) {
206242
servers := l.GetServers()
207243
expiration := convertDuration(l.GetExpirationInterval())
208244
var (
209-
sl []*addrInfo
210-
addrs []grpc.Address
245+
sl []*grpclbAddrInfo
246+
addrs []Address
211247
)
212248
for _, s := range servers {
213249
md := metadata.Pairs("lb-token", s.LoadBalanceToken)
214-
addr := grpc.Address{
250+
addr := Address{
215251
Addr: fmt.Sprintf("%s:%d", net.IP(s.IpAddress), s.Port),
216252
Metadata: &md,
217253
}
218-
sl = append(sl, &addrInfo{
219-
addr: addr,
220-
dropRequest: s.DropRequest,
254+
sl = append(sl, &grpclbAddrInfo{
255+
addr: addr,
256+
dropForRateLimiting: s.DropForRateLimiting,
257+
dropForLoadBalancing: s.DropForLoadBalancing,
221258
})
222259
addrs = append(addrs, addr)
223260
}
@@ -244,7 +281,7 @@ func (b *balancer) processServerList(l *lbpb.ServerList, seq int) {
244281
return
245282
}
246283

247-
func (b *balancer) callRemoteBalancer(lbc lbpb.LoadBalancerClient, seq int) (retry bool) {
284+
func (b *balancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry bool) {
248285
ctx, cancel := context.WithCancel(context.Background())
249286
defer cancel()
250287
stream, err := lbc.BalanceLoad(ctx)
@@ -306,7 +343,7 @@ func (b *balancer) callRemoteBalancer(lbc lbpb.LoadBalancerClient, seq int) (ret
306343
return true
307344
}
308345

309-
func (b *balancer) Start(target string, config grpc.BalancerConfig) error {
346+
func (b *balancer) Start(target string, config BalancerConfig) error {
310347
b.rand = rand.New(rand.NewSource(time.Now().Unix()))
311348
// TODO: Fall back to the basic direct connection if there is no name resolver.
312349
if b.r == nil {
@@ -316,9 +353,9 @@ func (b *balancer) Start(target string, config grpc.BalancerConfig) error {
316353
b.mu.Lock()
317354
if b.done {
318355
b.mu.Unlock()
319-
return grpc.ErrClientConnClosing
356+
return ErrClientConnClosing
320357
}
321-
b.addrCh = make(chan []grpc.Address)
358+
b.addrCh = make(chan []Address)
322359
w, err := b.r.Resolve(target)
323360
if err != nil {
324361
b.mu.Unlock()
@@ -340,7 +377,7 @@ func (b *balancer) Start(target string, config grpc.BalancerConfig) error {
340377
// Spawn a goroutine to talk to the remote load balancer.
341378
go func() {
342379
var (
343-
cc *grpc.ClientConn
380+
cc *ClientConn
344381
// ccError is closed when there is an error in the current cc.
345382
// A new rb should be picked from rbs and connected.
346383
ccError chan struct{}
@@ -419,15 +456,15 @@ func (b *balancer) Start(target string, config grpc.BalancerConfig) error {
419456
creds := config.DialCreds
420457
ccError = make(chan struct{})
421458
if creds == nil {
422-
cc, err = grpc.Dial(rb.addr, grpc.WithInsecure())
459+
cc, err = Dial(rb.addr, WithInsecure())
423460
} else {
424461
if rb.name != "" {
425462
if err := creds.OverrideServerName(rb.name); err != nil {
426463
grpclog.Printf("Failed to override the server name in the credentials: %v", err)
427464
continue
428465
}
429466
}
430-
cc, err = grpc.Dial(rb.addr, grpc.WithTransportCredentials(creds))
467+
cc, err = Dial(rb.addr, WithTransportCredentials(creds))
431468
}
432469
if err != nil {
433470
grpclog.Printf("Failed to setup a connection to the remote balancer %v: %v", rb.addr, err)
@@ -439,8 +476,8 @@ func (b *balancer) Start(target string, config grpc.BalancerConfig) error {
439476
seq := b.seq
440477
b.next = 0
441478
b.mu.Unlock()
442-
go func(cc *grpc.ClientConn, ccError chan struct{}) {
443-
lbc := lbpb.NewLoadBalancerClient(cc)
479+
go func(cc *ClientConn, ccError chan struct{}) {
480+
lbc := &loadBalancerClient{cc}
444481
b.callRemoteBalancer(lbc, seq)
445482
cc.Close()
446483
select {
@@ -454,7 +491,7 @@ func (b *balancer) Start(target string, config grpc.BalancerConfig) error {
454491
return nil
455492
}
456493

457-
func (b *balancer) down(addr grpc.Address, err error) {
494+
func (b *balancer) down(addr Address, err error) {
458495
b.mu.Lock()
459496
defer b.mu.Unlock()
460497
for _, a := range b.addrs {
@@ -465,7 +502,7 @@ func (b *balancer) down(addr grpc.Address, err error) {
465502
}
466503
}
467504

468-
func (b *balancer) Up(addr grpc.Address) func(error) {
505+
func (b *balancer) Up(addr Address) func(error) {
469506
b.mu.Lock()
470507
defer b.mu.Unlock()
471508
if b.done {
@@ -479,7 +516,7 @@ func (b *balancer) Up(addr grpc.Address) func(error) {
479516
}
480517
a.connected = true
481518
}
482-
if a.connected && !a.dropRequest {
519+
if a.connected && !a.dropForRateLimiting && !a.dropForLoadBalancing {
483520
cnt++
484521
}
485522
}
@@ -493,12 +530,12 @@ func (b *balancer) Up(addr grpc.Address) func(error) {
493530
}
494531
}
495532

496-
func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr grpc.Address, put func(), err error) {
533+
func (b *balancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) {
497534
var ch chan struct{}
498535
b.mu.Lock()
499536
if b.done {
500537
b.mu.Unlock()
501-
err = grpc.ErrClientConnClosing
538+
err = ErrClientConnClosing
502539
return
503540
}
504541

@@ -511,7 +548,7 @@ func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr
511548
a := b.addrs[next]
512549
next = (next + 1) % len(b.addrs)
513550
if a.connected {
514-
if !a.dropRequest {
551+
if !a.dropForRateLimiting && !a.dropForLoadBalancing {
515552
addr = a.addr
516553
b.next = next
517554
b.mu.Unlock()
@@ -520,7 +557,7 @@ func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr
520557
if !opts.BlockingWait {
521558
b.next = next
522559
b.mu.Unlock()
523-
err = grpc.Errorf(codes.Unavailable, "%s drops requests", a.addr.Addr)
560+
err = Errorf(codes.Unavailable, "%s drops requests", a.addr.Addr)
524561
return
525562
}
526563
}
@@ -533,7 +570,7 @@ func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr
533570
if !opts.BlockingWait {
534571
if len(b.addrs) == 0 {
535572
b.mu.Unlock()
536-
err = grpc.Errorf(codes.Unavailable, "there is no address available")
573+
err = Errorf(codes.Unavailable, "there is no address available")
537574
return
538575
}
539576
// Returns the next addr on b.addrs for a failfast RPC.
@@ -559,7 +596,7 @@ func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr
559596
b.mu.Lock()
560597
if b.done {
561598
b.mu.Unlock()
562-
err = grpc.ErrClientConnClosing
599+
err = ErrClientConnClosing
563600
return
564601
}
565602

@@ -572,7 +609,7 @@ func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr
572609
a := b.addrs[next]
573610
next = (next + 1) % len(b.addrs)
574611
if a.connected {
575-
if !a.dropRequest {
612+
if !a.dropForRateLimiting && !a.dropForLoadBalancing {
576613
addr = a.addr
577614
b.next = next
578615
b.mu.Unlock()
@@ -581,7 +618,7 @@ func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr
581618
if !opts.BlockingWait {
582619
b.next = next
583620
b.mu.Unlock()
584-
err = grpc.Errorf(codes.Unavailable, "drop requests for the addreess %s", a.addr.Addr)
621+
err = Errorf(codes.Unavailable, "drop requests for the addreess %s", a.addr.Addr)
585622
return
586623
}
587624
}
@@ -603,7 +640,7 @@ func (b *balancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (addr
603640
}
604641
}
605642

606-
func (b *balancer) Notify() <-chan []grpc.Address {
643+
func (b *balancer) Notify() <-chan []Address {
607644
return b.addrCh
608645
}
609646

0 commit comments

Comments
 (0)