cmd/protoc-gen-go-grpc: revert to interface-based service registration (#3911)

This commit is contained in:
Doug Fawley 2020-09-29 15:17:06 -07:00 committed by GitHub
parent e6c98a478e
commit 02cd07d9bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
68 changed files with 2021 additions and 2555 deletions

View File

@ -29,14 +29,8 @@ func NewLoadBalancerClient(cc grpc.ClientConnInterface) LoadBalancerClient {
return &loadBalancerClient{cc} return &loadBalancerClient{cc}
} }
var loadBalancerBalanceLoadStreamDesc = &grpc.StreamDesc{
StreamName: "BalanceLoad",
ServerStreams: true,
ClientStreams: true,
}
func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) { func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) {
stream, err := c.cc.NewStream(ctx, loadBalancerBalanceLoadStreamDesc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) stream, err := c.cc.NewStream(ctx, &_LoadBalancer_serviceDesc.Streams[0], "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -66,17 +60,35 @@ func (x *loadBalancerBalanceLoadClient) Recv() (*LoadBalanceResponse, error) {
return m, nil return m, nil
} }
// LoadBalancerService is the service API for LoadBalancer service. // LoadBalancerServer is the server API for LoadBalancer service.
// Fields should be assigned to their respective handler implementations only before // All implementations should embed UnimplementedLoadBalancerServer
// RegisterLoadBalancerService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type LoadBalancerServer interface {
type LoadBalancerService struct {
// Bidirectional rpc to get a list of servers. // Bidirectional rpc to get a list of servers.
BalanceLoad func(LoadBalancer_BalanceLoadServer) error BalanceLoad(LoadBalancer_BalanceLoadServer) error
} }
func (s *LoadBalancerService) balanceLoad(_ interface{}, stream grpc.ServerStream) error { // UnimplementedLoadBalancerServer should be embedded to have forward compatible implementations.
return s.BalanceLoad(&loadBalancerBalanceLoadServer{stream}) type UnimplementedLoadBalancerServer struct {
}
func (UnimplementedLoadBalancerServer) BalanceLoad(LoadBalancer_BalanceLoadServer) error {
return status.Errorf(codes.Unimplemented, "method BalanceLoad not implemented")
}
// UnsafeLoadBalancerServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to LoadBalancerServer will
// result in compilation errors.
type UnsafeLoadBalancerServer interface {
mustEmbedUnimplementedLoadBalancerServer()
}
func RegisterLoadBalancerServer(s *grpc.Server, srv LoadBalancerServer) {
s.RegisterService(&_LoadBalancer_serviceDesc, srv)
}
func _LoadBalancer_BalanceLoad_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(LoadBalancerServer).BalanceLoad(&loadBalancerBalanceLoadServer{stream})
} }
type LoadBalancer_BalanceLoadServer interface { type LoadBalancer_BalanceLoadServer interface {
@ -101,53 +113,17 @@ func (x *loadBalancerBalanceLoadServer) Recv() (*LoadBalanceRequest, error) {
return m, nil return m, nil
} }
// RegisterLoadBalancerService registers a service implementation with a gRPC server. var _LoadBalancer_serviceDesc = grpc.ServiceDesc{
func RegisterLoadBalancerService(s grpc.ServiceRegistrar, srv *LoadBalancerService) { ServiceName: "grpc.lb.v1.LoadBalancer",
srvCopy := *srv HandlerType: (*LoadBalancerServer)(nil),
if srvCopy.BalanceLoad == nil { Methods: []grpc.MethodDesc{},
srvCopy.BalanceLoad = func(LoadBalancer_BalanceLoadServer) error { Streams: []grpc.StreamDesc{
return status.Errorf(codes.Unimplemented, "method BalanceLoad not implemented") {
} StreamName: "BalanceLoad",
} Handler: _LoadBalancer_BalanceLoad_Handler,
sd := grpc.ServiceDesc{ ServerStreams: true,
ServiceName: "grpc.lb.v1.LoadBalancer", ClientStreams: true,
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "BalanceLoad",
Handler: srvCopy.balanceLoad,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "grpc/lb/v1/load_balancer.proto", },
} Metadata: "grpc/lb/v1/load_balancer.proto",
s.RegisterService(&sd, nil)
}
// LoadBalancerServer is the service API for LoadBalancer service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type LoadBalancerServer interface {
// Bidirectional rpc to get a list of servers.
BalanceLoad(LoadBalancer_BalanceLoadServer) error
}
// UnimplementedLoadBalancerServer can be embedded to have forward compatible implementations of
// LoadBalancerServer
type UnimplementedLoadBalancerServer struct {
}
func (UnimplementedLoadBalancerServer) BalanceLoad(LoadBalancer_BalanceLoadServer) error {
return status.Errorf(codes.Unimplemented, "method BalanceLoad not implemented")
}
// RegisterLoadBalancerServer registers a service implementation with a gRPC server.
func RegisterLoadBalancerServer(s grpc.ServiceRegistrar, srv LoadBalancerServer) {
str := &LoadBalancerService{
BalanceLoad: srv.BalanceLoad,
}
RegisterLoadBalancerService(s, str)
} }

View File

@ -276,6 +276,8 @@ func (b *remoteBalancer) BalanceLoad(stream lbgrpc.LoadBalancer_BalanceLoadServe
} }
type testServer struct { type testServer struct {
testpb.UnimplementedTestServiceServer
addr string addr string
fallback bool fallback bool
} }
@ -304,11 +306,7 @@ func startBackends(sn string, fallback bool, lis ...net.Listener) (servers []*gr
sn: sn, sn: sn,
} }
s := grpc.NewServer(grpc.Creds(creds)) s := grpc.NewServer(grpc.Creds(creds))
ts := &testServer{addr: l.Addr().String(), fallback: fallback} testpb.RegisterTestServiceServer(s, &testServer{addr: l.Addr().String(), fallback: fallback})
testpb.RegisterTestServiceService(s, &testpb.TestServiceService{
EmptyCall: ts.EmptyCall,
FullDuplexCall: ts.FullDuplexCall,
})
servers = append(servers, s) servers = append(servers, s)
go func(s *grpc.Server, l net.Listener) { go func(s *grpc.Server, l net.Listener) {
s.Serve(l) s.Serve(l)

View File

@ -29,10 +29,6 @@ func NewRouteLookupServiceClient(cc grpc.ClientConnInterface) RouteLookupService
return &routeLookupServiceClient{cc} return &routeLookupServiceClient{cc}
} }
var routeLookupServiceRouteLookupStreamDesc = &grpc.StreamDesc{
StreamName: "RouteLookup",
}
func (c *routeLookupServiceClient) RouteLookup(ctx context.Context, in *RouteLookupRequest, opts ...grpc.CallOption) (*RouteLookupResponse, error) { func (c *routeLookupServiceClient) RouteLookup(ctx context.Context, in *RouteLookupRequest, opts ...grpc.CallOption) (*RouteLookupResponse, error) {
out := new(RouteLookupResponse) out := new(RouteLookupResponse)
err := c.cc.Invoke(ctx, "/grpc.lookup.v1.RouteLookupService/RouteLookup", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.lookup.v1.RouteLookupService/RouteLookup", in, out, opts...)
@ -42,78 +38,62 @@ func (c *routeLookupServiceClient) RouteLookup(ctx context.Context, in *RouteLoo
return out, nil return out, nil
} }
// RouteLookupServiceService is the service API for RouteLookupService service. // RouteLookupServiceServer is the server API for RouteLookupService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedRouteLookupServiceServer
// RegisterRouteLookupServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error.
type RouteLookupServiceService struct {
// Lookup returns a target for a single key.
RouteLookup func(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error)
}
func (s *RouteLookupServiceService) routeLookup(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RouteLookupRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.RouteLookup(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.lookup.v1.RouteLookupService/RouteLookup",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.RouteLookup(ctx, req.(*RouteLookupRequest))
}
return interceptor(ctx, in, info, handler)
}
// RegisterRouteLookupServiceService registers a service implementation with a gRPC server.
func RegisterRouteLookupServiceService(s grpc.ServiceRegistrar, srv *RouteLookupServiceService) {
srvCopy := *srv
if srvCopy.RouteLookup == nil {
srvCopy.RouteLookup = func(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RouteLookup not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.lookup.v1.RouteLookupService",
Methods: []grpc.MethodDesc{
{
MethodName: "RouteLookup",
Handler: srvCopy.routeLookup,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "grpc/lookup/v1/rls.proto",
}
s.RegisterService(&sd, nil)
}
// RouteLookupServiceServer is the service API for RouteLookupService service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type RouteLookupServiceServer interface { type RouteLookupServiceServer interface {
// Lookup returns a target for a single key. // Lookup returns a target for a single key.
RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error)
mustEmbedUnimplementedRouteLookupServiceServer()
} }
// UnimplementedRouteLookupServiceServer can be embedded to have forward compatible implementations of // UnimplementedRouteLookupServiceServer must be embedded to have forward compatible implementations.
// RouteLookupServiceServer
type UnimplementedRouteLookupServiceServer struct { type UnimplementedRouteLookupServiceServer struct {
} }
func (UnimplementedRouteLookupServiceServer) RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) { func (UnimplementedRouteLookupServiceServer) RouteLookup(context.Context, *RouteLookupRequest) (*RouteLookupResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RouteLookup not implemented") return nil, status.Errorf(codes.Unimplemented, "method RouteLookup not implemented")
} }
func (UnimplementedRouteLookupServiceServer) mustEmbedUnimplementedRouteLookupServiceServer() {}
// RegisterRouteLookupServiceServer registers a service implementation with a gRPC server. // UnsafeRouteLookupServiceServer may be embedded to opt out of forward compatibility for this service.
func RegisterRouteLookupServiceServer(s grpc.ServiceRegistrar, srv RouteLookupServiceServer) { // Use of this interface is not recommended, as added methods to RouteLookupServiceServer will
str := &RouteLookupServiceService{ // result in compilation errors.
RouteLookup: srv.RouteLookup, type UnsafeRouteLookupServiceServer interface {
} mustEmbedUnimplementedRouteLookupServiceServer()
RegisterRouteLookupServiceService(s, str) }
func RegisterRouteLookupServiceServer(s *grpc.Server, srv RouteLookupServiceServer) {
s.RegisterService(&_RouteLookupService_serviceDesc, srv)
}
func _RouteLookupService_RouteLookup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RouteLookupRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(RouteLookupServiceServer).RouteLookup(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.lookup.v1.RouteLookupService/RouteLookup",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(RouteLookupServiceServer).RouteLookup(ctx, req.(*RouteLookupRequest))
}
return interceptor(ctx, in, info, handler)
}
var _RouteLookupService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.lookup.v1.RouteLookupService",
HandlerType: (*RouteLookupServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RouteLookup",
Handler: _RouteLookupService_RouteLookup_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "grpc/lookup/v1/rls.proto",
} }

View File

@ -47,11 +47,15 @@ func Test(t *testing.T) {
grpctest.RunSubTests(t, s{}) grpctest.RunSubTests(t, s{})
} }
func emptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { type testServer struct {
testpb.UnimplementedTestServiceServer
}
func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
return &testpb.Empty{}, nil return &testpb.Empty{}, nil
} }
func fullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error {
return nil return nil
} }
@ -81,10 +85,7 @@ func startTestServers(count int) (_ *test, err error) {
} }
s := grpc.NewServer() s := grpc.NewServer()
testpb.RegisterTestServiceService(s, &testpb.TestServiceService{ testpb.RegisterTestServiceServer(s, &testServer{})
EmptyCall: emptyCall,
FullDuplexCall: fullDuplexCall,
})
t.servers = append(t.servers, s) t.servers = append(t.servers, s)
t.addresses = append(t.addresses, lis.Addr().String()) t.addresses = append(t.addresses, lis.Addr().String())

View File

@ -61,14 +61,8 @@ func NewPayload(t testpb.PayloadType, size int) *testpb.Payload {
return p return p
} }
type testServer struct{} type testServer struct {
testpb.UnimplementedBenchmarkServiceServer
func (s *testServer) Svc() *testpb.BenchmarkServiceService {
return &testpb.BenchmarkServiceService{
UnaryCall: s.UnaryCall,
StreamingCall: s.StreamingCall,
UnconstrainedStreamingCall: s.UnconstrainedStreamingCall,
}
} }
func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
@ -150,17 +144,10 @@ func (s *testServer) UnconstrainedStreamingCall(stream testpb.BenchmarkService_U
// byteBufServer is a gRPC server that sends and receives byte buffer. // byteBufServer is a gRPC server that sends and receives byte buffer.
// The purpose is to benchmark the gRPC performance without protobuf serialization/deserialization overhead. // The purpose is to benchmark the gRPC performance without protobuf serialization/deserialization overhead.
type byteBufServer struct { type byteBufServer struct {
testpb.UnimplementedBenchmarkServiceServer
respSize int32 respSize int32
} }
func (s *byteBufServer) Svc() *testpb.BenchmarkServiceService {
return &testpb.BenchmarkServiceService{
UnaryCall: s.UnaryCall,
StreamingCall: s.StreamingCall,
UnconstrainedStreamingCall: s.UnconstrainedStreamingCall,
}
}
// UnaryCall is an empty function and is not used for benchmark. // UnaryCall is an empty function and is not used for benchmark.
// If bytebuf UnaryCall benchmark is needed later, the function body needs to be updated. // If bytebuf UnaryCall benchmark is needed later, the function body needs to be updated.
func (s *byteBufServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { func (s *byteBufServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
@ -224,13 +211,13 @@ func StartServer(info ServerInfo, opts ...grpc.ServerOption) func() {
s := grpc.NewServer(opts...) s := grpc.NewServer(opts...)
switch info.Type { switch info.Type {
case "protobuf": case "protobuf":
testpb.RegisterBenchmarkServiceService(s, (&testServer{}).Svc()) testpb.RegisterBenchmarkServiceServer(s, &testServer{})
case "bytebuf": case "bytebuf":
respSize, ok := info.Metadata.(int32) respSize, ok := info.Metadata.(int32)
if !ok { if !ok {
logger.Fatalf("failed to StartServer, invalid metadata: %v, for Type: %v", info.Metadata, info.Type) logger.Fatalf("failed to StartServer, invalid metadata: %v, for Type: %v", info.Metadata, info.Type)
} }
testpb.RegisterBenchmarkServiceService(s, (&byteBufServer{respSize: respSize}).Svc()) testpb.RegisterBenchmarkServiceServer(s, &byteBufServer{respSize: respSize})
default: default:
logger.Fatalf("failed to StartServer, unknown Type: %v", info.Type) logger.Fatalf("failed to StartServer, unknown Type: %v", info.Type)
} }

View File

@ -36,10 +36,6 @@ func NewBenchmarkServiceClient(cc grpc.ClientConnInterface) BenchmarkServiceClie
return &benchmarkServiceClient{cc} return &benchmarkServiceClient{cc}
} }
var benchmarkServiceUnaryCallStreamDesc = &grpc.StreamDesc{
StreamName: "UnaryCall",
}
func (c *benchmarkServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { func (c *benchmarkServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
out := new(SimpleResponse) out := new(SimpleResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.BenchmarkService/UnaryCall", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.BenchmarkService/UnaryCall", in, out, opts...)
@ -49,14 +45,8 @@ func (c *benchmarkServiceClient) UnaryCall(ctx context.Context, in *SimpleReques
return out, nil return out, nil
} }
var benchmarkServiceStreamingCallStreamDesc = &grpc.StreamDesc{
StreamName: "StreamingCall",
ServerStreams: true,
ClientStreams: true,
}
func (c *benchmarkServiceClient) StreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_StreamingCallClient, error) { func (c *benchmarkServiceClient) StreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_StreamingCallClient, error) {
stream, err := c.cc.NewStream(ctx, benchmarkServiceStreamingCallStreamDesc, "/grpc.testing.BenchmarkService/StreamingCall", opts...) stream, err := c.cc.NewStream(ctx, &_BenchmarkService_serviceDesc.Streams[0], "/grpc.testing.BenchmarkService/StreamingCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -86,14 +76,8 @@ func (x *benchmarkServiceStreamingCallClient) Recv() (*SimpleResponse, error) {
return m, nil return m, nil
} }
var benchmarkServiceUnconstrainedStreamingCallStreamDesc = &grpc.StreamDesc{
StreamName: "UnconstrainedStreamingCall",
ServerStreams: true,
ClientStreams: true,
}
func (c *benchmarkServiceClient) UnconstrainedStreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_UnconstrainedStreamingCallClient, error) { func (c *benchmarkServiceClient) UnconstrainedStreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_UnconstrainedStreamingCallClient, error) {
stream, err := c.cc.NewStream(ctx, benchmarkServiceUnconstrainedStreamingCallStreamDesc, "/grpc.testing.BenchmarkService/UnconstrainedStreamingCall", opts...) stream, err := c.cc.NewStream(ctx, &_BenchmarkService_serviceDesc.Streams[1], "/grpc.testing.BenchmarkService/UnconstrainedStreamingCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -123,44 +107,68 @@ func (x *benchmarkServiceUnconstrainedStreamingCallClient) Recv() (*SimpleRespon
return m, nil return m, nil
} }
// BenchmarkServiceService is the service API for BenchmarkService service. // BenchmarkServiceServer is the server API for BenchmarkService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedBenchmarkServiceServer
// RegisterBenchmarkServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type BenchmarkServiceServer interface {
type BenchmarkServiceService struct {
// One request followed by one response. // One request followed by one response.
// The server returns the client payload as-is. // The server returns the client payload as-is.
UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
// One request followed by one response. // One request followed by one response.
// The server returns the client payload as-is. // The server returns the client payload as-is.
StreamingCall func(BenchmarkService_StreamingCallServer) error StreamingCall(BenchmarkService_StreamingCallServer) error
// Unconstrainted streaming. // Unconstrainted streaming.
// Both server and client keep sending & receiving simultaneously. // Both server and client keep sending & receiving simultaneously.
UnconstrainedStreamingCall func(BenchmarkService_UnconstrainedStreamingCallServer) error UnconstrainedStreamingCall(BenchmarkService_UnconstrainedStreamingCallServer) error
mustEmbedUnimplementedBenchmarkServiceServer()
} }
func (s *BenchmarkServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedBenchmarkServiceServer must be embedded to have forward compatible implementations.
type UnimplementedBenchmarkServiceServer struct {
}
func (UnimplementedBenchmarkServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented")
}
func (UnimplementedBenchmarkServiceServer) StreamingCall(BenchmarkService_StreamingCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingCall not implemented")
}
func (UnimplementedBenchmarkServiceServer) UnconstrainedStreamingCall(BenchmarkService_UnconstrainedStreamingCallServer) error {
return status.Errorf(codes.Unimplemented, "method UnconstrainedStreamingCall not implemented")
}
func (UnimplementedBenchmarkServiceServer) mustEmbedUnimplementedBenchmarkServiceServer() {}
// UnsafeBenchmarkServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to BenchmarkServiceServer will
// result in compilation errors.
type UnsafeBenchmarkServiceServer interface {
mustEmbedUnimplementedBenchmarkServiceServer()
}
func RegisterBenchmarkServiceServer(s *grpc.Server, srv BenchmarkServiceServer) {
s.RegisterService(&_BenchmarkService_serviceDesc, srv)
}
func _BenchmarkService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimpleRequest) in := new(SimpleRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.UnaryCall(ctx, in) return srv.(BenchmarkServiceServer).UnaryCall(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.BenchmarkService/UnaryCall", FullMethod: "/grpc.testing.BenchmarkService/UnaryCall",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.UnaryCall(ctx, req.(*SimpleRequest)) return srv.(BenchmarkServiceServer).UnaryCall(ctx, req.(*SimpleRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *BenchmarkServiceService) streamingCall(_ interface{}, stream grpc.ServerStream) error {
return s.StreamingCall(&benchmarkServiceStreamingCallServer{stream}) func _BenchmarkService_StreamingCall_Handler(srv interface{}, stream grpc.ServerStream) error {
} return srv.(BenchmarkServiceServer).StreamingCall(&benchmarkServiceStreamingCallServer{stream})
func (s *BenchmarkServiceService) unconstrainedStreamingCall(_ interface{}, stream grpc.ServerStream) error {
return s.UnconstrainedStreamingCall(&benchmarkServiceUnconstrainedStreamingCallServer{stream})
} }
type BenchmarkService_StreamingCallServer interface { type BenchmarkService_StreamingCallServer interface {
@ -185,6 +193,10 @@ func (x *benchmarkServiceStreamingCallServer) Recv() (*SimpleRequest, error) {
return m, nil return m, nil
} }
func _BenchmarkService_UnconstrainedStreamingCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(BenchmarkServiceServer).UnconstrainedStreamingCall(&benchmarkServiceUnconstrainedStreamingCallServer{stream})
}
type BenchmarkService_UnconstrainedStreamingCallServer interface { type BenchmarkService_UnconstrainedStreamingCallServer interface {
Send(*SimpleResponse) error Send(*SimpleResponse) error
Recv() (*SimpleRequest, error) Recv() (*SimpleRequest, error)
@ -207,50 +219,30 @@ func (x *benchmarkServiceUnconstrainedStreamingCallServer) Recv() (*SimpleReques
return m, nil return m, nil
} }
// RegisterBenchmarkServiceService registers a service implementation with a gRPC server. var _BenchmarkService_serviceDesc = grpc.ServiceDesc{
func RegisterBenchmarkServiceService(s grpc.ServiceRegistrar, srv *BenchmarkServiceService) { ServiceName: "grpc.testing.BenchmarkService",
srvCopy := *srv HandlerType: (*BenchmarkServiceServer)(nil),
if srvCopy.UnaryCall == nil { Methods: []grpc.MethodDesc{
srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) { {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") MethodName: "UnaryCall",
} Handler: _BenchmarkService_UnaryCall_Handler,
}
if srvCopy.StreamingCall == nil {
srvCopy.StreamingCall = func(BenchmarkService_StreamingCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingCall not implemented")
}
}
if srvCopy.UnconstrainedStreamingCall == nil {
srvCopy.UnconstrainedStreamingCall = func(BenchmarkService_UnconstrainedStreamingCallServer) error {
return status.Errorf(codes.Unimplemented, "method UnconstrainedStreamingCall not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.testing.BenchmarkService",
Methods: []grpc.MethodDesc{
{
MethodName: "UnaryCall",
Handler: srvCopy.unaryCall,
},
}, },
Streams: []grpc.StreamDesc{ },
{ Streams: []grpc.StreamDesc{
StreamName: "StreamingCall", {
Handler: srvCopy.streamingCall, StreamName: "StreamingCall",
ServerStreams: true, Handler: _BenchmarkService_StreamingCall_Handler,
ClientStreams: true, ServerStreams: true,
}, ClientStreams: true,
{
StreamName: "UnconstrainedStreamingCall",
Handler: srvCopy.unconstrainedStreamingCall,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "benchmark/grpc_testing/services.proto", {
} StreamName: "UnconstrainedStreamingCall",
Handler: _BenchmarkService_UnconstrainedStreamingCall_Handler,
s.RegisterService(&sd, nil) ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "benchmark/grpc_testing/services.proto",
} }
// WorkerServiceClient is the client API for WorkerService service. // WorkerServiceClient is the client API for WorkerService service.
@ -285,14 +277,8 @@ func NewWorkerServiceClient(cc grpc.ClientConnInterface) WorkerServiceClient {
return &workerServiceClient{cc} return &workerServiceClient{cc}
} }
var workerServiceRunServerStreamDesc = &grpc.StreamDesc{
StreamName: "RunServer",
ServerStreams: true,
ClientStreams: true,
}
func (c *workerServiceClient) RunServer(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunServerClient, error) { func (c *workerServiceClient) RunServer(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunServerClient, error) {
stream, err := c.cc.NewStream(ctx, workerServiceRunServerStreamDesc, "/grpc.testing.WorkerService/RunServer", opts...) stream, err := c.cc.NewStream(ctx, &_WorkerService_serviceDesc.Streams[0], "/grpc.testing.WorkerService/RunServer", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -322,14 +308,8 @@ func (x *workerServiceRunServerClient) Recv() (*ServerStatus, error) {
return m, nil return m, nil
} }
var workerServiceRunClientStreamDesc = &grpc.StreamDesc{
StreamName: "RunClient",
ServerStreams: true,
ClientStreams: true,
}
func (c *workerServiceClient) RunClient(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunClientClient, error) { func (c *workerServiceClient) RunClient(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunClientClient, error) {
stream, err := c.cc.NewStream(ctx, workerServiceRunClientStreamDesc, "/grpc.testing.WorkerService/RunClient", opts...) stream, err := c.cc.NewStream(ctx, &_WorkerService_serviceDesc.Streams[1], "/grpc.testing.WorkerService/RunClient", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -359,10 +339,6 @@ func (x *workerServiceRunClientClient) Recv() (*ClientStatus, error) {
return m, nil return m, nil
} }
var workerServiceCoreCountStreamDesc = &grpc.StreamDesc{
StreamName: "CoreCount",
}
func (c *workerServiceClient) CoreCount(ctx context.Context, in *CoreRequest, opts ...grpc.CallOption) (*CoreResponse, error) { func (c *workerServiceClient) CoreCount(ctx context.Context, in *CoreRequest, opts ...grpc.CallOption) (*CoreResponse, error) {
out := new(CoreResponse) out := new(CoreResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/CoreCount", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/CoreCount", in, out, opts...)
@ -372,10 +348,6 @@ func (c *workerServiceClient) CoreCount(ctx context.Context, in *CoreRequest, op
return out, nil return out, nil
} }
var workerServiceQuitWorkerStreamDesc = &grpc.StreamDesc{
StreamName: "QuitWorker",
}
func (c *workerServiceClient) QuitWorker(ctx context.Context, in *Void, opts ...grpc.CallOption) (*Void, error) { func (c *workerServiceClient) QuitWorker(ctx context.Context, in *Void, opts ...grpc.CallOption) (*Void, error) {
out := new(Void) out := new(Void)
err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/QuitWorker", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/QuitWorker", in, out, opts...)
@ -385,70 +357,62 @@ func (c *workerServiceClient) QuitWorker(ctx context.Context, in *Void, opts ...
return out, nil return out, nil
} }
// WorkerServiceService is the service API for WorkerService service. // WorkerServiceServer is the server API for WorkerService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedWorkerServiceServer
// RegisterWorkerServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type WorkerServiceServer interface {
type WorkerServiceService struct {
// Start server with specified workload. // Start server with specified workload.
// First request sent specifies the ServerConfig followed by ServerStatus // First request sent specifies the ServerConfig followed by ServerStatus
// response. After that, a "Mark" can be sent anytime to request the latest // response. After that, a "Mark" can be sent anytime to request the latest
// stats. Closing the stream will initiate shutdown of the test server // stats. Closing the stream will initiate shutdown of the test server
// and once the shutdown has finished, the OK status is sent to terminate // and once the shutdown has finished, the OK status is sent to terminate
// this RPC. // this RPC.
RunServer func(WorkerService_RunServerServer) error RunServer(WorkerService_RunServerServer) error
// Start client with specified workload. // Start client with specified workload.
// First request sent specifies the ClientConfig followed by ClientStatus // First request sent specifies the ClientConfig followed by ClientStatus
// response. After that, a "Mark" can be sent anytime to request the latest // response. After that, a "Mark" can be sent anytime to request the latest
// stats. Closing the stream will initiate shutdown of the test client // stats. Closing the stream will initiate shutdown of the test client
// and once the shutdown has finished, the OK status is sent to terminate // and once the shutdown has finished, the OK status is sent to terminate
// this RPC. // this RPC.
RunClient func(WorkerService_RunClientServer) error RunClient(WorkerService_RunClientServer) error
// Just return the core count - unary call // Just return the core count - unary call
CoreCount func(context.Context, *CoreRequest) (*CoreResponse, error) CoreCount(context.Context, *CoreRequest) (*CoreResponse, error)
// Quit this worker // Quit this worker
QuitWorker func(context.Context, *Void) (*Void, error) QuitWorker(context.Context, *Void) (*Void, error)
mustEmbedUnimplementedWorkerServiceServer()
} }
func (s *WorkerServiceService) runServer(_ interface{}, stream grpc.ServerStream) error { // UnimplementedWorkerServiceServer must be embedded to have forward compatible implementations.
return s.RunServer(&workerServiceRunServerServer{stream}) type UnimplementedWorkerServiceServer struct {
} }
func (s *WorkerServiceService) runClient(_ interface{}, stream grpc.ServerStream) error {
return s.RunClient(&workerServiceRunClientServer{stream}) func (UnimplementedWorkerServiceServer) RunServer(WorkerService_RunServerServer) error {
return status.Errorf(codes.Unimplemented, "method RunServer not implemented")
} }
func (s *WorkerServiceService) coreCount(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { func (UnimplementedWorkerServiceServer) RunClient(WorkerService_RunClientServer) error {
in := new(CoreRequest) return status.Errorf(codes.Unimplemented, "method RunClient not implemented")
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.CoreCount(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.testing.WorkerService/CoreCount",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.CoreCount(ctx, req.(*CoreRequest))
}
return interceptor(ctx, in, info, handler)
} }
func (s *WorkerServiceService) quitWorker(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { func (UnimplementedWorkerServiceServer) CoreCount(context.Context, *CoreRequest) (*CoreResponse, error) {
in := new(Void) return nil, status.Errorf(codes.Unimplemented, "method CoreCount not implemented")
if err := dec(in); err != nil { }
return nil, err func (UnimplementedWorkerServiceServer) QuitWorker(context.Context, *Void) (*Void, error) {
} return nil, status.Errorf(codes.Unimplemented, "method QuitWorker not implemented")
if interceptor == nil { }
return s.QuitWorker(ctx, in) func (UnimplementedWorkerServiceServer) mustEmbedUnimplementedWorkerServiceServer() {}
}
info := &grpc.UnaryServerInfo{ // UnsafeWorkerServiceServer may be embedded to opt out of forward compatibility for this service.
Server: s, // Use of this interface is not recommended, as added methods to WorkerServiceServer will
FullMethod: "/grpc.testing.WorkerService/QuitWorker", // result in compilation errors.
} type UnsafeWorkerServiceServer interface {
handler := func(ctx context.Context, req interface{}) (interface{}, error) { mustEmbedUnimplementedWorkerServiceServer()
return s.QuitWorker(ctx, req.(*Void)) }
}
return interceptor(ctx, in, info, handler) func RegisterWorkerServiceServer(s *grpc.Server, srv WorkerServiceServer) {
s.RegisterService(&_WorkerService_serviceDesc, srv)
}
func _WorkerService_RunServer_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(WorkerServiceServer).RunServer(&workerServiceRunServerServer{stream})
} }
type WorkerService_RunServerServer interface { type WorkerService_RunServerServer interface {
@ -473,6 +437,10 @@ func (x *workerServiceRunServerServer) Recv() (*ServerArgs, error) {
return m, nil return m, nil
} }
func _WorkerService_RunClient_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(WorkerServiceServer).RunClient(&workerServiceRunClientServer{stream})
}
type WorkerService_RunClientServer interface { type WorkerService_RunClientServer interface {
Send(*ClientStatus) error Send(*ClientStatus) error
Recv() (*ClientArgs, error) Recv() (*ClientArgs, error)
@ -495,57 +463,68 @@ func (x *workerServiceRunClientServer) Recv() (*ClientArgs, error) {
return m, nil return m, nil
} }
// RegisterWorkerServiceService registers a service implementation with a gRPC server. func _WorkerService_CoreCount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
func RegisterWorkerServiceService(s grpc.ServiceRegistrar, srv *WorkerServiceService) { in := new(CoreRequest)
srvCopy := *srv if err := dec(in); err != nil {
if srvCopy.RunServer == nil { return nil, err
srvCopy.RunServer = func(WorkerService_RunServerServer) error {
return status.Errorf(codes.Unimplemented, "method RunServer not implemented")
}
} }
if srvCopy.RunClient == nil { if interceptor == nil {
srvCopy.RunClient = func(WorkerService_RunClientServer) error { return srv.(WorkerServiceServer).CoreCount(ctx, in)
return status.Errorf(codes.Unimplemented, "method RunClient not implemented")
}
} }
if srvCopy.CoreCount == nil { info := &grpc.UnaryServerInfo{
srvCopy.CoreCount = func(context.Context, *CoreRequest) (*CoreResponse, error) { Server: srv,
return nil, status.Errorf(codes.Unimplemented, "method CoreCount not implemented") FullMethod: "/grpc.testing.WorkerService/CoreCount",
}
} }
if srvCopy.QuitWorker == nil { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
srvCopy.QuitWorker = func(context.Context, *Void) (*Void, error) { return srv.(WorkerServiceServer).CoreCount(ctx, req.(*CoreRequest))
return nil, status.Errorf(codes.Unimplemented, "method QuitWorker not implemented")
}
} }
sd := grpc.ServiceDesc{ return interceptor(ctx, in, info, handler)
ServiceName: "grpc.testing.WorkerService", }
Methods: []grpc.MethodDesc{
{ func _WorkerService_QuitWorker_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
MethodName: "CoreCount", in := new(Void)
Handler: srvCopy.coreCount, if err := dec(in); err != nil {
}, return nil, err
{ }
MethodName: "QuitWorker", if interceptor == nil {
Handler: srvCopy.quitWorker, return srv.(WorkerServiceServer).QuitWorker(ctx, in)
}, }
}, info := &grpc.UnaryServerInfo{
Streams: []grpc.StreamDesc{ Server: srv,
{ FullMethod: "/grpc.testing.WorkerService/QuitWorker",
StreamName: "RunServer", }
Handler: srvCopy.runServer, handler := func(ctx context.Context, req interface{}) (interface{}, error) {
ServerStreams: true, return srv.(WorkerServiceServer).QuitWorker(ctx, req.(*Void))
ClientStreams: true, }
}, return interceptor(ctx, in, info, handler)
{ }
StreamName: "RunClient",
Handler: srvCopy.runClient, var _WorkerService_serviceDesc = grpc.ServiceDesc{
ServerStreams: true, ServiceName: "grpc.testing.WorkerService",
ClientStreams: true, HandlerType: (*WorkerServiceServer)(nil),
}, Methods: []grpc.MethodDesc{
}, {
Metadata: "benchmark/grpc_testing/services.proto", MethodName: "CoreCount",
} Handler: _WorkerService_CoreCount_Handler,
},
s.RegisterService(&sd, nil) {
MethodName: "QuitWorker",
Handler: _WorkerService_QuitWorker_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "RunServer",
Handler: _WorkerService_RunServer_Handler,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "RunClient",
Handler: _WorkerService_RunClient_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "benchmark/grpc_testing/services.proto",
} }

View File

@ -75,19 +75,11 @@ func (byteBufCodec) String() string {
// workerServer implements WorkerService rpc handlers. // workerServer implements WorkerService rpc handlers.
// It can create benchmarkServer or benchmarkClient on demand. // It can create benchmarkServer or benchmarkClient on demand.
type workerServer struct { type workerServer struct {
testpb.UnimplementedWorkerServiceServer
stop chan<- bool stop chan<- bool
serverPort int serverPort int
} }
func (s *workerServer) Svc() *testpb.WorkerServiceService {
return &testpb.WorkerServiceService{
RunServer: s.RunServer,
RunClient: s.RunClient,
CoreCount: s.CoreCount,
QuitWorker: s.QuitWorker,
}
}
func (s *workerServer) RunServer(stream testpb.WorkerService_RunServerServer) error { func (s *workerServer) RunServer(stream testpb.WorkerService_RunServerServer) error {
var bs *benchmarkServer var bs *benchmarkServer
defer func() { defer func() {
@ -217,10 +209,10 @@ func main() {
s := grpc.NewServer() s := grpc.NewServer()
stop := make(chan bool) stop := make(chan bool)
testpb.RegisterWorkerServiceService(s, (&workerServer{ testpb.RegisterWorkerServiceServer(s, &workerServer{
stop: stop, stop: stop,
serverPort: *serverPort, serverPort: *serverPort,
}).Svc()) })
go func() { go func() {
<-stop <-stop

View File

@ -115,18 +115,10 @@ var (
) )
type testServer struct { type testServer struct {
testpb.UnimplementedTestServiceServer
te *test te *test
} }
func (s *testServer) Svc() *testpb.TestServiceService {
return &testpb.TestServiceService{
UnaryCall: s.UnaryCall,
FullDuplexCall: s.FullDuplexCall,
ClientStreamCall: s.ClientStreamCall,
ServerStreamCall: s.ServerStreamCall,
}
}
func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
md, ok := metadata.FromIncomingContext(ctx) md, ok := metadata.FromIncomingContext(ctx)
if ok { if ok {
@ -224,7 +216,7 @@ func (s *testServer) ServerStreamCall(in *testpb.SimpleRequest, stream testpb.Te
type test struct { type test struct {
t *testing.T t *testing.T
testService *testpb.TestServiceService // nil means none testService testpb.TestServiceServer // nil means none
// srv and srvAddr are set once startServer is called. // srv and srvAddr are set once startServer is called.
srv *grpc.Server srv *grpc.Server
srvAddr string // Server IP without port. srvAddr string // Server IP without port.
@ -279,7 +271,7 @@ func (lw *listenerWrapper) Accept() (net.Conn, error) {
// startServer starts a gRPC server listening. Callers should defer a // startServer starts a gRPC server listening. Callers should defer a
// call to te.tearDown to clean up. // call to te.tearDown to clean up.
func (te *test) startServer(ts *testpb.TestServiceService) { func (te *test) startServer(ts testpb.TestServiceServer) {
te.testService = ts te.testService = ts
lis, err := net.Listen("tcp", "localhost:0") lis, err := net.Listen("tcp", "localhost:0")
@ -295,7 +287,7 @@ func (te *test) startServer(ts *testpb.TestServiceService) {
s := grpc.NewServer(opts...) s := grpc.NewServer(opts...)
te.srv = s te.srv = s
if te.testService != nil { if te.testService != nil {
testpb.RegisterTestServiceService(s, te.testService) testpb.RegisterTestServiceServer(s, te.testService)
} }
go s.Serve(lis) go s.Serve(lis)
@ -791,7 +783,7 @@ func (ed *expectedData) toServerLogEntries() []*pb.GrpcLogEntry {
func runRPCs(t *testing.T, tc *testConfig, cc *rpcConfig) *expectedData { func runRPCs(t *testing.T, tc *testConfig, cc *rpcConfig) *expectedData {
te := newTest(t, tc) te := newTest(t, tc)
te.startServer((&testServer{te: te}).Svc()) te.startServer(&testServer{te: te})
defer te.tearDown() defer te.tearDown()
expect := &expectedData{ expect := &expectedData{

View File

@ -42,10 +42,6 @@ func NewChannelzClient(cc grpc.ClientConnInterface) ChannelzClient {
return &channelzClient{cc} return &channelzClient{cc}
} }
var channelzGetTopChannelsStreamDesc = &grpc.StreamDesc{
StreamName: "GetTopChannels",
}
func (c *channelzClient) GetTopChannels(ctx context.Context, in *GetTopChannelsRequest, opts ...grpc.CallOption) (*GetTopChannelsResponse, error) { func (c *channelzClient) GetTopChannels(ctx context.Context, in *GetTopChannelsRequest, opts ...grpc.CallOption) (*GetTopChannelsResponse, error) {
out := new(GetTopChannelsResponse) out := new(GetTopChannelsResponse)
err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetTopChannels", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetTopChannels", in, out, opts...)
@ -55,10 +51,6 @@ func (c *channelzClient) GetTopChannels(ctx context.Context, in *GetTopChannelsR
return out, nil return out, nil
} }
var channelzGetServersStreamDesc = &grpc.StreamDesc{
StreamName: "GetServers",
}
func (c *channelzClient) GetServers(ctx context.Context, in *GetServersRequest, opts ...grpc.CallOption) (*GetServersResponse, error) { func (c *channelzClient) GetServers(ctx context.Context, in *GetServersRequest, opts ...grpc.CallOption) (*GetServersResponse, error) {
out := new(GetServersResponse) out := new(GetServersResponse)
err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServers", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServers", in, out, opts...)
@ -68,10 +60,6 @@ func (c *channelzClient) GetServers(ctx context.Context, in *GetServersRequest,
return out, nil return out, nil
} }
var channelzGetServerStreamDesc = &grpc.StreamDesc{
StreamName: "GetServer",
}
func (c *channelzClient) GetServer(ctx context.Context, in *GetServerRequest, opts ...grpc.CallOption) (*GetServerResponse, error) { func (c *channelzClient) GetServer(ctx context.Context, in *GetServerRequest, opts ...grpc.CallOption) (*GetServerResponse, error) {
out := new(GetServerResponse) out := new(GetServerResponse)
err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServer", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServer", in, out, opts...)
@ -81,10 +69,6 @@ func (c *channelzClient) GetServer(ctx context.Context, in *GetServerRequest, op
return out, nil return out, nil
} }
var channelzGetServerSocketsStreamDesc = &grpc.StreamDesc{
StreamName: "GetServerSockets",
}
func (c *channelzClient) GetServerSockets(ctx context.Context, in *GetServerSocketsRequest, opts ...grpc.CallOption) (*GetServerSocketsResponse, error) { func (c *channelzClient) GetServerSockets(ctx context.Context, in *GetServerSocketsRequest, opts ...grpc.CallOption) (*GetServerSocketsResponse, error) {
out := new(GetServerSocketsResponse) out := new(GetServerSocketsResponse)
err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServerSockets", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServerSockets", in, out, opts...)
@ -94,10 +78,6 @@ func (c *channelzClient) GetServerSockets(ctx context.Context, in *GetServerSock
return out, nil return out, nil
} }
var channelzGetChannelStreamDesc = &grpc.StreamDesc{
StreamName: "GetChannel",
}
func (c *channelzClient) GetChannel(ctx context.Context, in *GetChannelRequest, opts ...grpc.CallOption) (*GetChannelResponse, error) { func (c *channelzClient) GetChannel(ctx context.Context, in *GetChannelRequest, opts ...grpc.CallOption) (*GetChannelResponse, error) {
out := new(GetChannelResponse) out := new(GetChannelResponse)
err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetChannel", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetChannel", in, out, opts...)
@ -107,10 +87,6 @@ func (c *channelzClient) GetChannel(ctx context.Context, in *GetChannelRequest,
return out, nil return out, nil
} }
var channelzGetSubchannelStreamDesc = &grpc.StreamDesc{
StreamName: "GetSubchannel",
}
func (c *channelzClient) GetSubchannel(ctx context.Context, in *GetSubchannelRequest, opts ...grpc.CallOption) (*GetSubchannelResponse, error) { func (c *channelzClient) GetSubchannel(ctx context.Context, in *GetSubchannelRequest, opts ...grpc.CallOption) (*GetSubchannelResponse, error) {
out := new(GetSubchannelResponse) out := new(GetSubchannelResponse)
err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSubchannel", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSubchannel", in, out, opts...)
@ -120,10 +96,6 @@ func (c *channelzClient) GetSubchannel(ctx context.Context, in *GetSubchannelReq
return out, nil return out, nil
} }
var channelzGetSocketStreamDesc = &grpc.StreamDesc{
StreamName: "GetSocket",
}
func (c *channelzClient) GetSocket(ctx context.Context, in *GetSocketRequest, opts ...grpc.CallOption) (*GetSocketResponse, error) { func (c *channelzClient) GetSocket(ctx context.Context, in *GetSocketRequest, opts ...grpc.CallOption) (*GetSocketResponse, error) {
out := new(GetSocketResponse) out := new(GetSocketResponse)
err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSocket", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSocket", in, out, opts...)
@ -133,229 +105,9 @@ func (c *channelzClient) GetSocket(ctx context.Context, in *GetSocketRequest, op
return out, nil return out, nil
} }
// ChannelzService is the service API for Channelz service. // ChannelzServer is the server API for Channelz service.
// Fields should be assigned to their respective handler implementations only before // All implementations should embed UnimplementedChannelzServer
// RegisterChannelzService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error.
type ChannelzService struct {
// Gets all root channels (i.e. channels the application has directly
// created). This does not include subchannels nor non-top level channels.
GetTopChannels func(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error)
// Gets all servers that exist in the process.
GetServers func(context.Context, *GetServersRequest) (*GetServersResponse, error)
// Returns a single Server, or else a NOT_FOUND code.
GetServer func(context.Context, *GetServerRequest) (*GetServerResponse, error)
// Gets all server sockets that exist in the process.
GetServerSockets func(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error)
// Returns a single Channel, or else a NOT_FOUND code.
GetChannel func(context.Context, *GetChannelRequest) (*GetChannelResponse, error)
// Returns a single Subchannel, or else a NOT_FOUND code.
GetSubchannel func(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error)
// Returns a single Socket or else a NOT_FOUND code.
GetSocket func(context.Context, *GetSocketRequest) (*GetSocketResponse, error)
}
func (s *ChannelzService) getTopChannels(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetTopChannelsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetTopChannels(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.channelz.v1.Channelz/GetTopChannels",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetTopChannels(ctx, req.(*GetTopChannelsRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *ChannelzService) getServers(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetServersRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetServers(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.channelz.v1.Channelz/GetServers",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetServers(ctx, req.(*GetServersRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *ChannelzService) getServer(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetServerRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetServer(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.channelz.v1.Channelz/GetServer",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetServer(ctx, req.(*GetServerRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *ChannelzService) getServerSockets(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetServerSocketsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetServerSockets(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.channelz.v1.Channelz/GetServerSockets",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetServerSockets(ctx, req.(*GetServerSocketsRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *ChannelzService) getChannel(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetChannelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetChannel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.channelz.v1.Channelz/GetChannel",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetChannel(ctx, req.(*GetChannelRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *ChannelzService) getSubchannel(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetSubchannelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetSubchannel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.channelz.v1.Channelz/GetSubchannel",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetSubchannel(ctx, req.(*GetSubchannelRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *ChannelzService) getSocket(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetSocketRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetSocket(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.channelz.v1.Channelz/GetSocket",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetSocket(ctx, req.(*GetSocketRequest))
}
return interceptor(ctx, in, info, handler)
}
// RegisterChannelzService registers a service implementation with a gRPC server.
func RegisterChannelzService(s grpc.ServiceRegistrar, srv *ChannelzService) {
srvCopy := *srv
if srvCopy.GetTopChannels == nil {
srvCopy.GetTopChannels = func(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetTopChannels not implemented")
}
}
if srvCopy.GetServers == nil {
srvCopy.GetServers = func(context.Context, *GetServersRequest) (*GetServersResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetServers not implemented")
}
}
if srvCopy.GetServer == nil {
srvCopy.GetServer = func(context.Context, *GetServerRequest) (*GetServerResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetServer not implemented")
}
}
if srvCopy.GetServerSockets == nil {
srvCopy.GetServerSockets = func(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetServerSockets not implemented")
}
}
if srvCopy.GetChannel == nil {
srvCopy.GetChannel = func(context.Context, *GetChannelRequest) (*GetChannelResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetChannel not implemented")
}
}
if srvCopy.GetSubchannel == nil {
srvCopy.GetSubchannel = func(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetSubchannel not implemented")
}
}
if srvCopy.GetSocket == nil {
srvCopy.GetSocket = func(context.Context, *GetSocketRequest) (*GetSocketResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetSocket not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.channelz.v1.Channelz",
Methods: []grpc.MethodDesc{
{
MethodName: "GetTopChannels",
Handler: srvCopy.getTopChannels,
},
{
MethodName: "GetServers",
Handler: srvCopy.getServers,
},
{
MethodName: "GetServer",
Handler: srvCopy.getServer,
},
{
MethodName: "GetServerSockets",
Handler: srvCopy.getServerSockets,
},
{
MethodName: "GetChannel",
Handler: srvCopy.getChannel,
},
{
MethodName: "GetSubchannel",
Handler: srvCopy.getSubchannel,
},
{
MethodName: "GetSocket",
Handler: srvCopy.getSocket,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "grpc/channelz/v1/channelz.proto",
}
s.RegisterService(&sd, nil)
}
// ChannelzServer is the service API for Channelz service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type ChannelzServer interface { type ChannelzServer interface {
// Gets all root channels (i.e. channels the application has directly // Gets all root channels (i.e. channels the application has directly
// created). This does not include subchannels nor non-top level channels. // created). This does not include subchannels nor non-top level channels.
@ -374,8 +126,7 @@ type ChannelzServer interface {
GetSocket(context.Context, *GetSocketRequest) (*GetSocketResponse, error) GetSocket(context.Context, *GetSocketRequest) (*GetSocketResponse, error)
} }
// UnimplementedChannelzServer can be embedded to have forward compatible implementations of // UnimplementedChannelzServer should be embedded to have forward compatible implementations.
// ChannelzServer
type UnimplementedChannelzServer struct { type UnimplementedChannelzServer struct {
} }
@ -401,16 +152,176 @@ func (UnimplementedChannelzServer) GetSocket(context.Context, *GetSocketRequest)
return nil, status.Errorf(codes.Unimplemented, "method GetSocket not implemented") return nil, status.Errorf(codes.Unimplemented, "method GetSocket not implemented")
} }
// RegisterChannelzServer registers a service implementation with a gRPC server. // UnsafeChannelzServer may be embedded to opt out of forward compatibility for this service.
func RegisterChannelzServer(s grpc.ServiceRegistrar, srv ChannelzServer) { // Use of this interface is not recommended, as added methods to ChannelzServer will
str := &ChannelzService{ // result in compilation errors.
GetTopChannels: srv.GetTopChannels, type UnsafeChannelzServer interface {
GetServers: srv.GetServers, mustEmbedUnimplementedChannelzServer()
GetServer: srv.GetServer, }
GetServerSockets: srv.GetServerSockets,
GetChannel: srv.GetChannel, func RegisterChannelzServer(s *grpc.Server, srv ChannelzServer) {
GetSubchannel: srv.GetSubchannel, s.RegisterService(&_Channelz_serviceDesc, srv)
GetSocket: srv.GetSocket, }
}
RegisterChannelzService(s, str) func _Channelz_GetTopChannels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetTopChannelsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChannelzServer).GetTopChannels(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.channelz.v1.Channelz/GetTopChannels",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChannelzServer).GetTopChannels(ctx, req.(*GetTopChannelsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Channelz_GetServers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetServersRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChannelzServer).GetServers(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.channelz.v1.Channelz/GetServers",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChannelzServer).GetServers(ctx, req.(*GetServersRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Channelz_GetServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetServerRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChannelzServer).GetServer(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.channelz.v1.Channelz/GetServer",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChannelzServer).GetServer(ctx, req.(*GetServerRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Channelz_GetServerSockets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetServerSocketsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChannelzServer).GetServerSockets(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.channelz.v1.Channelz/GetServerSockets",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChannelzServer).GetServerSockets(ctx, req.(*GetServerSocketsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Channelz_GetChannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetChannelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChannelzServer).GetChannel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.channelz.v1.Channelz/GetChannel",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChannelzServer).GetChannel(ctx, req.(*GetChannelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Channelz_GetSubchannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetSubchannelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChannelzServer).GetSubchannel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.channelz.v1.Channelz/GetSubchannel",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChannelzServer).GetSubchannel(ctx, req.(*GetSubchannelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Channelz_GetSocket_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetSocketRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChannelzServer).GetSocket(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.channelz.v1.Channelz/GetSocket",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChannelzServer).GetSocket(ctx, req.(*GetSocketRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Channelz_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.channelz.v1.Channelz",
HandlerType: (*ChannelzServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetTopChannels",
Handler: _Channelz_GetTopChannels_Handler,
},
{
MethodName: "GetServers",
Handler: _Channelz_GetServers_Handler,
},
{
MethodName: "GetServer",
Handler: _Channelz_GetServer_Handler,
},
{
MethodName: "GetServerSockets",
Handler: _Channelz_GetServerSockets_Handler,
},
{
MethodName: "GetChannel",
Handler: _Channelz_GetChannel_Handler,
},
{
MethodName: "GetSubchannel",
Handler: _Channelz_GetSubchannel_Handler,
},
{
MethodName: "GetSocket",
Handler: _Channelz_GetSocket_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "grpc/channelz/v1/channelz.proto",
} }

View File

@ -4,115 +4,18 @@ This tool generates Go language bindings of `service`s in protobuf definition
files for gRPC. For usage information, please see our [quick start files for gRPC. For usage information, please see our [quick start
guide](https://grpc.io/docs/languages/go/quickstart/). guide](https://grpc.io/docs/languages/go/quickstart/).
## Service implementation and registration ## Future-proofing services
**NOTE:** service registration has changed from the previous version of the By default, to register services using the methods generated by this tool, the
code generator. Please read this section carefully if you are migrating. service implementations must embed the corresponding
`Unimplemented<ServiceName>Server` for future compatibility. This is a behavior
change from the grpc code generator previously included with `protoc-gen-go`.
To restore this behavior, set the option `require_unimplemented_servers=false`.
E.g.:
To register your service handlers with a gRPC server, first implement the ```
methods as either functions or methods on a struct. Examples: protoc --go-grpc_out=require_unimplemented_servers=false[,other options...]:. \
```go
// As a function:
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
// Echo.UnaryEcho implementation
}
// As a struct + method:
type myEchoService struct {
// ...fields used by this service...
}
func (s *myEchoService) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
// Echo.UnaryEcho implementation
}
``` ```
Then create an instance of the generated `Service` struct type and initialize Note that this is not recommended, and the option is only provided to restore
the handlers which have been implemented: backward compatibility with previously-generated code.
```go
func main() {
// ...
// As a function:
echoService := pb.EchoService{
UnaryEcho: unaryEcho,
// etc
}
// As a struct+method:
mes := &myEchoService{...}
echoService := pb.EchoService{
UnaryEcho: mes.UnaryEcho,
// etc
}
// ...
}
```
Finally, pass this `Service` instance to the generated `Register` function:
```go
pb.RegisterEchoService(grpcServer, echoService)
```
### Migration from legacy version
Older versions of `protoc-gen-go-grpc` and `protoc-gen-go` with the grpc plugin
used a different method to register services. With that method, it was only
possible to register a service implementation that was a complete
implementation of the service. It was also possible to embed an
`Unimplemented` implementation of the service, which was also generated and
returned an UNIMPLEMENTED status for all methods.
#### Generating the legacy API
To avoid the need to update existing code, an option has been added to the code
generator to produce the legacy API alongside the new API. To use it:
```sh
# Example 1: with OPTS set to common options for protoc-gen-go and
# protoc-gen-go-grpc
protoc --go_out=${OPTS}:. --go-grpc_out=${OPTS},gen_unstable_server_interfaces=true:. *.proto
# Example 2: if no special options are needed
protoc --go_out=:. --go-grpc_out=gen_unstable_server_interfaces=true:. *.proto
```
**The use of this legacy API is NOT recommended.** It was discontinued as it
results in compilation breakages when new methods are added to services, which
is a backward-compatible change in all other languages supported by gRPC. With
the newer API, newly-added methods will return an UNIMPLEMENTED status.
#### Updating existing code
To convert your existing code using the previous code generator, please refer
to the following example:
```go
type myEchoService{
// ...fields used by this service...
}
// ... method handler implementation ...
func main() {
// ...
// OLD:
pb.RegisterEchoServer(grpcServer, &myEchoService{})
// NEW:
es := &myEchoService{}
pb.RegisterEchoService(grpcServer, pb.EchoService{
UnaryEcho: es.UnaryEcho,
// enumerate all methods in EchoService implemented by myEchoService...
})
// ...
}
```

View File

@ -61,15 +61,11 @@ func generateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.
g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion7")) g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion7"))
g.P() g.P()
for _, service := range file.Services { for _, service := range file.Services {
genClient(gen, file, g, service)
genService(gen, file, g, service) genService(gen, file, g, service)
if *genUnstableServerInterfaces {
genUnstableServerInterface(gen, file, g, service)
}
} }
} }
func genClient(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
clientName := service.GoName + "Client" clientName := service.GoName + "Client"
g.P("// ", clientName, " is the client API for ", service.GoName, " service.") g.P("// ", clientName, " is the client API for ", service.GoName, " service.")
@ -109,10 +105,129 @@ func genClient(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedF
g.P("}") g.P("}")
g.P() g.P()
var methodIndex, streamIndex int
// Client method implementations. // Client method implementations.
for _, method := range service.Methods { for _, method := range service.Methods {
genClientMethod(gen, g, method) if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
// Unary RPC method
genClientMethod(gen, file, g, method, methodIndex)
methodIndex++
} else {
// Streaming RPC method
genClientMethod(gen, file, g, method, streamIndex)
streamIndex++
}
} }
mustOrShould := "must"
if !*requireUnimplemented {
mustOrShould = "should"
}
// Server interface.
serverType := service.GoName + "Server"
g.P("// ", serverType, " is the server API for ", service.GoName, " service.")
g.P("// All implementations ", mustOrShould, " embed Unimplemented", serverType)
g.P("// for forward compatibility")
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
g.Annotate(serverType, service.Location)
g.P("type ", serverType, " interface {")
for _, method := range service.Methods {
g.Annotate(serverType+"."+method.GoName, method.Location)
if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
g.P(deprecationComment)
}
g.P(method.Comments.Leading,
serverSignature(g, method))
}
if *requireUnimplemented {
g.P("mustEmbedUnimplemented", serverType, "()")
}
g.P("}")
g.P()
// Server Unimplemented struct for forward compatibility.
g.P("// Unimplemented", serverType, " ", mustOrShould, " be embedded to have forward compatible implementations.")
g.P("type Unimplemented", serverType, " struct {")
g.P("}")
g.P()
for _, method := range service.Methods {
nilArg := ""
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
nilArg = "nil,"
}
g.P("func (Unimplemented", serverType, ") ", serverSignature(g, method), "{")
g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`)
g.P("}")
}
if *requireUnimplemented {
g.P("func (Unimplemented", serverType, ") mustEmbedUnimplemented", serverType, "() {}")
}
g.P()
// Unsafe Server interface to opt-out of forward compatibility.
g.P("// Unsafe", serverType, " may be embedded to opt out of forward compatibility for this service.")
g.P("// Use of this interface is not recommended, as added methods to ", serverType, " will")
g.P("// result in compilation errors.")
g.P("type Unsafe", serverType, " interface {")
g.P("mustEmbedUnimplemented", serverType, "()")
g.P("}")
// Server registration.
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P(deprecationComment)
}
serviceDescVar := "_" + service.GoName + "_serviceDesc"
g.P("func Register", service.GoName, "Server(s *", grpcPackage.Ident("Server"), ", srv ", serverType, ") {")
g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
g.P("}")
g.P()
// Server handler implementations.
var handlerNames []string
for _, method := range service.Methods {
hname := genServerMethod(gen, file, g, method)
handlerNames = append(handlerNames, hname)
}
// Service descriptor.
g.P("var ", serviceDescVar, " = ", grpcPackage.Ident("ServiceDesc"), " {")
g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",")
g.P("HandlerType: (*", serverType, ")(nil),")
g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{")
for i, method := range service.Methods {
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
continue
}
g.P("{")
g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",")
g.P("Handler: ", handlerNames[i], ",")
g.P("},")
}
g.P("},")
g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{")
for i, method := range service.Methods {
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
continue
}
g.P("{")
g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",")
g.P("Handler: ", handlerNames[i], ",")
if method.Desc.IsStreamingServer() {
g.P("ServerStreams: true,")
}
if method.Desc.IsStreamingClient() {
g.P("ClientStreams: true,")
}
g.P("},")
}
g.P("},")
g.P("Metadata: \"", file.Desc.Path(), "\",")
g.P("}")
g.P()
} }
func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string { func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
@ -130,25 +245,13 @@ func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string
return s return s
} }
func genClientMethod(gen *protogen.Plugin, g *protogen.GeneratedFile, method *protogen.Method) { func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method, index int) {
service := method.Parent service := method.Parent
sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name()) sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name())
if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
g.P(deprecationComment) g.P(deprecationComment)
} }
streamDescName := unexport(service.GoName) + method.GoName + "StreamDesc"
g.P("var ", streamDescName, " = &", grpcPackage.Ident("StreamDesc"), "{")
g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",")
if method.Desc.IsStreamingServer() {
g.P("ServerStreams: true,")
}
if method.Desc.IsStreamingClient() {
g.P("ClientStreams: true,")
}
g.P("}")
g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{") g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{")
if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() { if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
g.P("out := new(", method.Output.GoIdent, ")") g.P("out := new(", method.Output.GoIdent, ")")
@ -160,8 +263,8 @@ func genClientMethod(gen *protogen.Plugin, g *protogen.GeneratedFile, method *pr
return return
} }
streamType := unexport(service.GoName) + method.GoName + "Client" streamType := unexport(service.GoName) + method.GoName + "Client"
serviceDescVar := "_" + service.GoName + "_serviceDesc"
g.P(`stream, err := c.cc.NewStream(ctx, `, streamDescName, `, "`, sname, `", opts...)`) g.P("stream, err := c.cc.NewStream(ctx, &", serviceDescVar, ".Streams[", index, `], "`, sname, `", opts...)`)
g.P("if err != nil { return nil, err }") g.P("if err != nil { return nil, err }")
g.P("x := &", streamType, "{stream}") g.P("x := &", streamType, "{stream}")
if !method.Desc.IsStreamingClient() { if !method.Desc.IsStreamingClient() {
@ -221,175 +324,7 @@ func genClientMethod(gen *protogen.Plugin, g *protogen.GeneratedFile, method *pr
} }
} }
func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { func serverSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
// Server struct.
serviceType := service.GoName + "Service"
g.P("// ", serviceType, " is the service API for ", service.GoName, " service.")
g.P("// Fields should be assigned to their respective handler implementations only before")
g.P("// Register", serviceType, " is called. Any unassigned fields will result in the")
g.P("// handler for that method returning an Unimplemented error.")
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
g.Annotate(serviceType, service.Location)
g.P("type ", serviceType, " struct {")
for _, method := range service.Methods {
if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
g.P(deprecationComment)
}
g.Annotate(serviceType+"."+method.GoName, method.Location)
g.P(method.Comments.Leading,
method.GoName, " func", handlerSignature(g, method))
}
g.P("}")
g.P()
// Method handler implementations.
for _, method := range service.Methods {
genMethodHandler(gen, g, method)
}
// Stream interfaces and implementations.
for _, method := range service.Methods {
genServerStreamTypes(gen, g, method)
}
// Service registration.
genRegisterFunction(gen, file, g, service)
}
func genRegisterFunction(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
g.P("// Register", service.GoName, "Service registers a service implementation with a gRPC server.")
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
g.P("func Register", service.GoName, "Service(s ", grpcPackage.Ident("ServiceRegistrar"), ", srv *", service.GoName, "Service) {")
g.P("srvCopy := *srv")
// Add Unimplemented defaults for unset handlers
for _, method := range service.Methods {
g.P("if srvCopy.", method.GoName, " == nil {")
g.P("srvCopy.", method.GoName, " = func", handlerSignature(g, method), "{")
nilArg := ""
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
nilArg = "nil, "
}
g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`)
g.P("}")
g.P("}")
}
// Service descriptor.
g.P("sd := ", grpcPackage.Ident("ServiceDesc"), " {")
g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",")
g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{")
for _, method := range service.Methods {
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
continue
}
g.P("{")
g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",")
g.P("Handler: srvCopy.", unexport(method.GoName), ",")
g.P("},")
}
g.P("},")
g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{")
for _, method := range service.Methods {
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
continue
}
g.P("{")
g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",")
g.P("Handler: srvCopy.", unexport(method.GoName), ",")
if method.Desc.IsStreamingServer() {
g.P("ServerStreams: true,")
}
if method.Desc.IsStreamingClient() {
g.P("ClientStreams: true,")
}
g.P("},")
}
g.P("},")
g.P("Metadata: \"", file.Desc.Path(), "\",")
g.P("}")
g.P()
g.P("s.RegisterService(&sd, nil)")
g.P("}")
g.P()
}
func genUnstableServerInterface(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
// Service interface.
serverType := service.GoName + "Server"
g.P("// ", serverType, " is the service API for ", service.GoName, " service.")
g.P("// New methods may be added to this interface if they are added to the service")
g.P("// definition, which is not a backward-compatible change. For this reason, ")
g.P("// use of this type is not recommended unless you own the service definition.")
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
g.Annotate(serverType, service.Location)
g.P("type ", serverType, " interface {")
for _, method := range service.Methods {
g.Annotate(serverType+"."+method.GoName, method.Location)
if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
g.P(deprecationComment)
}
g.P(method.Comments.Leading,
methodSignature(g, method))
}
g.P("}")
g.P()
// Unimplemented implementation.
genUnimplementedServer(gen, file, g, service)
// Service registration.
genUnstableRegisterFunction(gen, file, g, service)
}
func genUnimplementedServer(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
// Server Unimplemented struct for forward compatibility.
serverType := service.GoName + "Server"
g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations of")
g.P("// ", serverType)
g.P("type Unimplemented", serverType, " struct {")
g.P("}")
g.P()
for _, method := range service.Methods {
nilArg := ""
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
nilArg = "nil,"
}
g.P("func (Unimplemented", serverType, ") ", methodSignature(g, method), "{")
g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`)
g.P("}")
}
g.P()
}
func genUnstableRegisterFunction(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
serverType := service.GoName + "Server"
g.P("// Register", serverType, " registers a service implementation with a gRPC server.")
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
g.P("func Register", serverType, "(s ", grpcPackage.Ident("ServiceRegistrar"), ", srv ", serverType, ") {")
g.P("str := &", service.GoName, "Service{")
for _, method := range service.Methods {
g.P(method.GoName, ": srv.", method.GoName, ",")
}
g.P("}")
g.P("Register", service.GoName, "Service(s, str)")
g.P("}")
g.P()
}
func methodSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
var reqArgs []string var reqArgs []string
ret := "error" ret := "error"
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
@ -405,80 +340,39 @@ func methodSignature(g *protogen.GeneratedFile, method *protogen.Method) string
return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
} }
func handlerSignature(g *protogen.GeneratedFile, method *protogen.Method) string { func genServerMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method) string {
var reqArgs []string
ret := "error"
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
reqArgs = append(reqArgs, g.QualifiedGoIdent(contextPackage.Ident("Context")))
ret = "(*" + g.QualifiedGoIdent(method.Output.GoIdent) + ", error)"
}
if !method.Desc.IsStreamingClient() {
reqArgs = append(reqArgs, "*"+g.QualifiedGoIdent(method.Input.GoIdent))
}
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
reqArgs = append(reqArgs, method.Parent.GoName+"_"+method.GoName+"Server")
}
return "(" + strings.Join(reqArgs, ", ") + ") " + ret
}
func genericHandlerSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
// Unary
return "(_ interface{}, ctx " + g.QualifiedGoIdent(contextPackage.Ident("Context")) +
", dec func(interface{}) error, interceptor " +
g.QualifiedGoIdent(grpcPackage.Ident("UnaryServerInterceptor")) + ") (interface{}, error)"
}
// Streaming
return "(_ interface{}, stream " + g.QualifiedGoIdent(grpcPackage.Ident("ServerStream")) + ") error"
}
func genMethodHandler(gen *protogen.Plugin, g *protogen.GeneratedFile, method *protogen.Method) {
service := method.Parent service := method.Parent
hname := fmt.Sprintf("_%s_%s_Handler", service.GoName, method.GoName)
g.P("func (s *", service.GoName, "Service) ", unexport(method.GoName), genericHandlerSignature(g, method), " {")
// Unary
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
g.P("func ", hname, "(srv interface{}, ctx ", contextPackage.Ident("Context"), ", dec func(interface{}) error, interceptor ", grpcPackage.Ident("UnaryServerInterceptor"), ") (interface{}, error) {")
g.P("in := new(", method.Input.GoIdent, ")") g.P("in := new(", method.Input.GoIdent, ")")
g.P("if err := dec(in); err != nil { return nil, err }") g.P("if err := dec(in); err != nil { return nil, err }")
g.P("if interceptor == nil { return srv.(", service.GoName, "Server).", method.GoName, "(ctx, in) }")
g.P("if interceptor == nil {")
g.P("return s.", method.GoName, "(ctx, in)")
g.P("}")
g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{") g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{")
g.P("Server: s,") g.P("Server: srv,")
g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",") g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",")
g.P("}") g.P("}")
g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {") g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {")
g.P("return s.", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))") g.P("return srv.(", service.GoName, "Server).", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))")
g.P("}") g.P("}")
g.P("return interceptor(ctx, in, info, handler)") g.P("return interceptor(ctx, in, info, handler)")
g.P("}") g.P("}")
return g.P()
return hname
} }
// Streaming
streamType := unexport(service.GoName) + method.GoName + "Server" streamType := unexport(service.GoName) + method.GoName + "Server"
g.P("func ", hname, "(srv interface{}, stream ", grpcPackage.Ident("ServerStream"), ") error {")
if !method.Desc.IsStreamingClient() { if !method.Desc.IsStreamingClient() {
// Server-streaming
g.P("m := new(", method.Input.GoIdent, ")") g.P("m := new(", method.Input.GoIdent, ")")
g.P("if err := stream.RecvMsg(m); err != nil { return err }") g.P("if err := stream.RecvMsg(m); err != nil { return err }")
g.P("return s.", method.GoName, "(m, &", streamType, "{stream})") g.P("return srv.(", service.GoName, "Server).", method.GoName, "(m, &", streamType, "{stream})")
} else { } else {
// Bidi-streaming g.P("return srv.(", service.GoName, "Server).", method.GoName, "(&", streamType, "{stream})")
g.P("return s.", method.GoName, "(&", streamType, "{stream})")
} }
g.P("}") g.P("}")
} g.P()
func genServerStreamTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, method *protogen.Method) {
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
// Unary method
return
}
service := method.Parent
streamType := unexport(service.GoName) + method.GoName + "Server"
genSend := method.Desc.IsStreamingServer() genSend := method.Desc.IsStreamingServer()
genSendAndClose := !method.Desc.IsStreamingServer() genSendAndClose := !method.Desc.IsStreamingServer()
genRecv := method.Desc.IsStreamingClient() genRecv := method.Desc.IsStreamingClient()
@ -524,7 +418,7 @@ func genServerStreamTypes(gen *protogen.Plugin, g *protogen.GeneratedFile, metho
g.P() g.P()
} }
return return hname
} }
const deprecationComment = "// Deprecated: Do not use." const deprecationComment = "// Deprecated: Do not use."

View File

@ -34,19 +34,17 @@ import (
"flag" "flag"
"google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/types/pluginpb"
) )
var genUnstableServerInterfaces *bool var requireUnimplemented *bool
func main() { func main() {
var flags flag.FlagSet var flags flag.FlagSet
genUnstableServerInterfaces = flags.Bool("gen_unstable_server_interfaces", false, `set to generate legacy "Server" interfaces which do not guarantee backward compatibility`) requireUnimplemented = flags.Bool("require_unimplemented_servers", true, "set to false to match legacy behavior")
protogen.Options{ protogen.Options{
ParamFunc: flags.Set, ParamFunc: flags.Set,
}.Run(func(gen *protogen.Plugin) error { }.Run(func(gen *protogen.Plugin) error {
gen.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
for _, f := range gen.Files { for _, f := range gen.Files {
if !f.Generate { if !f.Generate {
continue continue

View File

@ -34,14 +34,8 @@ func NewHandshakerServiceClient(cc grpc.ClientConnInterface) HandshakerServiceCl
return &handshakerServiceClient{cc} return &handshakerServiceClient{cc}
} }
var handshakerServiceDoHandshakeStreamDesc = &grpc.StreamDesc{
StreamName: "DoHandshake",
ServerStreams: true,
ClientStreams: true,
}
func (c *handshakerServiceClient) DoHandshake(ctx context.Context, opts ...grpc.CallOption) (HandshakerService_DoHandshakeClient, error) { func (c *handshakerServiceClient) DoHandshake(ctx context.Context, opts ...grpc.CallOption) (HandshakerService_DoHandshakeClient, error) {
stream, err := c.cc.NewStream(ctx, handshakerServiceDoHandshakeStreamDesc, "/grpc.gcp.HandshakerService/DoHandshake", opts...) stream, err := c.cc.NewStream(ctx, &_HandshakerService_serviceDesc.Streams[0], "/grpc.gcp.HandshakerService/DoHandshake", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -71,22 +65,42 @@ func (x *handshakerServiceDoHandshakeClient) Recv() (*HandshakerResp, error) {
return m, nil return m, nil
} }
// HandshakerServiceService is the service API for HandshakerService service. // HandshakerServiceServer is the server API for HandshakerService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedHandshakerServiceServer
// RegisterHandshakerServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type HandshakerServiceServer interface {
type HandshakerServiceService struct {
// Handshaker service accepts a stream of handshaker request, returning a // Handshaker service accepts a stream of handshaker request, returning a
// stream of handshaker response. Client is expected to send exactly one // stream of handshaker response. Client is expected to send exactly one
// message with either client_start or server_start followed by one or more // message with either client_start or server_start followed by one or more
// messages with next. Each time client sends a request, the handshaker // messages with next. Each time client sends a request, the handshaker
// service expects to respond. Client does not have to wait for service's // service expects to respond. Client does not have to wait for service's
// response before sending next request. // response before sending next request.
DoHandshake func(HandshakerService_DoHandshakeServer) error DoHandshake(HandshakerService_DoHandshakeServer) error
mustEmbedUnimplementedHandshakerServiceServer()
} }
func (s *HandshakerServiceService) doHandshake(_ interface{}, stream grpc.ServerStream) error { // UnimplementedHandshakerServiceServer must be embedded to have forward compatible implementations.
return s.DoHandshake(&handshakerServiceDoHandshakeServer{stream}) type UnimplementedHandshakerServiceServer struct {
}
func (UnimplementedHandshakerServiceServer) DoHandshake(HandshakerService_DoHandshakeServer) error {
return status.Errorf(codes.Unimplemented, "method DoHandshake not implemented")
}
func (UnimplementedHandshakerServiceServer) mustEmbedUnimplementedHandshakerServiceServer() {}
// UnsafeHandshakerServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to HandshakerServiceServer will
// result in compilation errors.
type UnsafeHandshakerServiceServer interface {
mustEmbedUnimplementedHandshakerServiceServer()
}
func RegisterHandshakerServiceServer(s *grpc.Server, srv HandshakerServiceServer) {
s.RegisterService(&_HandshakerService_serviceDesc, srv)
}
func _HandshakerService_DoHandshake_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(HandshakerServiceServer).DoHandshake(&handshakerServiceDoHandshakeServer{stream})
} }
type HandshakerService_DoHandshakeServer interface { type HandshakerService_DoHandshakeServer interface {
@ -111,58 +125,17 @@ func (x *handshakerServiceDoHandshakeServer) Recv() (*HandshakerReq, error) {
return m, nil return m, nil
} }
// RegisterHandshakerServiceService registers a service implementation with a gRPC server. var _HandshakerService_serviceDesc = grpc.ServiceDesc{
func RegisterHandshakerServiceService(s grpc.ServiceRegistrar, srv *HandshakerServiceService) { ServiceName: "grpc.gcp.HandshakerService",
srvCopy := *srv HandlerType: (*HandshakerServiceServer)(nil),
if srvCopy.DoHandshake == nil { Methods: []grpc.MethodDesc{},
srvCopy.DoHandshake = func(HandshakerService_DoHandshakeServer) error { Streams: []grpc.StreamDesc{
return status.Errorf(codes.Unimplemented, "method DoHandshake not implemented") {
} StreamName: "DoHandshake",
} Handler: _HandshakerService_DoHandshake_Handler,
sd := grpc.ServiceDesc{ ServerStreams: true,
ServiceName: "grpc.gcp.HandshakerService", ClientStreams: true,
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "DoHandshake",
Handler: srvCopy.doHandshake,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "grpc/gcp/handshaker.proto", },
} Metadata: "grpc/gcp/handshaker.proto",
s.RegisterService(&sd, nil)
}
// HandshakerServiceServer is the service API for HandshakerService service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type HandshakerServiceServer interface {
// Handshaker service accepts a stream of handshaker request, returning a
// stream of handshaker response. Client is expected to send exactly one
// message with either client_start or server_start followed by one or more
// messages with next. Each time client sends a request, the handshaker
// service expects to respond. Client does not have to wait for service's
// response before sending next request.
DoHandshake(HandshakerService_DoHandshakeServer) error
}
// UnimplementedHandshakerServiceServer can be embedded to have forward compatible implementations of
// HandshakerServiceServer
type UnimplementedHandshakerServiceServer struct {
}
func (UnimplementedHandshakerServiceServer) DoHandshake(HandshakerService_DoHandshakeServer) error {
return status.Errorf(codes.Unimplemented, "method DoHandshake not implemented")
}
// RegisterHandshakerServiceServer registers a service implementation with a gRPC server.
func RegisterHandshakerServiceServer(s grpc.ServiceRegistrar, srv HandshakerServiceServer) {
str := &HandshakerServiceService{
DoHandshake: srv.DoHandshake,
}
RegisterHandshakerServiceService(s, str)
} }

View File

@ -30,10 +30,6 @@ func NewMeshCertificateServiceClient(cc grpc.ClientConnInterface) MeshCertificat
return &meshCertificateServiceClient{cc} return &meshCertificateServiceClient{cc}
} }
var meshCertificateServiceCreateCertificateStreamDesc = &grpc.StreamDesc{
StreamName: "CreateCertificate",
}
func (c *meshCertificateServiceClient) CreateCertificate(ctx context.Context, in *MeshCertificateRequest, opts ...grpc.CallOption) (*MeshCertificateResponse, error) { func (c *meshCertificateServiceClient) CreateCertificate(ctx context.Context, in *MeshCertificateRequest, opts ...grpc.CallOption) (*MeshCertificateResponse, error) {
out := new(MeshCertificateResponse) out := new(MeshCertificateResponse)
err := c.cc.Invoke(ctx, "/google.security.meshca.v1.MeshCertificateService/CreateCertificate", in, out, opts...) err := c.cc.Invoke(ctx, "/google.security.meshca.v1.MeshCertificateService/CreateCertificate", in, out, opts...)
@ -43,80 +39,64 @@ func (c *meshCertificateServiceClient) CreateCertificate(ctx context.Context, in
return out, nil return out, nil
} }
// MeshCertificateServiceService is the service API for MeshCertificateService service. // MeshCertificateServiceServer is the server API for MeshCertificateService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedMeshCertificateServiceServer
// RegisterMeshCertificateServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error.
type MeshCertificateServiceService struct {
// Using provided CSR, returns a signed certificate that represents a GCP
// service account identity.
CreateCertificate func(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error)
}
func (s *MeshCertificateServiceService) createCertificate(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MeshCertificateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.CreateCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/google.security.meshca.v1.MeshCertificateService/CreateCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.CreateCertificate(ctx, req.(*MeshCertificateRequest))
}
return interceptor(ctx, in, info, handler)
}
// RegisterMeshCertificateServiceService registers a service implementation with a gRPC server.
func RegisterMeshCertificateServiceService(s grpc.ServiceRegistrar, srv *MeshCertificateServiceService) {
srvCopy := *srv
if srvCopy.CreateCertificate == nil {
srvCopy.CreateCertificate = func(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreateCertificate not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "google.security.meshca.v1.MeshCertificateService",
Methods: []grpc.MethodDesc{
{
MethodName: "CreateCertificate",
Handler: srvCopy.createCertificate,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "istio/google/security/meshca/v1/meshca.proto",
}
s.RegisterService(&sd, nil)
}
// MeshCertificateServiceServer is the service API for MeshCertificateService service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type MeshCertificateServiceServer interface { type MeshCertificateServiceServer interface {
// Using provided CSR, returns a signed certificate that represents a GCP // Using provided CSR, returns a signed certificate that represents a GCP
// service account identity. // service account identity.
CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error)
mustEmbedUnimplementedMeshCertificateServiceServer()
} }
// UnimplementedMeshCertificateServiceServer can be embedded to have forward compatible implementations of // UnimplementedMeshCertificateServiceServer must be embedded to have forward compatible implementations.
// MeshCertificateServiceServer
type UnimplementedMeshCertificateServiceServer struct { type UnimplementedMeshCertificateServiceServer struct {
} }
func (UnimplementedMeshCertificateServiceServer) CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) { func (UnimplementedMeshCertificateServiceServer) CreateCertificate(context.Context, *MeshCertificateRequest) (*MeshCertificateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreateCertificate not implemented") return nil, status.Errorf(codes.Unimplemented, "method CreateCertificate not implemented")
} }
func (UnimplementedMeshCertificateServiceServer) mustEmbedUnimplementedMeshCertificateServiceServer() {
// RegisterMeshCertificateServiceServer registers a service implementation with a gRPC server. }
func RegisterMeshCertificateServiceServer(s grpc.ServiceRegistrar, srv MeshCertificateServiceServer) {
str := &MeshCertificateServiceService{ // UnsafeMeshCertificateServiceServer may be embedded to opt out of forward compatibility for this service.
CreateCertificate: srv.CreateCertificate, // Use of this interface is not recommended, as added methods to MeshCertificateServiceServer will
} // result in compilation errors.
RegisterMeshCertificateServiceService(s, str) type UnsafeMeshCertificateServiceServer interface {
mustEmbedUnimplementedMeshCertificateServiceServer()
}
func RegisterMeshCertificateServiceServer(s *grpc.Server, srv MeshCertificateServiceServer) {
s.RegisterService(&_MeshCertificateService_serviceDesc, srv)
}
func _MeshCertificateService_CreateCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MeshCertificateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MeshCertificateServiceServer).CreateCertificate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/google.security.meshca.v1.MeshCertificateService/CreateCertificate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MeshCertificateServiceServer).CreateCertificate(ctx, req.(*MeshCertificateRequest))
}
return interceptor(ctx, in, info, handler)
}
var _MeshCertificateService_serviceDesc = grpc.ServiceDesc{
ServiceName: "google.security.meshca.v1.MeshCertificateService",
HandlerType: (*MeshCertificateServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "CreateCertificate",
Handler: _MeshCertificateService_CreateCertificate_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "istio/google/security/meshca/v1/meshca.proto",
} }

View File

@ -63,7 +63,7 @@ func main() {
grpc.Creds(credentials.NewServerTLSFromCert(&cert)), grpc.Creds(credentials.NewServerTLSFromCert(&cert)),
} }
s := grpc.NewServer(opts...) s := grpc.NewServer(opts...)
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &ecServer{})
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)) lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil { if err != nil {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
@ -73,7 +73,11 @@ func main() {
} }
} }
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { type ecServer struct {
pb.UnimplementedEchoServer
}
func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{Message: req.Message}, nil return &pb.EchoResponse{Message: req.Message}, nil
} }

View File

@ -33,7 +33,11 @@ import (
var port = flag.Int("port", 50051, "the port to serve on") var port = flag.Int("port", 50051, "the port to serve on")
func bidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { type server struct {
pb.UnimplementedEchoServer
}
func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
for { for {
in, err := stream.Recv() in, err := stream.Recv()
if err != nil { if err != nil {
@ -57,6 +61,6 @@ func main() {
} }
fmt.Printf("server listening at port %v\n", lis.Addr()) fmt.Printf("server listening at port %v\n", lis.Addr())
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterEchoService(s, &pb.EchoService{BidirectionalStreamingEcho: bidirectionalStreamingEcho}) pb.RegisterEchoServer(s, &server{})
s.Serve(lis) s.Serve(lis)
} }

View File

@ -34,7 +34,11 @@ import (
var port = flag.Int("port", 50051, "the port to serve on") var port = flag.Int("port", 50051, "the port to serve on")
func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { type server struct {
pb.UnimplementedEchoServer
}
func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
fmt.Printf("UnaryEcho called with message %q\n", in.GetMessage()) fmt.Printf("UnaryEcho called with message %q\n", in.GetMessage())
return &pb.EchoResponse{Message: in.Message}, nil return &pb.EchoResponse{Message: in.Message}, nil
} }
@ -49,6 +53,6 @@ func main() {
fmt.Printf("server listening at %v\n", lis.Addr()) fmt.Printf("server listening at %v\n", lis.Addr())
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &server{})
s.Serve(lis) s.Serve(lis)
} }

View File

@ -40,6 +40,7 @@ var port = flag.Int("port", 50052, "port number")
// server is used to implement EchoServer. // server is used to implement EchoServer.
type server struct { type server struct {
pb.UnimplementedEchoServer
client pb.EchoClient client pb.EchoClient
cc *grpc.ClientConn cc *grpc.ClientConn
} }
@ -111,12 +112,9 @@ func main() {
echoServer := newEchoServer() echoServer := newEchoServer()
defer echoServer.Close() defer echoServer.Close()
grpcServer := grpc.NewServer()
pb.RegisterEchoService(grpcServer, &pb.EchoService{ grpcServer := grpc.NewServer()
UnaryEcho: echoServer.UnaryEcho, pb.RegisterEchoServer(grpcServer, echoServer)
BidirectionalStreamingEcho: echoServer.BidirectionalStreamingEcho,
})
if err := grpcServer.Serve(lis); err != nil { if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -36,13 +36,23 @@ var (
ports = []string{":10001", ":10002", ":10003"} ports = []string{":10001", ":10002", ":10003"}
) )
// sayHello implements helloworld.GreeterServer.SayHello // server is used to implement helloworld.GreeterServer.
func sayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { type server struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil return &pb.HelloReply{Message: "Hello " + in.Name}, nil
} }
// sayHelloSlow implements helloworld.GreeterServer.SayHello // slow server is used to simulate a server that has a variable delay in its response.
func sayHelloSlow(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { type slowServer struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *slowServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
// Delay 100ms ~ 200ms before replying // Delay 100ms ~ 200ms before replying
time.Sleep(time.Duration(100+grpcrand.Intn(100)) * time.Millisecond) time.Sleep(time.Duration(100+grpcrand.Intn(100)) * time.Millisecond)
return &pb.HelloReply{Message: "Hello " + in.Name}, nil return &pb.HelloReply{Message: "Hello " + in.Name}, nil
@ -60,7 +70,7 @@ func main() {
go s.Serve(lis) go s.Serve(lis)
defer s.Stop() defer s.Stop()
/***** Start three GreeterServers(with one of them to be the slow server). *****/ /***** Start three GreeterServers(with one of them to be the slowServer). *****/
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
lis, err := net.Listen("tcp", ports[i]) lis, err := net.Listen("tcp", ports[i])
if err != nil { if err != nil {
@ -69,9 +79,9 @@ func main() {
defer lis.Close() defer lis.Close()
s := grpc.NewServer() s := grpc.NewServer()
if i == 2 { if i == 2 {
pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHelloSlow}) pb.RegisterGreeterServer(s, &slowServer{})
} else { } else {
pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHello}) pb.RegisterGreeterServer(s, &server{})
} }
go s.Serve(lis) go s.Serve(lis)
} }

View File

@ -34,7 +34,11 @@ import (
var port = flag.Int("port", 50051, "the port to serve on") var port = flag.Int("port", 50051, "the port to serve on")
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { type ecServer struct {
pb.UnimplementedEchoServer
}
func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{Message: req.Message}, nil return &pb.EchoResponse{Message: req.Message}, nil
} }
@ -50,8 +54,8 @@ func main() {
s := grpc.NewServer(grpc.Creds(altsTC)) s := grpc.NewServer(grpc.Creds(altsTC))
// Register EchoService on the server. // Register EchoServer on the server.
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &ecServer{})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -35,7 +35,11 @@ import (
var port = flag.Int("port", 50051, "the port to serve on") var port = flag.Int("port", 50051, "the port to serve on")
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { type ecServer struct {
pb.UnimplementedEchoServer
}
func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{Message: req.Message}, nil return &pb.EchoResponse{Message: req.Message}, nil
} }
@ -56,7 +60,7 @@ func main() {
s := grpc.NewServer(grpc.Creds(creds)) s := grpc.NewServer(grpc.Creds(creds))
// Register EchoServer on the server. // Register EchoServer on the server.
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &ecServer{})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -39,6 +39,7 @@ var port = flag.Int("port", 50052, "port number")
// server is used to implement helloworld.GreeterServer. // server is used to implement helloworld.GreeterServer.
type server struct { type server struct {
pb.UnimplementedGreeterServer
mu sync.Mutex mu sync.Mutex
count map[string]int count map[string]int
} }
@ -77,8 +78,7 @@ func main() {
} }
s := grpc.NewServer() s := grpc.NewServer()
hw := &server{count: make(map[string]int)} pb.RegisterGreeterServer(s, &server{count: make(map[string]int)})
pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: hw.SayHello})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)
} }

View File

@ -40,12 +40,18 @@ var (
system = "" // empty string represents the health of the system system = "" // empty string represents the health of the system
) )
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { type echoServer struct {
pb.UnimplementedEchoServer
}
func (e *echoServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{ return &pb.EchoResponse{
Message: fmt.Sprintf("hello from localhost:%d", *port), Message: fmt.Sprintf("hello from localhost:%d", *port),
}, nil }, nil
} }
var _ pb.EchoServer = &echoServer{}
func main() { func main() {
flag.Parse() flag.Parse()
@ -57,7 +63,7 @@ func main() {
s := grpc.NewServer() s := grpc.NewServer()
healthcheck := health.NewServer() healthcheck := health.NewServer()
healthpb.RegisterHealthServer(s, healthcheck) healthpb.RegisterHealthServer(s, healthcheck)
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &echoServer{})
go func() { go func() {
// asynchronously inspect dependencies and toggle serving status as needed // asynchronously inspect dependencies and toggle serving status as needed

View File

@ -51,12 +51,16 @@ func logger(format string, a ...interface{}) {
fmt.Printf("LOG:\t"+format+"\n", a...) fmt.Printf("LOG:\t"+format+"\n", a...)
} }
func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { type server struct {
pb.UnimplementedEchoServer
}
func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
fmt.Printf("unary echoing message %q\n", in.Message) fmt.Printf("unary echoing message %q\n", in.Message)
return &pb.EchoResponse{Message: in.Message}, nil return &pb.EchoResponse{Message: in.Message}, nil
} }
func bidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
for { for {
in, err := stream.Recv() in, err := stream.Recv()
if err != nil { if err != nil {
@ -152,11 +156,8 @@ func main() {
s := grpc.NewServer(grpc.Creds(creds), grpc.UnaryInterceptor(unaryInterceptor), grpc.StreamInterceptor(streamInterceptor)) s := grpc.NewServer(grpc.Creds(creds), grpc.UnaryInterceptor(unaryInterceptor), grpc.StreamInterceptor(streamInterceptor))
// Register EchoService on the server. // Register EchoServer on the server.
pb.RegisterEchoService(s, &pb.EchoService{ pb.RegisterEchoServer(s, &server{})
UnaryEcho: unaryEcho,
BidirectionalStreamingEcho: bidirectionalStreamingEcho,
})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -48,7 +48,12 @@ var kasp = keepalive.ServerParameters{
Timeout: 1 * time.Second, // Wait 1 second for the ping ack before assuming the connection is dead Timeout: 1 * time.Second, // Wait 1 second for the ping ack before assuming the connection is dead
} }
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { // server implements EchoServer.
type server struct {
pb.UnimplementedEchoServer
}
func (s *server) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{Message: req.Message}, nil return &pb.EchoResponse{Message: req.Message}, nil
} }
@ -62,7 +67,7 @@ func main() {
} }
s := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp)) s := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp))
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &server{})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -36,6 +36,7 @@ var (
) )
type ecServer struct { type ecServer struct {
pb.UnimplementedEchoServer
addr string addr string
} }
@ -49,8 +50,7 @@ func startServer(addr string) {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
e := &ecServer{addr: addr} pb.RegisterEchoServer(s, &ecServer{addr: addr})
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: e.UnaryEcho})
log.Printf("serving on %s\n", addr) log.Printf("serving on %s\n", addr)
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -44,7 +44,11 @@ const (
streamingCount = 10 streamingCount = 10
) )
func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { type server struct {
pb.UnimplementedEchoServer
}
func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
fmt.Printf("--- UnaryEcho ---\n") fmt.Printf("--- UnaryEcho ---\n")
// Create trailer in defer to record function return time. // Create trailer in defer to record function return time.
defer func() { defer func() {
@ -73,7 +77,7 @@ func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error
return &pb.EchoResponse{Message: in.Message}, nil return &pb.EchoResponse{Message: in.Message}, nil
} }
func serverStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error { func (s *server) ServerStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error {
fmt.Printf("--- ServerStreamingEcho ---\n") fmt.Printf("--- ServerStreamingEcho ---\n")
// Create trailer in defer to record function return time. // Create trailer in defer to record function return time.
defer func() { defer func() {
@ -110,7 +114,7 @@ func serverStreamingEcho(in *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoS
return nil return nil
} }
func clientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error { func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error {
fmt.Printf("--- ClientStreamingEcho ---\n") fmt.Printf("--- ClientStreamingEcho ---\n")
// Create trailer in defer to record function return time. // Create trailer in defer to record function return time.
defer func() { defer func() {
@ -150,7 +154,7 @@ func clientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error {
} }
} }
func bidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error { func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
fmt.Printf("--- BidirectionalStreamingEcho ---\n") fmt.Printf("--- BidirectionalStreamingEcho ---\n")
// Create trailer in defer to record function return time. // Create trailer in defer to record function return time.
defer func() { defer func() {
@ -201,11 +205,6 @@ func main() {
fmt.Printf("server listening at %v\n", lis.Addr()) fmt.Printf("server listening at %v\n", lis.Addr())
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterEchoService(s, &pb.EchoService{ pb.RegisterEchoServer(s, &server{})
UnaryEcho: unaryEcho,
ServerStreamingEcho: serverStreamingEcho,
ClientStreamingEcho: clientStreamingEcho,
BidirectionalStreamingEcho: bidirectionalStreamingEcho,
})
s.Serve(lis) s.Serve(lis)
} }

View File

@ -34,13 +34,21 @@ import (
var port = flag.Int("port", 50051, "the port to serve on") var port = flag.Int("port", 50051, "the port to serve on")
// sayHello implements helloworld.GreeterServer.SayHello // hwServer is used to implement helloworld.GreeterServer.
func sayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { type hwServer struct {
hwpb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *hwServer) SayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) {
return &hwpb.HelloReply{Message: "Hello " + in.Name}, nil return &hwpb.HelloReply{Message: "Hello " + in.Name}, nil
} }
// unaryEcho implements echo.Echo.UnaryEcho type ecServer struct {
func unaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { ecpb.UnimplementedEchoServer
}
func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) {
return &ecpb.EchoResponse{Message: req.Message}, nil return &ecpb.EchoResponse{Message: req.Message}, nil
} }
@ -55,10 +63,10 @@ func main() {
s := grpc.NewServer() s := grpc.NewServer()
// Register Greeter on the server. // Register Greeter on the server.
hwpb.RegisterGreeterService(s, &hwpb.GreeterService{SayHello: sayHello}) hwpb.RegisterGreeterServer(s, &hwServer{})
// Register Echo on the same server. // Register RouteGuide on the same server.
ecpb.RegisterEchoService(s, &ecpb.EchoService{UnaryEcho: unaryEcho}) ecpb.RegisterEchoServer(s, &ecServer{})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -32,8 +32,13 @@ import (
const addr = "localhost:50051" const addr = "localhost:50051"
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { type ecServer struct {
return &pb.EchoResponse{Message: fmt.Sprintf("%s (from %s)", req.Message, addr)}, nil pb.UnimplementedEchoServer
addr string
}
func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{Message: fmt.Sprintf("%s (from %s)", req.Message, s.addr)}, nil
} }
func main() { func main() {
@ -42,7 +47,7 @@ func main() {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &ecServer{addr: addr})
log.Printf("serving on %s\n", addr) log.Printf("serving on %s\n", addr)
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -41,7 +41,7 @@ type server struct{}
func main() error { func main() error {
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterEchoService(s, &pb.EchoService{...}) pb.RegisterEchoServer(s, &server{})
// Include this to register a profiling-specific service within your server. // Include this to register a profiling-specific service within your server.
if err := profsvc.Init(&profsvc.ProfilingConfig{Server: s}); err != nil { if err := profsvc.Init(&profsvc.ProfilingConfig{Server: s}); err != nil {

View File

@ -33,7 +33,11 @@ import (
var port = flag.Int("port", 50051, "the port to serve on") var port = flag.Int("port", 50051, "the port to serve on")
func unaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) { type server struct {
pb.UnimplementedEchoServer
}
func (s *server) UnaryEcho(ctx context.Context, in *pb.EchoRequest) (*pb.EchoResponse, error) {
fmt.Printf("UnaryEcho called with message %q\n", in.GetMessage()) fmt.Printf("UnaryEcho called with message %q\n", in.GetMessage())
return &pb.EchoResponse{Message: in.Message}, nil return &pb.EchoResponse{Message: in.Message}, nil
} }
@ -48,7 +52,7 @@ func main() {
fmt.Printf("server listening at %v\n", lis.Addr()) fmt.Printf("server listening at %v\n", lis.Addr())
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &server{})
// Register your grpc.Server with profiling. // Register your grpc.Server with profiling.
pc := &profsvc.ProfilingConfig{ pc := &profsvc.ProfilingConfig{

View File

@ -35,10 +35,6 @@ func NewEchoClient(cc grpc.ClientConnInterface) EchoClient {
return &echoClient{cc} return &echoClient{cc}
} }
var echoUnaryEchoStreamDesc = &grpc.StreamDesc{
StreamName: "UnaryEcho",
}
func (c *echoClient) UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error) { func (c *echoClient) UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error) {
out := new(EchoResponse) out := new(EchoResponse)
err := c.cc.Invoke(ctx, "/grpc.examples.echo.Echo/UnaryEcho", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.examples.echo.Echo/UnaryEcho", in, out, opts...)
@ -48,13 +44,8 @@ func (c *echoClient) UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grp
return out, nil return out, nil
} }
var echoServerStreamingEchoStreamDesc = &grpc.StreamDesc{
StreamName: "ServerStreamingEcho",
ServerStreams: true,
}
func (c *echoClient) ServerStreamingEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (Echo_ServerStreamingEchoClient, error) { func (c *echoClient) ServerStreamingEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (Echo_ServerStreamingEchoClient, error) {
stream, err := c.cc.NewStream(ctx, echoServerStreamingEchoStreamDesc, "/grpc.examples.echo.Echo/ServerStreamingEcho", opts...) stream, err := c.cc.NewStream(ctx, &_Echo_serviceDesc.Streams[0], "/grpc.examples.echo.Echo/ServerStreamingEcho", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -85,13 +76,8 @@ func (x *echoServerStreamingEchoClient) Recv() (*EchoResponse, error) {
return m, nil return m, nil
} }
var echoClientStreamingEchoStreamDesc = &grpc.StreamDesc{
StreamName: "ClientStreamingEcho",
ClientStreams: true,
}
func (c *echoClient) ClientStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (Echo_ClientStreamingEchoClient, error) { func (c *echoClient) ClientStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (Echo_ClientStreamingEchoClient, error) {
stream, err := c.cc.NewStream(ctx, echoClientStreamingEchoStreamDesc, "/grpc.examples.echo.Echo/ClientStreamingEcho", opts...) stream, err := c.cc.NewStream(ctx, &_Echo_serviceDesc.Streams[1], "/grpc.examples.echo.Echo/ClientStreamingEcho", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -124,14 +110,8 @@ func (x *echoClientStreamingEchoClient) CloseAndRecv() (*EchoResponse, error) {
return m, nil return m, nil
} }
var echoBidirectionalStreamingEchoStreamDesc = &grpc.StreamDesc{
StreamName: "BidirectionalStreamingEcho",
ServerStreams: true,
ClientStreams: true,
}
func (c *echoClient) BidirectionalStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (Echo_BidirectionalStreamingEchoClient, error) { func (c *echoClient) BidirectionalStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (Echo_BidirectionalStreamingEchoClient, error) {
stream, err := c.cc.NewStream(ctx, echoBidirectionalStreamingEchoStreamDesc, "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", opts...) stream, err := c.cc.NewStream(ctx, &_Echo_serviceDesc.Streams[2], "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -161,50 +141,74 @@ func (x *echoBidirectionalStreamingEchoClient) Recv() (*EchoResponse, error) {
return m, nil return m, nil
} }
// EchoService is the service API for Echo service. // EchoServer is the server API for Echo service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedEchoServer
// RegisterEchoService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type EchoServer interface {
type EchoService struct {
// UnaryEcho is unary echo. // UnaryEcho is unary echo.
UnaryEcho func(context.Context, *EchoRequest) (*EchoResponse, error) UnaryEcho(context.Context, *EchoRequest) (*EchoResponse, error)
// ServerStreamingEcho is server side streaming. // ServerStreamingEcho is server side streaming.
ServerStreamingEcho func(*EchoRequest, Echo_ServerStreamingEchoServer) error ServerStreamingEcho(*EchoRequest, Echo_ServerStreamingEchoServer) error
// ClientStreamingEcho is client side streaming. // ClientStreamingEcho is client side streaming.
ClientStreamingEcho func(Echo_ClientStreamingEchoServer) error ClientStreamingEcho(Echo_ClientStreamingEchoServer) error
// BidirectionalStreamingEcho is bidi streaming. // BidirectionalStreamingEcho is bidi streaming.
BidirectionalStreamingEcho func(Echo_BidirectionalStreamingEchoServer) error BidirectionalStreamingEcho(Echo_BidirectionalStreamingEchoServer) error
mustEmbedUnimplementedEchoServer()
} }
func (s *EchoService) unaryEcho(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedEchoServer must be embedded to have forward compatible implementations.
type UnimplementedEchoServer struct {
}
func (UnimplementedEchoServer) UnaryEcho(context.Context, *EchoRequest) (*EchoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryEcho not implemented")
}
func (UnimplementedEchoServer) ServerStreamingEcho(*EchoRequest, Echo_ServerStreamingEchoServer) error {
return status.Errorf(codes.Unimplemented, "method ServerStreamingEcho not implemented")
}
func (UnimplementedEchoServer) ClientStreamingEcho(Echo_ClientStreamingEchoServer) error {
return status.Errorf(codes.Unimplemented, "method ClientStreamingEcho not implemented")
}
func (UnimplementedEchoServer) BidirectionalStreamingEcho(Echo_BidirectionalStreamingEchoServer) error {
return status.Errorf(codes.Unimplemented, "method BidirectionalStreamingEcho not implemented")
}
func (UnimplementedEchoServer) mustEmbedUnimplementedEchoServer() {}
// UnsafeEchoServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to EchoServer will
// result in compilation errors.
type UnsafeEchoServer interface {
mustEmbedUnimplementedEchoServer()
}
func RegisterEchoServer(s *grpc.Server, srv EchoServer) {
s.RegisterService(&_Echo_serviceDesc, srv)
}
func _Echo_UnaryEcho_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EchoRequest) in := new(EchoRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.UnaryEcho(ctx, in) return srv.(EchoServer).UnaryEcho(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.examples.echo.Echo/UnaryEcho", FullMethod: "/grpc.examples.echo.Echo/UnaryEcho",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.UnaryEcho(ctx, req.(*EchoRequest)) return srv.(EchoServer).UnaryEcho(ctx, req.(*EchoRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *EchoService) serverStreamingEcho(_ interface{}, stream grpc.ServerStream) error {
func _Echo_ServerStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(EchoRequest) m := new(EchoRequest)
if err := stream.RecvMsg(m); err != nil { if err := stream.RecvMsg(m); err != nil {
return err return err
} }
return s.ServerStreamingEcho(m, &echoServerStreamingEchoServer{stream}) return srv.(EchoServer).ServerStreamingEcho(m, &echoServerStreamingEchoServer{stream})
}
func (s *EchoService) clientStreamingEcho(_ interface{}, stream grpc.ServerStream) error {
return s.ClientStreamingEcho(&echoClientStreamingEchoServer{stream})
}
func (s *EchoService) bidirectionalStreamingEcho(_ interface{}, stream grpc.ServerStream) error {
return s.BidirectionalStreamingEcho(&echoBidirectionalStreamingEchoServer{stream})
} }
type Echo_ServerStreamingEchoServer interface { type Echo_ServerStreamingEchoServer interface {
@ -220,6 +224,10 @@ func (x *echoServerStreamingEchoServer) Send(m *EchoResponse) error {
return x.ServerStream.SendMsg(m) return x.ServerStream.SendMsg(m)
} }
func _Echo_ClientStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(EchoServer).ClientStreamingEcho(&echoClientStreamingEchoServer{stream})
}
type Echo_ClientStreamingEchoServer interface { type Echo_ClientStreamingEchoServer interface {
SendAndClose(*EchoResponse) error SendAndClose(*EchoResponse) error
Recv() (*EchoRequest, error) Recv() (*EchoRequest, error)
@ -242,6 +250,10 @@ func (x *echoClientStreamingEchoServer) Recv() (*EchoRequest, error) {
return m, nil return m, nil
} }
func _Echo_BidirectionalStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(EchoServer).BidirectionalStreamingEcho(&echoBidirectionalStreamingEchoServer{stream})
}
type Echo_BidirectionalStreamingEchoServer interface { type Echo_BidirectionalStreamingEchoServer interface {
Send(*EchoResponse) error Send(*EchoResponse) error
Recv() (*EchoRequest, error) Recv() (*EchoRequest, error)
@ -264,57 +276,32 @@ func (x *echoBidirectionalStreamingEchoServer) Recv() (*EchoRequest, error) {
return m, nil return m, nil
} }
// RegisterEchoService registers a service implementation with a gRPC server. var _Echo_serviceDesc = grpc.ServiceDesc{
func RegisterEchoService(s grpc.ServiceRegistrar, srv *EchoService) { ServiceName: "grpc.examples.echo.Echo",
srvCopy := *srv HandlerType: (*EchoServer)(nil),
if srvCopy.UnaryEcho == nil { Methods: []grpc.MethodDesc{
srvCopy.UnaryEcho = func(context.Context, *EchoRequest) (*EchoResponse, error) { {
return nil, status.Errorf(codes.Unimplemented, "method UnaryEcho not implemented") MethodName: "UnaryEcho",
} Handler: _Echo_UnaryEcho_Handler,
}
if srvCopy.ServerStreamingEcho == nil {
srvCopy.ServerStreamingEcho = func(*EchoRequest, Echo_ServerStreamingEchoServer) error {
return status.Errorf(codes.Unimplemented, "method ServerStreamingEcho not implemented")
}
}
if srvCopy.ClientStreamingEcho == nil {
srvCopy.ClientStreamingEcho = func(Echo_ClientStreamingEchoServer) error {
return status.Errorf(codes.Unimplemented, "method ClientStreamingEcho not implemented")
}
}
if srvCopy.BidirectionalStreamingEcho == nil {
srvCopy.BidirectionalStreamingEcho = func(Echo_BidirectionalStreamingEchoServer) error {
return status.Errorf(codes.Unimplemented, "method BidirectionalStreamingEcho not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.examples.echo.Echo",
Methods: []grpc.MethodDesc{
{
MethodName: "UnaryEcho",
Handler: srvCopy.unaryEcho,
},
}, },
Streams: []grpc.StreamDesc{ },
{ Streams: []grpc.StreamDesc{
StreamName: "ServerStreamingEcho", {
Handler: srvCopy.serverStreamingEcho, StreamName: "ServerStreamingEcho",
ServerStreams: true, Handler: _Echo_ServerStreamingEcho_Handler,
}, ServerStreams: true,
{
StreamName: "ClientStreamingEcho",
Handler: srvCopy.clientStreamingEcho,
ClientStreams: true,
},
{
StreamName: "BidirectionalStreamingEcho",
Handler: srvCopy.bidirectionalStreamingEcho,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "examples/features/proto/echo/echo.proto", {
} StreamName: "ClientStreamingEcho",
Handler: _Echo_ClientStreamingEcho_Handler,
s.RegisterService(&sd, nil) ClientStreams: true,
},
{
StreamName: "BidirectionalStreamingEcho",
Handler: _Echo_BidirectionalStreamingEcho_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "examples/features/proto/echo/echo.proto",
} }

View File

@ -35,13 +35,21 @@ import (
var port = flag.Int("port", 50051, "the port to serve on") var port = flag.Int("port", 50051, "the port to serve on")
// sayHello implements helloworld.GreeterServer.SayHello // hwServer is used to implement helloworld.GreeterServer.
func sayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { type hwServer struct {
hwpb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *hwServer) SayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) {
return &hwpb.HelloReply{Message: "Hello " + in.Name}, nil return &hwpb.HelloReply{Message: "Hello " + in.Name}, nil
} }
// unaryEcho implements echo.Echo.UnaryEcho type ecServer struct {
func unaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { ecpb.UnimplementedEchoServer
}
func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) {
return &ecpb.EchoResponse{Message: req.Message}, nil return &ecpb.EchoResponse{Message: req.Message}, nil
} }
@ -56,10 +64,10 @@ func main() {
s := grpc.NewServer() s := grpc.NewServer()
// Register Greeter on the server. // Register Greeter on the server.
hwpb.RegisterGreeterService(s, &hwpb.GreeterService{SayHello: sayHello}) hwpb.RegisterGreeterServer(s, &hwServer{})
// Register RouteGuide on the same server. // Register RouteGuide on the same server.
ecpb.RegisterEchoService(s, &ecpb.EchoService{UnaryEcho: unaryEcho}) ecpb.RegisterEchoServer(s, &ecServer{})
// Register reflection service on gRPC server. // Register reflection service on gRPC server.
reflection.Register(s) reflection.Register(s)

View File

@ -37,6 +37,7 @@ import (
var port = flag.Int("port", 50052, "port number") var port = flag.Int("port", 50052, "port number")
type failingServer struct { type failingServer struct {
pb.UnimplementedEchoServer
mu sync.Mutex mu sync.Mutex
reqCounter uint reqCounter uint
@ -85,7 +86,7 @@ func main() {
reqModulo: 4, reqModulo: 4,
} }
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: failingservice.UnaryEcho}) pb.RegisterEchoServer(s, failingservice)
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)
} }

View File

@ -34,7 +34,12 @@ import (
pb "google.golang.org/grpc/examples/features/proto/echo" pb "google.golang.org/grpc/examples/features/proto/echo"
) )
func unaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { // server is used to implement EchoServer.
type server struct {
pb.UnimplementedEchoServer
}
func (s *server) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{Message: req.Message}, nil return &pb.EchoResponse{Message: req.Message}, nil
} }
@ -45,7 +50,7 @@ func serve() {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterEchoService(s, &pb.EchoService{UnaryEcho: unaryEcho}) pb.RegisterEchoServer(s, &server{})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)

View File

@ -45,6 +45,8 @@ const (
// server is used to implement helloworld.GreeterServer. // server is used to implement helloworld.GreeterServer.
type server struct { type server struct {
pb.UnimplementedGreeterServer
serverName string serverName string
} }
@ -122,8 +124,7 @@ func main() {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
hw := newServer(hostname) pb.RegisterGreeterServer(s, newServer(hostname))
pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: hw.SayHello})
reflection.Register(s) reflection.Register(s)
healthServer := health.NewServer() healthServer := health.NewServer()

View File

@ -268,13 +268,7 @@ if err != nil {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
} }
grpcServer := grpc.NewServer() grpcServer := grpc.NewServer()
rgs := &routeGuideServer{} pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
pb.RegisterRouteGuideService(grpcServer, pb.RouteGuideService{
GetFeature: rgs.GetFeature,
ListFeatures: rgs.ListFeatures,
RecordRoute: rgs.RecordRoute,
RouteChat: rgs.RouteChat,
})
... // determine whether to use TLS ... // determine whether to use TLS
grpcServer.Serve(lis) grpcServer.Serve(lis)
``` ```

View File

@ -32,8 +32,13 @@ const (
port = ":50051" port = ":50051"
) )
// sayHello implements helloworld.GreeterServer.SayHello // server is used to implement helloworld.GreeterServer.
func sayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { type server struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.GetName()) log.Printf("Received: %v", in.GetName())
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
} }
@ -44,7 +49,7 @@ func main() {
log.Fatalf("failed to listen: %v", err) log.Fatalf("failed to listen: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHello}) pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil { if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err) log.Fatalf("failed to serve: %v", err)
} }

View File

@ -29,10 +29,6 @@ func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
return &greeterClient{cc} return &greeterClient{cc}
} }
var greeterSayHelloStreamDesc = &grpc.StreamDesc{
StreamName: "SayHello",
}
func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) {
out := new(HelloReply) out := new(HelloReply)
err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...)
@ -42,52 +38,62 @@ func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...
return out, nil return out, nil
} }
// GreeterService is the service API for Greeter service. // GreeterServer is the server API for Greeter service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedGreeterServer
// RegisterGreeterService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type GreeterServer interface {
type GreeterService struct {
// Sends a greeting // Sends a greeting
SayHello func(context.Context, *HelloRequest) (*HelloReply, error) SayHello(context.Context, *HelloRequest) (*HelloReply, error)
mustEmbedUnimplementedGreeterServer()
} }
func (s *GreeterService) sayHello(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedGreeterServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}
func (UnimplementedGreeterServer) SayHello(context.Context, *HelloRequest) (*HelloReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented")
}
func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}
// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServer will
// result in compilation errors.
type UnsafeGreeterServer interface {
mustEmbedUnimplementedGreeterServer()
}
func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) {
s.RegisterService(&_Greeter_serviceDesc, srv)
}
func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HelloRequest) in := new(HelloRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.SayHello(ctx, in) return srv.(GreeterServer).SayHello(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/helloworld.Greeter/SayHello", FullMethod: "/helloworld.Greeter/SayHello",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.SayHello(ctx, req.(*HelloRequest)) return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
// RegisterGreeterService registers a service implementation with a gRPC server. var _Greeter_serviceDesc = grpc.ServiceDesc{
func RegisterGreeterService(s grpc.ServiceRegistrar, srv *GreeterService) { ServiceName: "helloworld.Greeter",
srvCopy := *srv HandlerType: (*GreeterServer)(nil),
if srvCopy.SayHello == nil { Methods: []grpc.MethodDesc{
srvCopy.SayHello = func(context.Context, *HelloRequest) (*HelloReply, error) { {
return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") MethodName: "SayHello",
} Handler: _Greeter_SayHello_Handler,
}
sd := grpc.ServiceDesc{
ServiceName: "helloworld.Greeter",
Methods: []grpc.MethodDesc{
{
MethodName: "SayHello",
Handler: srvCopy.sayHello,
},
}, },
Streams: []grpc.StreamDesc{}, },
Metadata: "examples/helloworld/helloworld/helloworld.proto", Streams: []grpc.StreamDesc{},
} Metadata: "examples/helloworld/helloworld/helloworld.proto",
s.RegisterService(&sd, nil)
} }

View File

@ -51,10 +51,6 @@ func NewRouteGuideClient(cc grpc.ClientConnInterface) RouteGuideClient {
return &routeGuideClient{cc} return &routeGuideClient{cc}
} }
var routeGuideGetFeatureStreamDesc = &grpc.StreamDesc{
StreamName: "GetFeature",
}
func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) { func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) {
out := new(Feature) out := new(Feature)
err := c.cc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, opts...) err := c.cc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, opts...)
@ -64,13 +60,8 @@ func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...gr
return out, nil return out, nil
} }
var routeGuideListFeaturesStreamDesc = &grpc.StreamDesc{
StreamName: "ListFeatures",
ServerStreams: true,
}
func (c *routeGuideClient) ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) { func (c *routeGuideClient) ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) {
stream, err := c.cc.NewStream(ctx, routeGuideListFeaturesStreamDesc, "/routeguide.RouteGuide/ListFeatures", opts...) stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[0], "/routeguide.RouteGuide/ListFeatures", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -101,13 +92,8 @@ func (x *routeGuideListFeaturesClient) Recv() (*Feature, error) {
return m, nil return m, nil
} }
var routeGuideRecordRouteStreamDesc = &grpc.StreamDesc{
StreamName: "RecordRoute",
ClientStreams: true,
}
func (c *routeGuideClient) RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) { func (c *routeGuideClient) RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) {
stream, err := c.cc.NewStream(ctx, routeGuideRecordRouteStreamDesc, "/routeguide.RouteGuide/RecordRoute", opts...) stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[1], "/routeguide.RouteGuide/RecordRoute", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -140,14 +126,8 @@ func (x *routeGuideRecordRouteClient) CloseAndRecv() (*RouteSummary, error) {
return m, nil return m, nil
} }
var routeGuideRouteChatStreamDesc = &grpc.StreamDesc{
StreamName: "RouteChat",
ServerStreams: true,
ClientStreams: true,
}
func (c *routeGuideClient) RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) { func (c *routeGuideClient) RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) {
stream, err := c.cc.NewStream(ctx, routeGuideRouteChatStreamDesc, "/routeguide.RouteGuide/RouteChat", opts...) stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[2], "/routeguide.RouteGuide/RouteChat", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -177,66 +157,90 @@ func (x *routeGuideRouteChatClient) Recv() (*RouteNote, error) {
return m, nil return m, nil
} }
// RouteGuideService is the service API for RouteGuide service. // RouteGuideServer is the server API for RouteGuide service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedRouteGuideServer
// RegisterRouteGuideService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type RouteGuideServer interface {
type RouteGuideService struct {
// A simple RPC. // A simple RPC.
// //
// Obtains the feature at a given position. // Obtains the feature at a given position.
// //
// A feature with an empty name is returned if there's no feature at the given // A feature with an empty name is returned if there's no feature at the given
// position. // position.
GetFeature func(context.Context, *Point) (*Feature, error) GetFeature(context.Context, *Point) (*Feature, error)
// A server-to-client streaming RPC. // A server-to-client streaming RPC.
// //
// Obtains the Features available within the given Rectangle. Results are // Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a // streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a // repeated field), as the rectangle may cover a large area and contain a
// huge number of features. // huge number of features.
ListFeatures func(*Rectangle, RouteGuide_ListFeaturesServer) error ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error
// A client-to-server streaming RPC. // A client-to-server streaming RPC.
// //
// Accepts a stream of Points on a route being traversed, returning a // Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed. // RouteSummary when traversal is completed.
RecordRoute func(RouteGuide_RecordRouteServer) error RecordRoute(RouteGuide_RecordRouteServer) error
// A Bidirectional streaming RPC. // A Bidirectional streaming RPC.
// //
// Accepts a stream of RouteNotes sent while a route is being traversed, // Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users). // while receiving other RouteNotes (e.g. from other users).
RouteChat func(RouteGuide_RouteChatServer) error RouteChat(RouteGuide_RouteChatServer) error
mustEmbedUnimplementedRouteGuideServer()
} }
func (s *RouteGuideService) getFeature(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedRouteGuideServer must be embedded to have forward compatible implementations.
type UnimplementedRouteGuideServer struct {
}
func (UnimplementedRouteGuideServer) GetFeature(context.Context, *Point) (*Feature, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFeature not implemented")
}
func (UnimplementedRouteGuideServer) ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error {
return status.Errorf(codes.Unimplemented, "method ListFeatures not implemented")
}
func (UnimplementedRouteGuideServer) RecordRoute(RouteGuide_RecordRouteServer) error {
return status.Errorf(codes.Unimplemented, "method RecordRoute not implemented")
}
func (UnimplementedRouteGuideServer) RouteChat(RouteGuide_RouteChatServer) error {
return status.Errorf(codes.Unimplemented, "method RouteChat not implemented")
}
func (UnimplementedRouteGuideServer) mustEmbedUnimplementedRouteGuideServer() {}
// UnsafeRouteGuideServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to RouteGuideServer will
// result in compilation errors.
type UnsafeRouteGuideServer interface {
mustEmbedUnimplementedRouteGuideServer()
}
func RegisterRouteGuideServer(s *grpc.Server, srv RouteGuideServer) {
s.RegisterService(&_RouteGuide_serviceDesc, srv)
}
func _RouteGuide_GetFeature_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Point) in := new(Point)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.GetFeature(ctx, in) return srv.(RouteGuideServer).GetFeature(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/routeguide.RouteGuide/GetFeature", FullMethod: "/routeguide.RouteGuide/GetFeature",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetFeature(ctx, req.(*Point)) return srv.(RouteGuideServer).GetFeature(ctx, req.(*Point))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *RouteGuideService) listFeatures(_ interface{}, stream grpc.ServerStream) error {
func _RouteGuide_ListFeatures_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(Rectangle) m := new(Rectangle)
if err := stream.RecvMsg(m); err != nil { if err := stream.RecvMsg(m); err != nil {
return err return err
} }
return s.ListFeatures(m, &routeGuideListFeaturesServer{stream}) return srv.(RouteGuideServer).ListFeatures(m, &routeGuideListFeaturesServer{stream})
}
func (s *RouteGuideService) recordRoute(_ interface{}, stream grpc.ServerStream) error {
return s.RecordRoute(&routeGuideRecordRouteServer{stream})
}
func (s *RouteGuideService) routeChat(_ interface{}, stream grpc.ServerStream) error {
return s.RouteChat(&routeGuideRouteChatServer{stream})
} }
type RouteGuide_ListFeaturesServer interface { type RouteGuide_ListFeaturesServer interface {
@ -252,6 +256,10 @@ func (x *routeGuideListFeaturesServer) Send(m *Feature) error {
return x.ServerStream.SendMsg(m) return x.ServerStream.SendMsg(m)
} }
func _RouteGuide_RecordRoute_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(RouteGuideServer).RecordRoute(&routeGuideRecordRouteServer{stream})
}
type RouteGuide_RecordRouteServer interface { type RouteGuide_RecordRouteServer interface {
SendAndClose(*RouteSummary) error SendAndClose(*RouteSummary) error
Recv() (*Point, error) Recv() (*Point, error)
@ -274,6 +282,10 @@ func (x *routeGuideRecordRouteServer) Recv() (*Point, error) {
return m, nil return m, nil
} }
func _RouteGuide_RouteChat_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(RouteGuideServer).RouteChat(&routeGuideRouteChatServer{stream})
}
type RouteGuide_RouteChatServer interface { type RouteGuide_RouteChatServer interface {
Send(*RouteNote) error Send(*RouteNote) error
Recv() (*RouteNote, error) Recv() (*RouteNote, error)
@ -296,57 +308,32 @@ func (x *routeGuideRouteChatServer) Recv() (*RouteNote, error) {
return m, nil return m, nil
} }
// RegisterRouteGuideService registers a service implementation with a gRPC server. var _RouteGuide_serviceDesc = grpc.ServiceDesc{
func RegisterRouteGuideService(s grpc.ServiceRegistrar, srv *RouteGuideService) { ServiceName: "routeguide.RouteGuide",
srvCopy := *srv HandlerType: (*RouteGuideServer)(nil),
if srvCopy.GetFeature == nil { Methods: []grpc.MethodDesc{
srvCopy.GetFeature = func(context.Context, *Point) (*Feature, error) { {
return nil, status.Errorf(codes.Unimplemented, "method GetFeature not implemented") MethodName: "GetFeature",
} Handler: _RouteGuide_GetFeature_Handler,
}
if srvCopy.ListFeatures == nil {
srvCopy.ListFeatures = func(*Rectangle, RouteGuide_ListFeaturesServer) error {
return status.Errorf(codes.Unimplemented, "method ListFeatures not implemented")
}
}
if srvCopy.RecordRoute == nil {
srvCopy.RecordRoute = func(RouteGuide_RecordRouteServer) error {
return status.Errorf(codes.Unimplemented, "method RecordRoute not implemented")
}
}
if srvCopy.RouteChat == nil {
srvCopy.RouteChat = func(RouteGuide_RouteChatServer) error {
return status.Errorf(codes.Unimplemented, "method RouteChat not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "routeguide.RouteGuide",
Methods: []grpc.MethodDesc{
{
MethodName: "GetFeature",
Handler: srvCopy.getFeature,
},
}, },
Streams: []grpc.StreamDesc{ },
{ Streams: []grpc.StreamDesc{
StreamName: "ListFeatures", {
Handler: srvCopy.listFeatures, StreamName: "ListFeatures",
ServerStreams: true, Handler: _RouteGuide_ListFeatures_Handler,
}, ServerStreams: true,
{
StreamName: "RecordRoute",
Handler: srvCopy.recordRoute,
ClientStreams: true,
},
{
StreamName: "RouteChat",
Handler: srvCopy.routeChat,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "examples/route_guide/routeguide/route_guide.proto", {
} StreamName: "RecordRoute",
Handler: _RouteGuide_RecordRoute_Handler,
s.RegisterService(&sd, nil) ClientStreams: true,
},
{
StreamName: "RouteChat",
Handler: _RouteGuide_RouteChat_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "examples/route_guide/routeguide/route_guide.proto",
} }

View File

@ -54,21 +54,13 @@ var (
) )
type routeGuideServer struct { type routeGuideServer struct {
pb.UnimplementedRouteGuideServer
savedFeatures []*pb.Feature // read-only after initialized savedFeatures []*pb.Feature // read-only after initialized
mu sync.Mutex // protects routeNotes mu sync.Mutex // protects routeNotes
routeNotes map[string][]*pb.RouteNote routeNotes map[string][]*pb.RouteNote
} }
func (s *routeGuideServer) Svc() *pb.RouteGuideService {
return &pb.RouteGuideService{
GetFeature: s.GetFeature,
ListFeatures: s.ListFeatures,
RecordRoute: s.RecordRoute,
RouteChat: s.RouteChat,
}
}
// GetFeature returns the feature at the given point. // GetFeature returns the feature at the given point.
func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
for _, feature := range s.savedFeatures { for _, feature := range s.savedFeatures {
@ -246,7 +238,7 @@ func main() {
opts = []grpc.ServerOption{grpc.Creds(creds)} opts = []grpc.ServerOption{grpc.Creds(creds)}
} }
grpcServer := grpc.NewServer(opts...) grpcServer := grpc.NewServer(opts...)
pb.RegisterRouteGuideService(grpcServer, newServer().Svc()) pb.RegisterRouteGuideServer(grpcServer, newServer())
grpcServer.Serve(lis) grpcServer.Serve(lis)
} }

View File

@ -46,10 +46,6 @@ func NewHealthClient(cc grpc.ClientConnInterface) HealthClient {
return &healthClient{cc} return &healthClient{cc}
} }
var healthCheckStreamDesc = &grpc.StreamDesc{
StreamName: "Check",
}
func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) {
out := new(HealthCheckResponse) out := new(HealthCheckResponse)
err := c.cc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, opts...)
@ -59,13 +55,8 @@ func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts .
return out, nil return out, nil
} }
var healthWatchStreamDesc = &grpc.StreamDesc{
StreamName: "Watch",
ServerStreams: true,
}
func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) { func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) {
stream, err := c.cc.NewStream(ctx, healthWatchStreamDesc, "/grpc.health.v1.Health/Watch", opts...) stream, err := c.cc.NewStream(ctx, &_Health_serviceDesc.Streams[0], "/grpc.health.v1.Health/Watch", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -96,108 +87,9 @@ func (x *healthWatchClient) Recv() (*HealthCheckResponse, error) {
return m, nil return m, nil
} }
// HealthService is the service API for Health service. // HealthServer is the server API for Health service.
// Fields should be assigned to their respective handler implementations only before // All implementations should embed UnimplementedHealthServer
// RegisterHealthService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error.
type HealthService struct {
// If the requested service is unknown, the call will fail with status
// NOT_FOUND.
Check func(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error)
// Performs a watch for the serving status of the requested service.
// The server will immediately send back a message indicating the current
// serving status. It will then subsequently send a new message whenever
// the service's serving status changes.
//
// If the requested service is unknown when the call is received, the
// server will send a message setting the serving status to
// SERVICE_UNKNOWN but will *not* terminate the call. If at some
// future point, the serving status of the service becomes known, the
// server will send a new message with the service's serving status.
//
// If the call terminates with status UNIMPLEMENTED, then clients
// should assume this method is not supported and should not retry the
// call. If the call terminates with any other status (including OK),
// clients should retry the call with appropriate exponential backoff.
Watch func(*HealthCheckRequest, Health_WatchServer) error
}
func (s *HealthService) check(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HealthCheckRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.Check(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.health.v1.Health/Check",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.Check(ctx, req.(*HealthCheckRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *HealthService) watch(_ interface{}, stream grpc.ServerStream) error {
m := new(HealthCheckRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return s.Watch(m, &healthWatchServer{stream})
}
type Health_WatchServer interface {
Send(*HealthCheckResponse) error
grpc.ServerStream
}
type healthWatchServer struct {
grpc.ServerStream
}
func (x *healthWatchServer) Send(m *HealthCheckResponse) error {
return x.ServerStream.SendMsg(m)
}
// RegisterHealthService registers a service implementation with a gRPC server.
func RegisterHealthService(s grpc.ServiceRegistrar, srv *HealthService) {
srvCopy := *srv
if srvCopy.Check == nil {
srvCopy.Check = func(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Check not implemented")
}
}
if srvCopy.Watch == nil {
srvCopy.Watch = func(*HealthCheckRequest, Health_WatchServer) error {
return status.Errorf(codes.Unimplemented, "method Watch not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.health.v1.Health",
Methods: []grpc.MethodDesc{
{
MethodName: "Check",
Handler: srvCopy.check,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "Watch",
Handler: srvCopy.watch,
ServerStreams: true,
},
},
Metadata: "grpc/health/v1/health.proto",
}
s.RegisterService(&sd, nil)
}
// HealthServer is the service API for Health service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type HealthServer interface { type HealthServer interface {
// If the requested service is unknown, the call will fail with status // If the requested service is unknown, the call will fail with status
// NOT_FOUND. // NOT_FOUND.
@ -220,8 +112,7 @@ type HealthServer interface {
Watch(*HealthCheckRequest, Health_WatchServer) error Watch(*HealthCheckRequest, Health_WatchServer) error
} }
// UnimplementedHealthServer can be embedded to have forward compatible implementations of // UnimplementedHealthServer should be embedded to have forward compatible implementations.
// HealthServer
type UnimplementedHealthServer struct { type UnimplementedHealthServer struct {
} }
@ -232,11 +123,71 @@ func (UnimplementedHealthServer) Watch(*HealthCheckRequest, Health_WatchServer)
return status.Errorf(codes.Unimplemented, "method Watch not implemented") return status.Errorf(codes.Unimplemented, "method Watch not implemented")
} }
// RegisterHealthServer registers a service implementation with a gRPC server. // UnsafeHealthServer may be embedded to opt out of forward compatibility for this service.
func RegisterHealthServer(s grpc.ServiceRegistrar, srv HealthServer) { // Use of this interface is not recommended, as added methods to HealthServer will
str := &HealthService{ // result in compilation errors.
Check: srv.Check, type UnsafeHealthServer interface {
Watch: srv.Watch, mustEmbedUnimplementedHealthServer()
} }
RegisterHealthService(s, str)
func RegisterHealthServer(s *grpc.Server, srv HealthServer) {
s.RegisterService(&_Health_serviceDesc, srv)
}
func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HealthCheckRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(HealthServer).Check(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.health.v1.Health/Check",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Health_Watch_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(HealthCheckRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(HealthServer).Watch(m, &healthWatchServer{stream})
}
type Health_WatchServer interface {
Send(*HealthCheckResponse) error
grpc.ServerStream
}
type healthWatchServer struct {
grpc.ServerStream
}
func (x *healthWatchServer) Send(m *HealthCheckResponse) error {
return x.ServerStream.SendMsg(m)
}
var _Health_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.health.v1.Health",
HandlerType: (*HealthServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Check",
Handler: _Health_Check_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "Watch",
Handler: _Health_Watch_Handler,
ServerStreams: true,
},
},
Metadata: "grpc/health/v1/health.proto",
} }

View File

@ -64,7 +64,7 @@ func main() {
} }
altsTC := alts.NewServerCreds(opts) altsTC := alts.NewServerCreds(opts)
grpcServer := grpc.NewServer(grpc.Creds(altsTC), grpc.InTapHandle(authz)) grpcServer := grpc.NewServer(grpc.Creds(altsTC), grpc.InTapHandle(authz))
testpb.RegisterTestServiceService(grpcServer, interop.NewTestServer()) testpb.RegisterTestServiceServer(grpcServer, interop.NewTestServer())
grpcServer.Serve(lis) grpcServer.Serve(lis)
} }

View File

@ -47,10 +47,6 @@ func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient {
return &testServiceClient{cc} return &testServiceClient{cc}
} }
var testServiceEmptyCallStreamDesc = &grpc.StreamDesc{
StreamName: "EmptyCall",
}
func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) {
out := new(Empty) out := new(Empty)
err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...)
@ -60,10 +56,6 @@ func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...gr
return out, nil return out, nil
} }
var testServiceUnaryCallStreamDesc = &grpc.StreamDesc{
StreamName: "UnaryCall",
}
func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
out := new(SimpleResponse) out := new(SimpleResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...)
@ -73,13 +65,8 @@ func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, op
return out, nil return out, nil
} }
var testServiceStreamingOutputCallStreamDesc = &grpc.StreamDesc{
StreamName: "StreamingOutputCall",
ServerStreams: true,
}
func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceStreamingOutputCallStreamDesc, "/grpc.testing.TestService/StreamingOutputCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/StreamingOutputCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -110,13 +97,8 @@ func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallRespo
return m, nil return m, nil
} }
var testServiceStreamingInputCallStreamDesc = &grpc.StreamDesc{
StreamName: "StreamingInputCall",
ClientStreams: true,
}
func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceStreamingInputCallStreamDesc, "/grpc.testing.TestService/StreamingInputCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/StreamingInputCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -149,14 +131,8 @@ func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCal
return m, nil return m, nil
} }
var testServiceFullDuplexCallStreamDesc = &grpc.StreamDesc{
StreamName: "FullDuplexCall",
ServerStreams: true,
ClientStreams: true,
}
func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceFullDuplexCallStreamDesc, "/grpc.testing.TestService/FullDuplexCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/FullDuplexCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -186,14 +162,8 @@ func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse,
return m, nil return m, nil
} }
var testServiceHalfDuplexCallStreamDesc = &grpc.StreamDesc{
StreamName: "HalfDuplexCall",
ServerStreams: true,
ClientStreams: true,
}
func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceHalfDuplexCallStreamDesc, "/grpc.testing.TestService/HalfDuplexCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[3], "/grpc.testing.TestService/HalfDuplexCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -223,82 +193,110 @@ func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse,
return m, nil return m, nil
} }
// TestServiceService is the service API for TestService service. // TestServiceServer is the server API for TestService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedTestServiceServer
// RegisterTestServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type TestServiceServer interface {
type TestServiceService struct {
// One empty request followed by one empty response. // One empty request followed by one empty response.
EmptyCall func(context.Context, *Empty) (*Empty, error) EmptyCall(context.Context, *Empty) (*Empty, error)
// One request followed by one response. // One request followed by one response.
// The server returns the client payload as-is. // The server returns the client payload as-is.
UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
// One request followed by a sequence of responses (streamed download). // One request followed by a sequence of responses (streamed download).
// The server returns the payload with client desired type and sizes. // The server returns the payload with client desired type and sizes.
StreamingOutputCall func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error
// A sequence of requests followed by one response (streamed upload). // A sequence of requests followed by one response (streamed upload).
// The server returns the aggregated size of client payload as the result. // The server returns the aggregated size of client payload as the result.
StreamingInputCall func(TestService_StreamingInputCallServer) error StreamingInputCall(TestService_StreamingInputCallServer) error
// A sequence of requests with each request served by the server immediately. // A sequence of requests with each request served by the server immediately.
// As one request could lead to multiple responses, this interface // As one request could lead to multiple responses, this interface
// demonstrates the idea of full duplexing. // demonstrates the idea of full duplexing.
FullDuplexCall func(TestService_FullDuplexCallServer) error FullDuplexCall(TestService_FullDuplexCallServer) error
// A sequence of requests followed by a sequence of responses. // A sequence of requests followed by a sequence of responses.
// The server buffers all the client requests and then serves them in order. A // The server buffers all the client requests and then serves them in order. A
// stream of responses are returned to the client when the server starts with // stream of responses are returned to the client when the server starts with
// first request. // first request.
HalfDuplexCall func(TestService_HalfDuplexCallServer) error HalfDuplexCall(TestService_HalfDuplexCallServer) error
mustEmbedUnimplementedTestServiceServer()
} }
func (s *TestServiceService) emptyCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedTestServiceServer must be embedded to have forward compatible implementations.
type UnimplementedTestServiceServer struct {
}
func (UnimplementedTestServiceServer) EmptyCall(context.Context, *Empty) (*Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented")
}
func (UnimplementedTestServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented")
}
func (UnimplementedTestServiceServer) StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented")
}
func (UnimplementedTestServiceServer) StreamingInputCall(TestService_StreamingInputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented")
}
func (UnimplementedTestServiceServer) FullDuplexCall(TestService_FullDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented")
}
func (UnimplementedTestServiceServer) HalfDuplexCall(TestService_HalfDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented")
}
func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {}
// UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to TestServiceServer will
// result in compilation errors.
type UnsafeTestServiceServer interface {
mustEmbedUnimplementedTestServiceServer()
}
func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) {
s.RegisterService(&_TestService_serviceDesc, srv)
}
func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty) in := new(Empty)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.EmptyCall(ctx, in) return srv.(TestServiceServer).EmptyCall(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.TestService/EmptyCall", FullMethod: "/grpc.testing.TestService/EmptyCall",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.EmptyCall(ctx, req.(*Empty)) return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *TestServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimpleRequest) in := new(SimpleRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.UnaryCall(ctx, in) return srv.(TestServiceServer).UnaryCall(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.TestService/UnaryCall", FullMethod: "/grpc.testing.TestService/UnaryCall",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.UnaryCall(ctx, req.(*SimpleRequest)) return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *TestServiceService) streamingOutputCall(_ interface{}, stream grpc.ServerStream) error {
func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(StreamingOutputCallRequest) m := new(StreamingOutputCallRequest)
if err := stream.RecvMsg(m); err != nil { if err := stream.RecvMsg(m); err != nil {
return err return err
} }
return s.StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream})
}
func (s *TestServiceService) streamingInputCall(_ interface{}, stream grpc.ServerStream) error {
return s.StreamingInputCall(&testServiceStreamingInputCallServer{stream})
}
func (s *TestServiceService) fullDuplexCall(_ interface{}, stream grpc.ServerStream) error {
return s.FullDuplexCall(&testServiceFullDuplexCallServer{stream})
}
func (s *TestServiceService) halfDuplexCall(_ interface{}, stream grpc.ServerStream) error {
return s.HalfDuplexCall(&testServiceHalfDuplexCallServer{stream})
} }
type TestService_StreamingOutputCallServer interface { type TestService_StreamingOutputCallServer interface {
@ -314,6 +312,10 @@ func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallRespon
return x.ServerStream.SendMsg(m) return x.ServerStream.SendMsg(m)
} }
func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream})
}
type TestService_StreamingInputCallServer interface { type TestService_StreamingInputCallServer interface {
SendAndClose(*StreamingInputCallResponse) error SendAndClose(*StreamingInputCallResponse) error
Recv() (*StreamingInputCallRequest, error) Recv() (*StreamingInputCallRequest, error)
@ -336,6 +338,10 @@ func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest
return m, nil return m, nil
} }
func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream})
}
type TestService_FullDuplexCallServer interface { type TestService_FullDuplexCallServer interface {
Send(*StreamingOutputCallResponse) error Send(*StreamingOutputCallResponse) error
Recv() (*StreamingOutputCallRequest, error) Recv() (*StreamingOutputCallRequest, error)
@ -358,6 +364,10 @@ func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, e
return m, nil return m, nil
} }
func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream})
}
type TestService_HalfDuplexCallServer interface { type TestService_HalfDuplexCallServer interface {
Send(*StreamingOutputCallResponse) error Send(*StreamingOutputCallResponse) error
Recv() (*StreamingOutputCallRequest, error) Recv() (*StreamingOutputCallRequest, error)
@ -380,79 +390,44 @@ func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, e
return m, nil return m, nil
} }
// RegisterTestServiceService registers a service implementation with a gRPC server. var _TestService_serviceDesc = grpc.ServiceDesc{
func RegisterTestServiceService(s grpc.ServiceRegistrar, srv *TestServiceService) { ServiceName: "grpc.testing.TestService",
srvCopy := *srv HandlerType: (*TestServiceServer)(nil),
if srvCopy.EmptyCall == nil { Methods: []grpc.MethodDesc{
srvCopy.EmptyCall = func(context.Context, *Empty) (*Empty, error) { {
return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented") MethodName: "EmptyCall",
} Handler: _TestService_EmptyCall_Handler,
}
if srvCopy.UnaryCall == nil {
srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented")
}
}
if srvCopy.StreamingOutputCall == nil {
srvCopy.StreamingOutputCall = func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented")
}
}
if srvCopy.StreamingInputCall == nil {
srvCopy.StreamingInputCall = func(TestService_StreamingInputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented")
}
}
if srvCopy.FullDuplexCall == nil {
srvCopy.FullDuplexCall = func(TestService_FullDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented")
}
}
if srvCopy.HalfDuplexCall == nil {
srvCopy.HalfDuplexCall = func(TestService_HalfDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.testing.TestService",
Methods: []grpc.MethodDesc{
{
MethodName: "EmptyCall",
Handler: srvCopy.emptyCall,
},
{
MethodName: "UnaryCall",
Handler: srvCopy.unaryCall,
},
}, },
Streams: []grpc.StreamDesc{ {
{ MethodName: "UnaryCall",
StreamName: "StreamingOutputCall", Handler: _TestService_UnaryCall_Handler,
Handler: srvCopy.streamingOutputCall,
ServerStreams: true,
},
{
StreamName: "StreamingInputCall",
Handler: srvCopy.streamingInputCall,
ClientStreams: true,
},
{
StreamName: "FullDuplexCall",
Handler: srvCopy.fullDuplexCall,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "HalfDuplexCall",
Handler: srvCopy.halfDuplexCall,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "interop/grpc_testing/test.proto", },
} Streams: []grpc.StreamDesc{
{
s.RegisterService(&sd, nil) StreamName: "StreamingOutputCall",
Handler: _TestService_StreamingOutputCall_Handler,
ServerStreams: true,
},
{
StreamName: "StreamingInputCall",
Handler: _TestService_StreamingInputCall_Handler,
ClientStreams: true,
},
{
StreamName: "FullDuplexCall",
Handler: _TestService_FullDuplexCall_Handler,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "HalfDuplexCall",
Handler: _TestService_HalfDuplexCall_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "interop/grpc_testing/test.proto",
} }
// UnimplementedServiceClient is the client API for UnimplementedService service. // UnimplementedServiceClient is the client API for UnimplementedService service.
@ -471,10 +446,6 @@ func NewUnimplementedServiceClient(cc grpc.ClientConnInterface) UnimplementedSer
return &unimplementedServiceClient{cc} return &unimplementedServiceClient{cc}
} }
var unimplementedServiceUnimplementedCallStreamDesc = &grpc.StreamDesc{
StreamName: "UnimplementedCall",
}
func (c *unimplementedServiceClient) UnimplementedCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { func (c *unimplementedServiceClient) UnimplementedCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) {
out := new(Empty) out := new(Empty)
err := c.cc.Invoke(ctx, "/grpc.testing.UnimplementedService/UnimplementedCall", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.UnimplementedService/UnimplementedCall", in, out, opts...)
@ -484,54 +455,64 @@ func (c *unimplementedServiceClient) UnimplementedCall(ctx context.Context, in *
return out, nil return out, nil
} }
// UnimplementedServiceService is the service API for UnimplementedService service. // UnimplementedServiceServer is the server API for UnimplementedService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedUnimplementedServiceServer
// RegisterUnimplementedServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type UnimplementedServiceServer interface {
type UnimplementedServiceService struct {
// A call that no server should implement // A call that no server should implement
UnimplementedCall func(context.Context, *Empty) (*Empty, error) UnimplementedCall(context.Context, *Empty) (*Empty, error)
mustEmbedUnimplementedUnimplementedServiceServer()
} }
func (s *UnimplementedServiceService) unimplementedCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedUnimplementedServiceServer must be embedded to have forward compatible implementations.
type UnimplementedUnimplementedServiceServer struct {
}
func (UnimplementedUnimplementedServiceServer) UnimplementedCall(context.Context, *Empty) (*Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnimplementedCall not implemented")
}
func (UnimplementedUnimplementedServiceServer) mustEmbedUnimplementedUnimplementedServiceServer() {}
// UnsafeUnimplementedServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to UnimplementedServiceServer will
// result in compilation errors.
type UnsafeUnimplementedServiceServer interface {
mustEmbedUnimplementedUnimplementedServiceServer()
}
func RegisterUnimplementedServiceServer(s *grpc.Server, srv UnimplementedServiceServer) {
s.RegisterService(&_UnimplementedService_serviceDesc, srv)
}
func _UnimplementedService_UnimplementedCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty) in := new(Empty)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.UnimplementedCall(ctx, in) return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.UnimplementedService/UnimplementedCall", FullMethod: "/grpc.testing.UnimplementedService/UnimplementedCall",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.UnimplementedCall(ctx, req.(*Empty)) return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, req.(*Empty))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
// RegisterUnimplementedServiceService registers a service implementation with a gRPC server. var _UnimplementedService_serviceDesc = grpc.ServiceDesc{
func RegisterUnimplementedServiceService(s grpc.ServiceRegistrar, srv *UnimplementedServiceService) { ServiceName: "grpc.testing.UnimplementedService",
srvCopy := *srv HandlerType: (*UnimplementedServiceServer)(nil),
if srvCopy.UnimplementedCall == nil { Methods: []grpc.MethodDesc{
srvCopy.UnimplementedCall = func(context.Context, *Empty) (*Empty, error) { {
return nil, status.Errorf(codes.Unimplemented, "method UnimplementedCall not implemented") MethodName: "UnimplementedCall",
} Handler: _UnimplementedService_UnimplementedCall_Handler,
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.testing.UnimplementedService",
Methods: []grpc.MethodDesc{
{
MethodName: "UnimplementedCall",
Handler: srvCopy.unimplementedCall,
},
}, },
Streams: []grpc.StreamDesc{}, },
Metadata: "interop/grpc_testing/test.proto", Streams: []grpc.StreamDesc{},
} Metadata: "interop/grpc_testing/test.proto",
s.RegisterService(&sd, nil)
} }
// LoadBalancerStatsServiceClient is the client API for LoadBalancerStatsService service. // LoadBalancerStatsServiceClient is the client API for LoadBalancerStatsService service.
@ -550,10 +531,6 @@ func NewLoadBalancerStatsServiceClient(cc grpc.ClientConnInterface) LoadBalancer
return &loadBalancerStatsServiceClient{cc} return &loadBalancerStatsServiceClient{cc}
} }
var loadBalancerStatsServiceGetClientStatsStreamDesc = &grpc.StreamDesc{
StreamName: "GetClientStats",
}
func (c *loadBalancerStatsServiceClient) GetClientStats(ctx context.Context, in *LoadBalancerStatsRequest, opts ...grpc.CallOption) (*LoadBalancerStatsResponse, error) { func (c *loadBalancerStatsServiceClient) GetClientStats(ctx context.Context, in *LoadBalancerStatsRequest, opts ...grpc.CallOption) (*LoadBalancerStatsResponse, error) {
out := new(LoadBalancerStatsResponse) out := new(LoadBalancerStatsResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.LoadBalancerStatsService/GetClientStats", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.LoadBalancerStatsService/GetClientStats", in, out, opts...)
@ -563,52 +540,63 @@ func (c *loadBalancerStatsServiceClient) GetClientStats(ctx context.Context, in
return out, nil return out, nil
} }
// LoadBalancerStatsServiceService is the service API for LoadBalancerStatsService service. // LoadBalancerStatsServiceServer is the server API for LoadBalancerStatsService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedLoadBalancerStatsServiceServer
// RegisterLoadBalancerStatsServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type LoadBalancerStatsServiceServer interface {
type LoadBalancerStatsServiceService struct {
// Gets the backend distribution for RPCs sent by a test client. // Gets the backend distribution for RPCs sent by a test client.
GetClientStats func(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error) GetClientStats(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error)
mustEmbedUnimplementedLoadBalancerStatsServiceServer()
} }
func (s *LoadBalancerStatsServiceService) getClientStats(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedLoadBalancerStatsServiceServer must be embedded to have forward compatible implementations.
type UnimplementedLoadBalancerStatsServiceServer struct {
}
func (UnimplementedLoadBalancerStatsServiceServer) GetClientStats(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetClientStats not implemented")
}
func (UnimplementedLoadBalancerStatsServiceServer) mustEmbedUnimplementedLoadBalancerStatsServiceServer() {
}
// UnsafeLoadBalancerStatsServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to LoadBalancerStatsServiceServer will
// result in compilation errors.
type UnsafeLoadBalancerStatsServiceServer interface {
mustEmbedUnimplementedLoadBalancerStatsServiceServer()
}
func RegisterLoadBalancerStatsServiceServer(s *grpc.Server, srv LoadBalancerStatsServiceServer) {
s.RegisterService(&_LoadBalancerStatsService_serviceDesc, srv)
}
func _LoadBalancerStatsService_GetClientStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(LoadBalancerStatsRequest) in := new(LoadBalancerStatsRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.GetClientStats(ctx, in) return srv.(LoadBalancerStatsServiceServer).GetClientStats(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.LoadBalancerStatsService/GetClientStats", FullMethod: "/grpc.testing.LoadBalancerStatsService/GetClientStats",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetClientStats(ctx, req.(*LoadBalancerStatsRequest)) return srv.(LoadBalancerStatsServiceServer).GetClientStats(ctx, req.(*LoadBalancerStatsRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
// RegisterLoadBalancerStatsServiceService registers a service implementation with a gRPC server. var _LoadBalancerStatsService_serviceDesc = grpc.ServiceDesc{
func RegisterLoadBalancerStatsServiceService(s grpc.ServiceRegistrar, srv *LoadBalancerStatsServiceService) { ServiceName: "grpc.testing.LoadBalancerStatsService",
srvCopy := *srv HandlerType: (*LoadBalancerStatsServiceServer)(nil),
if srvCopy.GetClientStats == nil { Methods: []grpc.MethodDesc{
srvCopy.GetClientStats = func(context.Context, *LoadBalancerStatsRequest) (*LoadBalancerStatsResponse, error) { {
return nil, status.Errorf(codes.Unimplemented, "method GetClientStats not implemented") MethodName: "GetClientStats",
} Handler: _LoadBalancerStatsService_GetClientStats_Handler,
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.testing.LoadBalancerStatsService",
Methods: []grpc.MethodDesc{
{
MethodName: "GetClientStats",
Handler: srvCopy.getClientStats,
},
}, },
Streams: []grpc.StreamDesc{}, },
Metadata: "interop/grpc_testing/test.proto", Streams: []grpc.StreamDesc{},
} Metadata: "interop/grpc_testing/test.proto",
s.RegisterService(&sd, nil)
} }

View File

@ -76,6 +76,6 @@ func main() {
opts = append(opts, grpc.Creds(altsTC)) opts = append(opts, grpc.Creds(altsTC))
} }
server := grpc.NewServer(opts...) server := grpc.NewServer(opts...)
testpb.RegisterTestServiceService(server, interop.NewTestServer()) testpb.RegisterTestServiceServer(server, interop.NewTestServer())
server.Serve(lis) server.Serve(lis)
} }

View File

@ -673,19 +673,13 @@ func DoPickFirstUnary(tc testpb.TestServiceClient) {
} }
} }
type testServer struct{} type testServer struct {
testpb.UnimplementedTestServiceServer
}
// NewTestServer creates a test server for test service. // NewTestServer creates a test server for test service.
func NewTestServer() *testpb.TestServiceService { func NewTestServer() testpb.TestServiceServer {
s := testServer{} return &testServer{}
return &testpb.TestServiceService{
EmptyCall: s.EmptyCall,
UnaryCall: s.UnaryCall,
StreamingOutputCall: s.StreamingOutputCall,
StreamingInputCall: s.StreamingInputCall,
FullDuplexCall: s.FullDuplexCall,
HalfDuplexCall: s.HalfDuplexCall,
}
} }
func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {

View File

@ -95,6 +95,10 @@ var (
logger = grpclog.Component("interop") logger = grpclog.Component("interop")
) )
type statsService struct {
testpb.UnimplementedLoadBalancerStatsServiceServer
}
func hasRPCSucceeded() bool { func hasRPCSucceeded() bool {
return atomic.LoadUint32(&rpcSucceeded) > 0 return atomic.LoadUint32(&rpcSucceeded) > 0
} }
@ -107,7 +111,7 @@ func setRPCSucceeded() {
// and return the distribution of remote peers. This is essentially a clientside // and return the distribution of remote peers. This is essentially a clientside
// LB reporting mechanism that is designed to be queried by an external test // LB reporting mechanism that is designed to be queried by an external test
// driver when verifying that the client is distributing RPCs as expected. // driver when verifying that the client is distributing RPCs as expected.
func getClientStats(ctx context.Context, in *testpb.LoadBalancerStatsRequest) (*testpb.LoadBalancerStatsResponse, error) { func (s *statsService) GetClientStats(ctx context.Context, in *testpb.LoadBalancerStatsRequest) (*testpb.LoadBalancerStatsResponse, error) {
mu.Lock() mu.Lock()
watcherKey := statsWatcherKey{currentRequestID, currentRequestID + in.GetNumRpcs()} watcherKey := statsWatcherKey{currentRequestID, currentRequestID + in.GetNumRpcs()}
watcher, ok := watchers[watcherKey] watcher, ok := watchers[watcherKey]
@ -222,7 +226,7 @@ func main() {
} }
s := grpc.NewServer() s := grpc.NewServer()
defer s.Stop() defer s.Stop()
testpb.RegisterLoadBalancerStatsServiceService(s, &testpb.LoadBalancerStatsServiceService{GetClientStats: getClientStats}) testpb.RegisterLoadBalancerStatsServiceServer(s, &statsService{})
go s.Serve(lis) go s.Serve(lis)
clients := make([]testpb.TestServiceClient, *numChannels) clients := make([]testpb.TestServiceClient, *numChannels)

View File

@ -49,12 +49,16 @@ func getHostname() string {
return hostname return hostname
} }
func emptyCall(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) { type server struct {
testpb.UnimplementedTestServiceServer
}
func (s *server) EmptyCall(ctx context.Context, _ *testpb.Empty) (*testpb.Empty, error) {
grpc.SetHeader(ctx, metadata.Pairs("hostname", hostname)) grpc.SetHeader(ctx, metadata.Pairs("hostname", hostname))
return &testpb.Empty{}, nil return &testpb.Empty{}, nil
} }
func unaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { func (s *server) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
grpc.SetHeader(ctx, metadata.Pairs("hostname", hostname)) grpc.SetHeader(ctx, metadata.Pairs("hostname", hostname))
return &testpb.SimpleResponse{ServerId: *serverID, Hostname: hostname}, nil return &testpb.SimpleResponse{ServerId: *serverID, Hostname: hostname}, nil
} }
@ -67,6 +71,6 @@ func main() {
logger.Fatalf("failed to listen: %v", err) logger.Fatalf("failed to listen: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
testpb.RegisterTestServiceService(s, &testpb.TestServiceService{EmptyCall: emptyCall, UnaryCall: unaryCall}) testpb.RegisterTestServiceServer(s, &server{})
s.Serve(lis) s.Serve(lis)
} }

View File

@ -32,10 +32,6 @@ func NewProfilingClient(cc grpc.ClientConnInterface) ProfilingClient {
return &profilingClient{cc} return &profilingClient{cc}
} }
var profilingEnableStreamDesc = &grpc.StreamDesc{
StreamName: "Enable",
}
func (c *profilingClient) Enable(ctx context.Context, in *EnableRequest, opts ...grpc.CallOption) (*EnableResponse, error) { func (c *profilingClient) Enable(ctx context.Context, in *EnableRequest, opts ...grpc.CallOption) (*EnableResponse, error) {
out := new(EnableResponse) out := new(EnableResponse)
err := c.cc.Invoke(ctx, "/grpc.go.profiling.v1alpha.Profiling/Enable", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.go.profiling.v1alpha.Profiling/Enable", in, out, opts...)
@ -45,10 +41,6 @@ func (c *profilingClient) Enable(ctx context.Context, in *EnableRequest, opts ..
return out, nil return out, nil
} }
var profilingGetStreamStatsStreamDesc = &grpc.StreamDesc{
StreamName: "GetStreamStats",
}
func (c *profilingClient) GetStreamStats(ctx context.Context, in *GetStreamStatsRequest, opts ...grpc.CallOption) (*GetStreamStatsResponse, error) { func (c *profilingClient) GetStreamStats(ctx context.Context, in *GetStreamStatsRequest, opts ...grpc.CallOption) (*GetStreamStatsResponse, error) {
out := new(GetStreamStatsResponse) out := new(GetStreamStatsResponse)
err := c.cc.Invoke(ctx, "/grpc.go.profiling.v1alpha.Profiling/GetStreamStats", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.go.profiling.v1alpha.Profiling/GetStreamStats", in, out, opts...)
@ -58,89 +50,9 @@ func (c *profilingClient) GetStreamStats(ctx context.Context, in *GetStreamStats
return out, nil return out, nil
} }
// ProfilingService is the service API for Profiling service. // ProfilingServer is the server API for Profiling service.
// Fields should be assigned to their respective handler implementations only before // All implementations should embed UnimplementedProfilingServer
// RegisterProfilingService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error.
type ProfilingService struct {
// Enable allows users to toggle profiling on and off remotely.
Enable func(context.Context, *EnableRequest) (*EnableResponse, error)
// GetStreamStats is used to retrieve an array of stream-level stats from a
// gRPC client/server.
GetStreamStats func(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error)
}
func (s *ProfilingService) enable(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EnableRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.Enable(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.go.profiling.v1alpha.Profiling/Enable",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.Enable(ctx, req.(*EnableRequest))
}
return interceptor(ctx, in, info, handler)
}
func (s *ProfilingService) getStreamStats(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetStreamStatsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetStreamStats(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.go.profiling.v1alpha.Profiling/GetStreamStats",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetStreamStats(ctx, req.(*GetStreamStatsRequest))
}
return interceptor(ctx, in, info, handler)
}
// RegisterProfilingService registers a service implementation with a gRPC server.
func RegisterProfilingService(s grpc.ServiceRegistrar, srv *ProfilingService) {
srvCopy := *srv
if srvCopy.Enable == nil {
srvCopy.Enable = func(context.Context, *EnableRequest) (*EnableResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Enable not implemented")
}
}
if srvCopy.GetStreamStats == nil {
srvCopy.GetStreamStats = func(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetStreamStats not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.go.profiling.v1alpha.Profiling",
Methods: []grpc.MethodDesc{
{
MethodName: "Enable",
Handler: srvCopy.enable,
},
{
MethodName: "GetStreamStats",
Handler: srvCopy.getStreamStats,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "profiling/proto/service.proto",
}
s.RegisterService(&sd, nil)
}
// ProfilingServer is the service API for Profiling service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type ProfilingServer interface { type ProfilingServer interface {
// Enable allows users to toggle profiling on and off remotely. // Enable allows users to toggle profiling on and off remotely.
Enable(context.Context, *EnableRequest) (*EnableResponse, error) Enable(context.Context, *EnableRequest) (*EnableResponse, error)
@ -149,8 +61,7 @@ type ProfilingServer interface {
GetStreamStats(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error) GetStreamStats(context.Context, *GetStreamStatsRequest) (*GetStreamStatsResponse, error)
} }
// UnimplementedProfilingServer can be embedded to have forward compatible implementations of // UnimplementedProfilingServer should be embedded to have forward compatible implementations.
// ProfilingServer
type UnimplementedProfilingServer struct { type UnimplementedProfilingServer struct {
} }
@ -161,11 +72,66 @@ func (UnimplementedProfilingServer) GetStreamStats(context.Context, *GetStreamSt
return nil, status.Errorf(codes.Unimplemented, "method GetStreamStats not implemented") return nil, status.Errorf(codes.Unimplemented, "method GetStreamStats not implemented")
} }
// RegisterProfilingServer registers a service implementation with a gRPC server. // UnsafeProfilingServer may be embedded to opt out of forward compatibility for this service.
func RegisterProfilingServer(s grpc.ServiceRegistrar, srv ProfilingServer) { // Use of this interface is not recommended, as added methods to ProfilingServer will
str := &ProfilingService{ // result in compilation errors.
Enable: srv.Enable, type UnsafeProfilingServer interface {
GetStreamStats: srv.GetStreamStats, mustEmbedUnimplementedProfilingServer()
} }
RegisterProfilingService(s, str)
func RegisterProfilingServer(s *grpc.Server, srv ProfilingServer) {
s.RegisterService(&_Profiling_serviceDesc, srv)
}
func _Profiling_Enable_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EnableRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ProfilingServer).Enable(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.go.profiling.v1alpha.Profiling/Enable",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ProfilingServer).Enable(ctx, req.(*EnableRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Profiling_GetStreamStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetStreamStatsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ProfilingServer).GetStreamStats(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.go.profiling.v1alpha.Profiling/GetStreamStats",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ProfilingServer).GetStreamStats(ctx, req.(*GetStreamStatsRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Profiling_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.go.profiling.v1alpha.Profiling",
HandlerType: (*ProfilingServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Enable",
Handler: _Profiling_Enable_Handler,
},
{
MethodName: "GetStreamStats",
Handler: _Profiling_GetStreamStats_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "profiling/proto/service.proto",
} }

View File

@ -30,14 +30,8 @@ func NewServerReflectionClient(cc grpc.ClientConnInterface) ServerReflectionClie
return &serverReflectionClient{cc} return &serverReflectionClient{cc}
} }
var serverReflectionServerReflectionInfoStreamDesc = &grpc.StreamDesc{
StreamName: "ServerReflectionInfo",
ServerStreams: true,
ClientStreams: true,
}
func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) { func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) {
stream, err := c.cc.NewStream(ctx, serverReflectionServerReflectionInfoStreamDesc, "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...) stream, err := c.cc.NewStream(ctx, &_ServerReflection_serviceDesc.Streams[0], "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -67,18 +61,36 @@ func (x *serverReflectionServerReflectionInfoClient) Recv() (*ServerReflectionRe
return m, nil return m, nil
} }
// ServerReflectionService is the service API for ServerReflection service. // ServerReflectionServer is the server API for ServerReflection service.
// Fields should be assigned to their respective handler implementations only before // All implementations should embed UnimplementedServerReflectionServer
// RegisterServerReflectionService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type ServerReflectionServer interface {
type ServerReflectionService struct {
// The reflection service is structured as a bidirectional stream, ensuring // The reflection service is structured as a bidirectional stream, ensuring
// all related requests go to a single server. // all related requests go to a single server.
ServerReflectionInfo func(ServerReflection_ServerReflectionInfoServer) error ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error
} }
func (s *ServerReflectionService) serverReflectionInfo(_ interface{}, stream grpc.ServerStream) error { // UnimplementedServerReflectionServer should be embedded to have forward compatible implementations.
return s.ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream}) type UnimplementedServerReflectionServer struct {
}
func (UnimplementedServerReflectionServer) ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error {
return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented")
}
// UnsafeServerReflectionServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ServerReflectionServer will
// result in compilation errors.
type UnsafeServerReflectionServer interface {
mustEmbedUnimplementedServerReflectionServer()
}
func RegisterServerReflectionServer(s *grpc.Server, srv ServerReflectionServer) {
s.RegisterService(&_ServerReflection_serviceDesc, srv)
}
func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(ServerReflectionServer).ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream})
} }
type ServerReflection_ServerReflectionInfoServer interface { type ServerReflection_ServerReflectionInfoServer interface {
@ -103,54 +115,17 @@ func (x *serverReflectionServerReflectionInfoServer) Recv() (*ServerReflectionRe
return m, nil return m, nil
} }
// RegisterServerReflectionService registers a service implementation with a gRPC server. var _ServerReflection_serviceDesc = grpc.ServiceDesc{
func RegisterServerReflectionService(s grpc.ServiceRegistrar, srv *ServerReflectionService) { ServiceName: "grpc.reflection.v1alpha.ServerReflection",
srvCopy := *srv HandlerType: (*ServerReflectionServer)(nil),
if srvCopy.ServerReflectionInfo == nil { Methods: []grpc.MethodDesc{},
srvCopy.ServerReflectionInfo = func(ServerReflection_ServerReflectionInfoServer) error { Streams: []grpc.StreamDesc{
return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented") {
} StreamName: "ServerReflectionInfo",
} Handler: _ServerReflection_ServerReflectionInfo_Handler,
sd := grpc.ServiceDesc{ ServerStreams: true,
ServiceName: "grpc.reflection.v1alpha.ServerReflection", ClientStreams: true,
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "ServerReflectionInfo",
Handler: srvCopy.serverReflectionInfo,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "reflection/grpc_reflection_v1alpha/reflection.proto", },
} Metadata: "reflection/grpc_reflection_v1alpha/reflection.proto",
s.RegisterService(&sd, nil)
}
// ServerReflectionServer is the service API for ServerReflection service.
// New methods may be added to this interface if they are added to the service
// definition, which is not a backward-compatible change. For this reason,
// use of this type is not recommended unless you own the service definition.
type ServerReflectionServer interface {
// The reflection service is structured as a bidirectional stream, ensuring
// all related requests go to a single server.
ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error
}
// UnimplementedServerReflectionServer can be embedded to have forward compatible implementations of
// ServerReflectionServer
type UnimplementedServerReflectionServer struct {
}
func (UnimplementedServerReflectionServer) ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error {
return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented")
}
// RegisterServerReflectionServer registers a service implementation with a gRPC server.
func RegisterServerReflectionServer(s grpc.ServiceRegistrar, srv ServerReflectionServer) {
str := &ServerReflectionService{
ServerReflectionInfo: srv.ServerReflectionInfo,
}
RegisterServerReflectionService(s, str)
} }

View File

@ -29,10 +29,6 @@ func NewSearchServiceClient(cc grpc.ClientConnInterface) SearchServiceClient {
return &searchServiceClient{cc} return &searchServiceClient{cc}
} }
var searchServiceSearchStreamDesc = &grpc.StreamDesc{
StreamName: "Search",
}
func (c *searchServiceClient) Search(ctx context.Context, in *SearchRequest, opts ...grpc.CallOption) (*SearchResponse, error) { func (c *searchServiceClient) Search(ctx context.Context, in *SearchRequest, opts ...grpc.CallOption) (*SearchResponse, error) {
out := new(SearchResponse) out := new(SearchResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.SearchService/Search", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.SearchService/Search", in, out, opts...)
@ -42,14 +38,8 @@ func (c *searchServiceClient) Search(ctx context.Context, in *SearchRequest, opt
return out, nil return out, nil
} }
var searchServiceStreamingSearchStreamDesc = &grpc.StreamDesc{
StreamName: "StreamingSearch",
ServerStreams: true,
ClientStreams: true,
}
func (c *searchServiceClient) StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchService_StreamingSearchClient, error) { func (c *searchServiceClient) StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchService_StreamingSearchClient, error) {
stream, err := c.cc.NewStream(ctx, searchServiceStreamingSearchStreamDesc, "/grpc.testing.SearchService/StreamingSearch", opts...) stream, err := c.cc.NewStream(ctx, &_SearchService_serviceDesc.Streams[0], "/grpc.testing.SearchService/StreamingSearch", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -79,34 +69,58 @@ func (x *searchServiceStreamingSearchClient) Recv() (*SearchResponse, error) {
return m, nil return m, nil
} }
// SearchServiceService is the service API for SearchService service. // SearchServiceServer is the server API for SearchService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedSearchServiceServer
// RegisterSearchServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type SearchServiceServer interface {
type SearchServiceService struct { Search(context.Context, *SearchRequest) (*SearchResponse, error)
Search func(context.Context, *SearchRequest) (*SearchResponse, error) StreamingSearch(SearchService_StreamingSearchServer) error
StreamingSearch func(SearchService_StreamingSearchServer) error mustEmbedUnimplementedSearchServiceServer()
} }
func (s *SearchServiceService) search(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedSearchServiceServer must be embedded to have forward compatible implementations.
type UnimplementedSearchServiceServer struct {
}
func (UnimplementedSearchServiceServer) Search(context.Context, *SearchRequest) (*SearchResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Search not implemented")
}
func (UnimplementedSearchServiceServer) StreamingSearch(SearchService_StreamingSearchServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingSearch not implemented")
}
func (UnimplementedSearchServiceServer) mustEmbedUnimplementedSearchServiceServer() {}
// UnsafeSearchServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to SearchServiceServer will
// result in compilation errors.
type UnsafeSearchServiceServer interface {
mustEmbedUnimplementedSearchServiceServer()
}
func RegisterSearchServiceServer(s *grpc.Server, srv SearchServiceServer) {
s.RegisterService(&_SearchService_serviceDesc, srv)
}
func _SearchService_Search_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SearchRequest) in := new(SearchRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.Search(ctx, in) return srv.(SearchServiceServer).Search(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.SearchService/Search", FullMethod: "/grpc.testing.SearchService/Search",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.Search(ctx, req.(*SearchRequest)) return srv.(SearchServiceServer).Search(ctx, req.(*SearchRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *SearchServiceService) streamingSearch(_ interface{}, stream grpc.ServerStream) error {
return s.StreamingSearch(&searchServiceStreamingSearchServer{stream}) func _SearchService_StreamingSearch_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(SearchServiceServer).StreamingSearch(&searchServiceStreamingSearchServer{stream})
} }
type SearchService_StreamingSearchServer interface { type SearchService_StreamingSearchServer interface {
@ -131,37 +145,22 @@ func (x *searchServiceStreamingSearchServer) Recv() (*SearchRequest, error) {
return m, nil return m, nil
} }
// RegisterSearchServiceService registers a service implementation with a gRPC server. var _SearchService_serviceDesc = grpc.ServiceDesc{
func RegisterSearchServiceService(s grpc.ServiceRegistrar, srv *SearchServiceService) { ServiceName: "grpc.testing.SearchService",
srvCopy := *srv HandlerType: (*SearchServiceServer)(nil),
if srvCopy.Search == nil { Methods: []grpc.MethodDesc{
srvCopy.Search = func(context.Context, *SearchRequest) (*SearchResponse, error) { {
return nil, status.Errorf(codes.Unimplemented, "method Search not implemented") MethodName: "Search",
} Handler: _SearchService_Search_Handler,
}
if srvCopy.StreamingSearch == nil {
srvCopy.StreamingSearch = func(SearchService_StreamingSearchServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingSearch not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.testing.SearchService",
Methods: []grpc.MethodDesc{
{
MethodName: "Search",
Handler: srvCopy.search,
},
}, },
Streams: []grpc.StreamDesc{ },
{ Streams: []grpc.StreamDesc{
StreamName: "StreamingSearch", {
Handler: srvCopy.streamingSearch, StreamName: "StreamingSearch",
ServerStreams: true, Handler: _SearchService_StreamingSearch_Handler,
ClientStreams: true, ServerStreams: true,
}, ClientStreams: true,
}, },
Metadata: "reflection/grpc_testing/test.proto", },
} Metadata: "reflection/grpc_testing/test.proto",
s.RegisterService(&sd, nil)
} }

View File

@ -166,13 +166,8 @@ func (x) TestAllExtensionNumbersForType(t *testing.T) {
// Do end2end tests. // Do end2end tests.
type server struct{} type server struct {
pb.UnimplementedSearchServiceServer
func (s *server) Svc() *pb.SearchServiceService {
return &pb.SearchServiceService{
Search: s.Search,
StreamingSearch: s.StreamingSearch,
}
} }
func (s *server) Search(ctx context.Context, in *pb.SearchRequest) (*pb.SearchResponse, error) { func (s *server) Search(ctx context.Context, in *pb.SearchRequest) (*pb.SearchResponse, error) {
@ -200,7 +195,7 @@ func (x) TestReflectionEnd2end(t *testing.T) {
t.Fatalf("failed to listen: %v", err) t.Fatalf("failed to listen: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
pb.RegisterSearchServiceService(s, (&server{}).Svc()) pb.RegisterSearchServiceServer(s, &server{})
pbv3.RegisterSearchServiceV3Server(s, &serverV3{}) pbv3.RegisterSearchServiceV3Server(s, &serverV3{})
// Register reflection service on s. // Register reflection service on s.
Register(s) Register(s)

View File

@ -26,6 +26,11 @@ export GOBIN=${WORKDIR}/bin
export PATH=${GOBIN}:${PATH} export PATH=${GOBIN}:${PATH}
mkdir -p ${GOBIN} mkdir -p ${GOBIN}
echo "remove existing generated files"
# grpc_testingv3/testv3.pb.go is not re-generated because it was
# intentionally generated by an older version of protoc-gen-go.
rm -f $(find . -name '*.pb.go' | grep -v 'grpc_testingv3/testv3.pb.go')
echo "go install github.com/golang/protobuf/protoc-gen-go" echo "go install github.com/golang/protobuf/protoc-gen-go"
(cd test/tools && go install github.com/golang/protobuf/protoc-gen-go) (cd test/tools && go install github.com/golang/protobuf/protoc-gen-go)
@ -35,6 +40,7 @@ echo "go install cmd/protoc-gen-go-grpc"
echo "git clone https://github.com/grpc/grpc-proto" echo "git clone https://github.com/grpc/grpc-proto"
git clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto git clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto
# Pull in code.proto as a proto dependency
mkdir -p ${WORKDIR}/googleapis/google/rpc mkdir -p ${WORKDIR}/googleapis/google/rpc
echo "curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto" echo "curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto"
curl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto curl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto
@ -59,21 +65,12 @@ curl --silent https://raw.githubusercontent.com/istio/istio/master/security/prot
mkdir -p ${WORKDIR}/out mkdir -p ${WORKDIR}/out
# Generates legacy gRPC Server symbols in addition to the newer Service symbols # Generates sources without the embed requirement
LEGACY_SOURCES=( LEGACY_SOURCES=(
${WORKDIR}/googleapis/google/rpc/code.proto
${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto ${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto
${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto ${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto
${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto
${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto
${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto
${WORKDIR}/grpc-proto/grpc/health/v1/health.proto ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto
${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto
${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto
${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto
${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto
${WORKDIR}/grpc-proto/grpc/tls/provider/meshca/experimental/config.proto
${WORKDIR}/istio/istio/google/security/meshca/v1/meshca.proto
profiling/proto/service.proto profiling/proto/service.proto
reflection/grpc_reflection_v1alpha/reflection.proto reflection/grpc_reflection_v1alpha/reflection.proto
) )
@ -81,6 +78,14 @@ LEGACY_SOURCES=(
# Generates only the new gRPC Service symbols # Generates only the new gRPC Service symbols
SOURCES=( SOURCES=(
$(git ls-files --exclude-standard --cached --others "*.proto" | grep -v '^\(profiling/proto/service.proto\|reflection/grpc_reflection_v1alpha/reflection.proto\)$') $(git ls-files --exclude-standard --cached --others "*.proto" | grep -v '^\(profiling/proto/service.proto\|reflection/grpc_reflection_v1alpha/reflection.proto\)$')
${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto
${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto
${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto
${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto
${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto
${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto
${WORKDIR}/grpc-proto/grpc/tls/provider/meshca/experimental/config.proto
${WORKDIR}/istio/istio/google/security/meshca/v1/meshca.proto
) )
# These options of the form 'Mfoo.proto=bar' instruct the codegen to use an # These options of the form 'Mfoo.proto=bar' instruct the codegen to use an
@ -91,12 +96,20 @@ Menvoy/config/core/v3/config_source.proto=github.com/envoyproxy/go-control-plane
for src in ${SOURCES[@]}; do for src in ${SOURCES[@]}; do
echo "protoc ${src}" echo "protoc ${src}"
protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out ${src} protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out \
-I"." \
-I${WORKDIR}/grpc-proto \
-I${WORKDIR}/googleapis \
-I${WORKDIR}/data-plane-api \
-I${WORKDIR}/udpa \
-I${WORKDIR}/protoc-gen-validate \
-I${WORKDIR}/istio \
${src}
done done
for src in ${LEGACY_SOURCES[@]}; do for src in ${LEGACY_SOURCES[@]}; do
echo "protoc ${src}" echo "protoc ${src}"
protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},gen_unstable_server_interfaces=true:${WORKDIR}/out \ protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},require_unimplemented_servers=false:${WORKDIR}/out \
-I"." \ -I"." \
-I${WORKDIR}/grpc-proto \ -I${WORKDIR}/grpc-proto \
-I${WORKDIR}/googleapis \ -I${WORKDIR}/googleapis \

View File

@ -130,8 +130,12 @@ func (cs *certStore) loadCerts() error {
return nil return nil
} }
type greeterServer struct {
pb.UnimplementedGreeterServer
}
// sayHello is a simple implementation of the pb.GreeterServer SayHello method. // sayHello is a simple implementation of the pb.GreeterServer SayHello method.
func sayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { func (greeterServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil return &pb.HelloReply{Message: "Hello " + in.Name}, nil
} }
@ -408,7 +412,7 @@ func (s) TestEnd2End(t *testing.T) {
t.Fatalf("failed to listen: %v", err) t.Fatalf("failed to listen: %v", err)
} }
defer lis.Close() defer lis.Close()
pb.RegisterGreeterService(s, &pb.GreeterService{SayHello: sayHello}) pb.RegisterGreeterServer(s, greeterServer{})
go s.Serve(lis) go s.Serve(lis)
clientOptions := &ClientOptions{ clientOptions := &ClientOptions{
IdentityOptions: IdentityCertificateOptions{ IdentityOptions: IdentityCertificateOptions{

View File

@ -38,10 +38,6 @@ func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient {
return &testServiceClient{cc} return &testServiceClient{cc}
} }
var testServiceUnaryCallStreamDesc = &grpc.StreamDesc{
StreamName: "UnaryCall",
}
func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
out := new(SimpleResponse) out := new(SimpleResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...)
@ -51,14 +47,8 @@ func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, op
return out, nil return out, nil
} }
var testServiceFullDuplexCallStreamDesc = &grpc.StreamDesc{
StreamName: "FullDuplexCall",
ServerStreams: true,
ClientStreams: true,
}
func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceFullDuplexCallStreamDesc, "/grpc.testing.TestService/FullDuplexCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/FullDuplexCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -88,13 +78,8 @@ func (x *testServiceFullDuplexCallClient) Recv() (*SimpleResponse, error) {
return m, nil return m, nil
} }
var testServiceClientStreamCallStreamDesc = &grpc.StreamDesc{
StreamName: "ClientStreamCall",
ClientStreams: true,
}
func (c *testServiceClient) ClientStreamCall(ctx context.Context, opts ...grpc.CallOption) (TestService_ClientStreamCallClient, error) { func (c *testServiceClient) ClientStreamCall(ctx context.Context, opts ...grpc.CallOption) (TestService_ClientStreamCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceClientStreamCallStreamDesc, "/grpc.testing.TestService/ClientStreamCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/ClientStreamCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -127,13 +112,8 @@ func (x *testServiceClientStreamCallClient) CloseAndRecv() (*SimpleResponse, err
return m, nil return m, nil
} }
var testServiceServerStreamCallStreamDesc = &grpc.StreamDesc{
StreamName: "ServerStreamCall",
ServerStreams: true,
}
func (c *testServiceClient) ServerStreamCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (TestService_ServerStreamCallClient, error) { func (c *testServiceClient) ServerStreamCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (TestService_ServerStreamCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceServerStreamCallStreamDesc, "/grpc.testing.TestService/ServerStreamCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/ServerStreamCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -164,53 +144,73 @@ func (x *testServiceServerStreamCallClient) Recv() (*SimpleResponse, error) {
return m, nil return m, nil
} }
// TestServiceService is the service API for TestService service. // TestServiceServer is the server API for TestService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedTestServiceServer
// RegisterTestServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type TestServiceServer interface {
type TestServiceService struct {
// One request followed by one response. // One request followed by one response.
// The server returns the client id as-is. // The server returns the client id as-is.
UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
// A sequence of requests with each request served by the server immediately. // A sequence of requests with each request served by the server immediately.
// As one request could lead to multiple responses, this interface // As one request could lead to multiple responses, this interface
// demonstrates the idea of full duplexing. // demonstrates the idea of full duplexing.
FullDuplexCall func(TestService_FullDuplexCallServer) error FullDuplexCall(TestService_FullDuplexCallServer) error
// Client stream // Client stream
ClientStreamCall func(TestService_ClientStreamCallServer) error ClientStreamCall(TestService_ClientStreamCallServer) error
// Server stream // Server stream
ServerStreamCall func(*SimpleRequest, TestService_ServerStreamCallServer) error ServerStreamCall(*SimpleRequest, TestService_ServerStreamCallServer) error
mustEmbedUnimplementedTestServiceServer()
} }
func (s *TestServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedTestServiceServer must be embedded to have forward compatible implementations.
type UnimplementedTestServiceServer struct {
}
func (UnimplementedTestServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented")
}
func (UnimplementedTestServiceServer) FullDuplexCall(TestService_FullDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented")
}
func (UnimplementedTestServiceServer) ClientStreamCall(TestService_ClientStreamCallServer) error {
return status.Errorf(codes.Unimplemented, "method ClientStreamCall not implemented")
}
func (UnimplementedTestServiceServer) ServerStreamCall(*SimpleRequest, TestService_ServerStreamCallServer) error {
return status.Errorf(codes.Unimplemented, "method ServerStreamCall not implemented")
}
func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {}
// UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to TestServiceServer will
// result in compilation errors.
type UnsafeTestServiceServer interface {
mustEmbedUnimplementedTestServiceServer()
}
func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) {
s.RegisterService(&_TestService_serviceDesc, srv)
}
func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimpleRequest) in := new(SimpleRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.UnaryCall(ctx, in) return srv.(TestServiceServer).UnaryCall(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.TestService/UnaryCall", FullMethod: "/grpc.testing.TestService/UnaryCall",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.UnaryCall(ctx, req.(*SimpleRequest)) return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *TestServiceService) fullDuplexCall(_ interface{}, stream grpc.ServerStream) error {
return s.FullDuplexCall(&testServiceFullDuplexCallServer{stream}) func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
} return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream})
func (s *TestServiceService) clientStreamCall(_ interface{}, stream grpc.ServerStream) error {
return s.ClientStreamCall(&testServiceClientStreamCallServer{stream})
}
func (s *TestServiceService) serverStreamCall(_ interface{}, stream grpc.ServerStream) error {
m := new(SimpleRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return s.ServerStreamCall(m, &testServiceServerStreamCallServer{stream})
} }
type TestService_FullDuplexCallServer interface { type TestService_FullDuplexCallServer interface {
@ -235,6 +235,10 @@ func (x *testServiceFullDuplexCallServer) Recv() (*SimpleRequest, error) {
return m, nil return m, nil
} }
func _TestService_ClientStreamCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServiceServer).ClientStreamCall(&testServiceClientStreamCallServer{stream})
}
type TestService_ClientStreamCallServer interface { type TestService_ClientStreamCallServer interface {
SendAndClose(*SimpleResponse) error SendAndClose(*SimpleResponse) error
Recv() (*SimpleRequest, error) Recv() (*SimpleRequest, error)
@ -257,6 +261,14 @@ func (x *testServiceClientStreamCallServer) Recv() (*SimpleRequest, error) {
return m, nil return m, nil
} }
func _TestService_ServerStreamCall_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(SimpleRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(TestServiceServer).ServerStreamCall(m, &testServiceServerStreamCallServer{stream})
}
type TestService_ServerStreamCallServer interface { type TestService_ServerStreamCallServer interface {
Send(*SimpleResponse) error Send(*SimpleResponse) error
grpc.ServerStream grpc.ServerStream
@ -270,57 +282,32 @@ func (x *testServiceServerStreamCallServer) Send(m *SimpleResponse) error {
return x.ServerStream.SendMsg(m) return x.ServerStream.SendMsg(m)
} }
// RegisterTestServiceService registers a service implementation with a gRPC server. var _TestService_serviceDesc = grpc.ServiceDesc{
func RegisterTestServiceService(s grpc.ServiceRegistrar, srv *TestServiceService) { ServiceName: "grpc.testing.TestService",
srvCopy := *srv HandlerType: (*TestServiceServer)(nil),
if srvCopy.UnaryCall == nil { Methods: []grpc.MethodDesc{
srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) { {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented") MethodName: "UnaryCall",
} Handler: _TestService_UnaryCall_Handler,
}
if srvCopy.FullDuplexCall == nil {
srvCopy.FullDuplexCall = func(TestService_FullDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented")
}
}
if srvCopy.ClientStreamCall == nil {
srvCopy.ClientStreamCall = func(TestService_ClientStreamCallServer) error {
return status.Errorf(codes.Unimplemented, "method ClientStreamCall not implemented")
}
}
if srvCopy.ServerStreamCall == nil {
srvCopy.ServerStreamCall = func(*SimpleRequest, TestService_ServerStreamCallServer) error {
return status.Errorf(codes.Unimplemented, "method ServerStreamCall not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.testing.TestService",
Methods: []grpc.MethodDesc{
{
MethodName: "UnaryCall",
Handler: srvCopy.unaryCall,
},
}, },
Streams: []grpc.StreamDesc{ },
{ Streams: []grpc.StreamDesc{
StreamName: "FullDuplexCall", {
Handler: srvCopy.fullDuplexCall, StreamName: "FullDuplexCall",
ServerStreams: true, Handler: _TestService_FullDuplexCall_Handler,
ClientStreams: true, ServerStreams: true,
}, ClientStreams: true,
{
StreamName: "ClientStreamCall",
Handler: srvCopy.clientStreamCall,
ClientStreams: true,
},
{
StreamName: "ServerStreamCall",
Handler: srvCopy.serverStreamCall,
ServerStreams: true,
},
}, },
Metadata: "stats/grpc_testing/test.proto", {
} StreamName: "ClientStreamCall",
Handler: _TestService_ClientStreamCall_Handler,
s.RegisterService(&sd, nil) ClientStreams: true,
},
{
StreamName: "ServerStreamCall",
Handler: _TestService_ServerStreamCall_Handler,
ServerStreams: true,
},
},
Metadata: "stats/grpc_testing/test.proto",
} }

View File

@ -73,15 +73,8 @@ var (
errorID int32 = 32202 errorID int32 = 32202
) )
type testServer struct{} type testServer struct {
testpb.UnimplementedTestServiceServer
func (s *testServer) Svc() *testpb.TestServiceService {
return &testpb.TestServiceService{
UnaryCall: s.UnaryCall,
FullDuplexCall: s.FullDuplexCall,
ClientStreamCall: s.ClientStreamCall,
ServerStreamCall: s.ServerStreamCall,
}
} }
func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
@ -172,7 +165,7 @@ type test struct {
clientStatsHandler stats.Handler clientStatsHandler stats.Handler
serverStatsHandler stats.Handler serverStatsHandler stats.Handler
testService *testpb.TestServiceService // nil means none testServer testpb.TestServiceServer // nil means none
// srv and srvAddr are set once startServer is called. // srv and srvAddr are set once startServer is called.
srv *grpc.Server srv *grpc.Server
srvAddr string srvAddr string
@ -207,8 +200,8 @@ func newTest(t *testing.T, tc *testConfig, ch stats.Handler, sh stats.Handler) *
// startServer starts a gRPC server listening. Callers should defer a // startServer starts a gRPC server listening. Callers should defer a
// call to te.tearDown to clean up. // call to te.tearDown to clean up.
func (te *test) startServer(ts *testpb.TestServiceService) { func (te *test) startServer(ts testpb.TestServiceServer) {
te.testService = ts te.testServer = ts
lis, err := net.Listen("tcp", "localhost:0") lis, err := net.Listen("tcp", "localhost:0")
if err != nil { if err != nil {
te.t.Fatalf("Failed to listen: %v", err) te.t.Fatalf("Failed to listen: %v", err)
@ -225,8 +218,8 @@ func (te *test) startServer(ts *testpb.TestServiceService) {
} }
s := grpc.NewServer(opts...) s := grpc.NewServer(opts...)
te.srv = s te.srv = s
if te.testService != nil { if te.testServer != nil {
testpb.RegisterTestServiceService(s, te.testService) testpb.RegisterTestServiceServer(s, te.testServer)
} }
go s.Serve(lis) go s.Serve(lis)
@ -822,7 +815,7 @@ func checkServerStats(t *testing.T, got []*gotData, expect *expectedData, checkF
func testServerStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs []func(t *testing.T, d *gotData, e *expectedData)) { func testServerStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs []func(t *testing.T, d *gotData, e *expectedData)) {
h := &statshandler{} h := &statshandler{}
te := newTest(t, tc, nil, h) te := newTest(t, tc, nil, h)
te.startServer((&testServer{}).Svc()) te.startServer(&testServer{})
defer te.tearDown() defer te.tearDown()
var ( var (
@ -1113,7 +1106,7 @@ func checkClientStats(t *testing.T, got []*gotData, expect *expectedData, checkF
func testClientStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs map[int]*checkFuncWithCount) { func testClientStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs map[int]*checkFuncWithCount) {
h := &statshandler{} h := &statshandler{}
te := newTest(t, tc, h, nil) te := newTest(t, tc, h, nil)
te.startServer((&testServer{}).Svc()) te.startServer(&testServer{})
defer te.tearDown() defer te.tearDown()
var ( var (

View File

@ -146,6 +146,7 @@ func (g *gauge) get() int64 {
// server implements metrics server functions. // server implements metrics server functions.
type server struct { type server struct {
metricspb.UnimplementedMetricsServiceServer
mutex sync.RWMutex mutex sync.RWMutex
// gauges is a map from /stress_test/server_<n>/channel_<n>/stub_<n>/qps to its qps gauge. // gauges is a map from /stress_test/server_<n>/channel_<n>/stub_<n>/qps to its qps gauge.
gauges map[string]*gauge gauges map[string]*gauge
@ -156,13 +157,6 @@ func newMetricsServer() *server {
return &server{gauges: make(map[string]*gauge)} return &server{gauges: make(map[string]*gauge)}
} }
func (s *server) Svc() *metricspb.MetricsServiceService {
return &metricspb.MetricsServiceService{
GetAllGauges: s.GetAllGauges,
GetGauge: s.GetGauge,
}
}
// GetAllGauges returns all gauges. // GetAllGauges returns all gauges.
func (s *server) GetAllGauges(in *metricspb.EmptyMessage, stream metricspb.MetricsService_GetAllGaugesServer) error { func (s *server) GetAllGauges(in *metricspb.EmptyMessage, stream metricspb.MetricsService_GetAllGaugesServer) error {
s.mutex.RLock() s.mutex.RLock()
@ -208,8 +202,9 @@ func startServer(server *server, port int) {
} }
s := grpc.NewServer() s := grpc.NewServer()
metricspb.RegisterMetricsServiceService(s, server.Svc()) metricspb.RegisterMetricsServiceServer(s, server)
s.Serve(lis) s.Serve(lis)
} }
// performRPCs uses weightedRandomTestSelector to select test case and runs the tests. // performRPCs uses weightedRandomTestSelector to select test case and runs the tests.

View File

@ -32,13 +32,8 @@ func NewMetricsServiceClient(cc grpc.ClientConnInterface) MetricsServiceClient {
return &metricsServiceClient{cc} return &metricsServiceClient{cc}
} }
var metricsServiceGetAllGaugesStreamDesc = &grpc.StreamDesc{
StreamName: "GetAllGauges",
ServerStreams: true,
}
func (c *metricsServiceClient) GetAllGauges(ctx context.Context, in *EmptyMessage, opts ...grpc.CallOption) (MetricsService_GetAllGaugesClient, error) { func (c *metricsServiceClient) GetAllGauges(ctx context.Context, in *EmptyMessage, opts ...grpc.CallOption) (MetricsService_GetAllGaugesClient, error) {
stream, err := c.cc.NewStream(ctx, metricsServiceGetAllGaugesStreamDesc, "/grpc.testing.MetricsService/GetAllGauges", opts...) stream, err := c.cc.NewStream(ctx, &_MetricsService_serviceDesc.Streams[0], "/grpc.testing.MetricsService/GetAllGauges", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -69,10 +64,6 @@ func (x *metricsServiceGetAllGaugesClient) Recv() (*GaugeResponse, error) {
return m, nil return m, nil
} }
var metricsServiceGetGaugeStreamDesc = &grpc.StreamDesc{
StreamName: "GetGauge",
}
func (c *metricsServiceClient) GetGauge(ctx context.Context, in *GaugeRequest, opts ...grpc.CallOption) (*GaugeResponse, error) { func (c *metricsServiceClient) GetGauge(ctx context.Context, in *GaugeRequest, opts ...grpc.CallOption) (*GaugeResponse, error) {
out := new(GaugeResponse) out := new(GaugeResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.MetricsService/GetGauge", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.MetricsService/GetGauge", in, out, opts...)
@ -82,41 +73,47 @@ func (c *metricsServiceClient) GetGauge(ctx context.Context, in *GaugeRequest, o
return out, nil return out, nil
} }
// MetricsServiceService is the service API for MetricsService service. // MetricsServiceServer is the server API for MetricsService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedMetricsServiceServer
// RegisterMetricsServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type MetricsServiceServer interface {
type MetricsServiceService struct {
// Returns the values of all the gauges that are currently being maintained by // Returns the values of all the gauges that are currently being maintained by
// the service // the service
GetAllGauges func(*EmptyMessage, MetricsService_GetAllGaugesServer) error GetAllGauges(*EmptyMessage, MetricsService_GetAllGaugesServer) error
// Returns the value of one gauge // Returns the value of one gauge
GetGauge func(context.Context, *GaugeRequest) (*GaugeResponse, error) GetGauge(context.Context, *GaugeRequest) (*GaugeResponse, error)
mustEmbedUnimplementedMetricsServiceServer()
} }
func (s *MetricsServiceService) getAllGauges(_ interface{}, stream grpc.ServerStream) error { // UnimplementedMetricsServiceServer must be embedded to have forward compatible implementations.
type UnimplementedMetricsServiceServer struct {
}
func (UnimplementedMetricsServiceServer) GetAllGauges(*EmptyMessage, MetricsService_GetAllGaugesServer) error {
return status.Errorf(codes.Unimplemented, "method GetAllGauges not implemented")
}
func (UnimplementedMetricsServiceServer) GetGauge(context.Context, *GaugeRequest) (*GaugeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetGauge not implemented")
}
func (UnimplementedMetricsServiceServer) mustEmbedUnimplementedMetricsServiceServer() {}
// UnsafeMetricsServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to MetricsServiceServer will
// result in compilation errors.
type UnsafeMetricsServiceServer interface {
mustEmbedUnimplementedMetricsServiceServer()
}
func RegisterMetricsServiceServer(s *grpc.Server, srv MetricsServiceServer) {
s.RegisterService(&_MetricsService_serviceDesc, srv)
}
func _MetricsService_GetAllGauges_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(EmptyMessage) m := new(EmptyMessage)
if err := stream.RecvMsg(m); err != nil { if err := stream.RecvMsg(m); err != nil {
return err return err
} }
return s.GetAllGauges(m, &metricsServiceGetAllGaugesServer{stream}) return srv.(MetricsServiceServer).GetAllGauges(m, &metricsServiceGetAllGaugesServer{stream})
}
func (s *MetricsServiceService) getGauge(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GaugeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return s.GetGauge(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: s,
FullMethod: "/grpc.testing.MetricsService/GetGauge",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.GetGauge(ctx, req.(*GaugeRequest))
}
return interceptor(ctx, in, info, handler)
} }
type MetricsService_GetAllGaugesServer interface { type MetricsService_GetAllGaugesServer interface {
@ -132,36 +129,39 @@ func (x *metricsServiceGetAllGaugesServer) Send(m *GaugeResponse) error {
return x.ServerStream.SendMsg(m) return x.ServerStream.SendMsg(m)
} }
// RegisterMetricsServiceService registers a service implementation with a gRPC server. func _MetricsService_GetGauge_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
func RegisterMetricsServiceService(s grpc.ServiceRegistrar, srv *MetricsServiceService) { in := new(GaugeRequest)
srvCopy := *srv if err := dec(in); err != nil {
if srvCopy.GetAllGauges == nil { return nil, err
srvCopy.GetAllGauges = func(*EmptyMessage, MetricsService_GetAllGaugesServer) error {
return status.Errorf(codes.Unimplemented, "method GetAllGauges not implemented")
}
} }
if srvCopy.GetGauge == nil { if interceptor == nil {
srvCopy.GetGauge = func(context.Context, *GaugeRequest) (*GaugeResponse, error) { return srv.(MetricsServiceServer).GetGauge(ctx, in)
return nil, status.Errorf(codes.Unimplemented, "method GetGauge not implemented")
}
} }
sd := grpc.ServiceDesc{ info := &grpc.UnaryServerInfo{
ServiceName: "grpc.testing.MetricsService", Server: srv,
Methods: []grpc.MethodDesc{ FullMethod: "/grpc.testing.MetricsService/GetGauge",
{
MethodName: "GetGauge",
Handler: srvCopy.getGauge,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "GetAllGauges",
Handler: srvCopy.getAllGauges,
ServerStreams: true,
},
},
Metadata: "stress/grpc_testing/metrics.proto",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
s.RegisterService(&sd, nil) return srv.(MetricsServiceServer).GetGauge(ctx, req.(*GaugeRequest))
}
return interceptor(ctx, in, info, handler)
}
var _MetricsService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.testing.MetricsService",
HandlerType: (*MetricsServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetGauge",
Handler: _MetricsService_GetGauge_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "GetAllGauges",
Handler: _MetricsService_GetAllGauges_Handler,
ServerStreams: true,
},
},
Metadata: "stress/grpc_testing/metrics.proto",
} }

View File

@ -150,7 +150,7 @@ func (s) TestCredsBundleFromBalancer(t *testing.T) {
te.customServerOptions = []grpc.ServerOption{ te.customServerOptions = []grpc.ServerOption{
grpc.Creds(creds), grpc.Creds(creds),
} }
te.startServer((&testServer{}).Svc()) te.startServer(&testServer{})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
@ -179,7 +179,7 @@ func testPickExtraMetadata(t *testing.T, e env) {
grpc.WithBalancerName(testBalancerName), grpc.WithBalancerName(testBalancerName),
grpc.WithUserAgent(testUserAgent), grpc.WithUserAgent(testUserAgent),
} }
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
// Set resolver to xds to trigger the extra metadata code path. // Set resolver to xds to trigger the extra metadata code path.
@ -228,7 +228,7 @@ func testDoneInfo(t *testing.T, e env) {
grpc.WithBalancerName(testBalancerName), grpc.WithBalancerName(testBalancerName),
} }
te.userAgent = failAppUA te.userAgent = failAppUA
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
@ -498,7 +498,7 @@ func (s) TestAddressAttributesInNewSubConn(t *testing.T) {
} }
s := grpc.NewServer() s := grpc.NewServer()
testpb.RegisterTestServiceService(s, (&testServer{}).Svc()) testpb.RegisterTestServiceServer(s, &testServer{})
go s.Serve(lis) go s.Serve(lis)
defer s.Stop() defer s.Stop()
t.Logf("Started gRPC server at %s...", lis.Addr().String()) t.Logf("Started gRPC server at %s...", lis.Addr().String())
@ -556,12 +556,12 @@ func (s) TestServersSwap(t *testing.T) {
t.Fatalf("Error while listening. Err: %v", err) t.Fatalf("Error while listening. Err: %v", err)
} }
s := grpc.NewServer() s := grpc.NewServer()
ts := &testpb.TestServiceService{ ts := &funcServer{
UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{Username: username}, nil return &testpb.SimpleResponse{Username: username}, nil
}, },
} }
testpb.RegisterTestServiceService(s, ts) testpb.RegisterTestServiceServer(s, ts)
go s.Serve(lis) go s.Serve(lis)
return lis.Addr().String(), s.Stop return lis.Addr().String(), s.Stop
} }
@ -616,12 +616,12 @@ func (s) TestEmptyAddrs(t *testing.T) {
s := grpc.NewServer() s := grpc.NewServer()
defer s.Stop() defer s.Stop()
const one = "1" const one = "1"
ts := &testpb.TestServiceService{ ts := &funcServer{
UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{Username: one}, nil return &testpb.SimpleResponse{Username: one}, nil
}, },
} }
testpb.RegisterTestServiceService(s, ts) testpb.RegisterTestServiceServer(s, ts)
go s.Serve(lis) go s.Serve(lis)
// Initialize pickfirst client // Initialize pickfirst client
@ -705,12 +705,12 @@ func (s) TestWaitForReady(t *testing.T) {
s := grpc.NewServer() s := grpc.NewServer()
defer s.Stop() defer s.Stop()
const one = "1" const one = "1"
ts := &testpb.TestServiceService{ ts := &funcServer{
UnaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
return &testpb.SimpleResponse{Username: one}, nil return &testpb.SimpleResponse{Username: one}, nil
}, },
} }
testpb.RegisterTestServiceService(s, ts) testpb.RegisterTestServiceServer(s, ts)
go s.Serve(lis) go s.Serve(lis)
// Initialize client // Initialize client

View File

@ -43,7 +43,7 @@ func testCZSocketMetricsSocketOption(t *testing.T, e env) {
czCleanup := channelz.NewChannelzStorage() czCleanup := channelz.NewChannelzStorage()
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
te := newTest(t, e) te := newTest(t, e)
te.startServer((&testServer{security: e.security}).Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
tc := testpb.NewTestServiceClient(cc) tc := testpb.NewTestServiceClient(cc)

View File

@ -85,7 +85,7 @@ func (s) TestCZServerRegistrationAndDeletion(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServers(testServer{security: e.security}.Svc(), c.total) te.startServers(&testServer{security: e.security}, c.total)
ss, end := channelz.GetServers(c.start, c.max) ss, end := channelz.GetServers(c.start, c.max)
if int64(len(ss)) != c.length || end != c.end { if int64(len(ss)) != c.length || end != c.end {
@ -104,7 +104,7 @@ func (s) TestCZGetServer(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
ss, _ := channelz.GetServers(0, 0) ss, _ := channelz.GetServers(0, 0)
@ -253,7 +253,7 @@ func (s) TestCZClientSubChannelSocketRegistrationAndDeletion(t *testing.T) {
num := 3 // number of backends num := 3 // number of backends
te := newTest(t, e) te := newTest(t, e)
var svrAddrs []resolver.Address var svrAddrs []resolver.Address
te.startServers(testServer{security: e.security}.Svc(), num) te.startServers(&testServer{security: e.security}, num)
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
for _, a := range te.srvAddrs { for _, a := range te.srvAddrs {
svrAddrs = append(svrAddrs, resolver.Address{Addr: a}) svrAddrs = append(svrAddrs, resolver.Address{Addr: a})
@ -339,7 +339,7 @@ func (s) TestCZServerSocketRegistrationAndDeletion(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
var ccs []*grpc.ClientConn var ccs []*grpc.ClientConn
for i := 0; i < c.total; i++ { for i := 0; i < c.total; i++ {
cc := te.clientConn() cc := te.clientConn()
@ -504,7 +504,7 @@ func (s) TestCZChannelMetrics(t *testing.T) {
te := newTest(t, e) te := newTest(t, e)
te.maxClientSendMsgSize = newInt(8) te.maxClientSendMsgSize = newInt(8)
var svrAddrs []resolver.Address var svrAddrs []resolver.Address
te.startServers(testServer{security: e.security}.Svc(), num) te.startServers(&testServer{security: e.security}, num)
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
for _, a := range te.srvAddrs { for _, a := range te.srvAddrs {
svrAddrs = append(svrAddrs, resolver.Address{Addr: a}) svrAddrs = append(svrAddrs, resolver.Address{Addr: a})
@ -590,7 +590,7 @@ func (s) TestCZServerMetrics(t *testing.T) {
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.maxServerReceiveMsgSize = newInt(8) te.maxServerReceiveMsgSize = newInt(8)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
tc := testpb.NewTestServiceClient(cc) tc := testpb.NewTestServiceClient(cc)
@ -861,7 +861,7 @@ func (s) TestCZClientSocketMetricsStreamsAndMessagesCount(t *testing.T) {
te := newTest(t, e) te := newTest(t, e)
te.maxServerReceiveMsgSize = newInt(20) te.maxServerReceiveMsgSize = newInt(20)
te.maxClientReceiveMsgSize = newInt(20) te.maxClientReceiveMsgSize = newInt(20)
rcw := te.startServerWithConnControl(testServer{security: e.security}.Svc()) rcw := te.startServerWithConnControl(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)}
@ -963,7 +963,7 @@ func (s) TestCZClientAndServerSocketMetricsStreamsCountFlowControlRSTStream(t *t
// Avoid overflowing connection level flow control window, which will lead to // Avoid overflowing connection level flow control window, which will lead to
// transport being closed. // transport being closed.
te.serverInitialConnWindowSize = 65536 * 2 te.serverInitialConnWindowSize = 65536 * 2
ts := &testpb.TestServiceService{FullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { ts := &stubServer{fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error {
stream.Send(&testpb.StreamingOutputCallResponse{}) stream.Send(&testpb.StreamingOutputCallResponse{})
<-stream.Context().Done() <-stream.Context().Done()
return status.Errorf(codes.DeadlineExceeded, "deadline exceeded or cancelled") return status.Errorf(codes.DeadlineExceeded, "deadline exceeded or cancelled")
@ -1048,7 +1048,7 @@ func (s) TestCZClientAndServerSocketMetricsFlowControl(t *testing.T) {
te.serverInitialConnWindowSize = 65536 te.serverInitialConnWindowSize = 65536
te.clientInitialWindowSize = 65536 te.clientInitialWindowSize = 65536
te.clientInitialConnWindowSize = 65536 te.clientInitialConnWindowSize = 65536
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
tc := testpb.NewTestServiceClient(cc) tc := testpb.NewTestServiceClient(cc)
@ -1169,7 +1169,7 @@ func (s) TestCZClientSocketMetricsKeepAlive(t *testing.T) {
MinTime: 500 * time.Millisecond, MinTime: 500 * time.Millisecond,
PermitWithoutStream: true, PermitWithoutStream: true,
})) }))
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
te.clientConn() // Dial the server te.clientConn() // Dial the server
defer te.tearDown() defer te.tearDown()
if err := verifyResultWithDelay(func() (bool, error) { if err := verifyResultWithDelay(func() (bool, error) {
@ -1211,7 +1211,7 @@ func (s) TestCZServerSocketMetricsStreamsAndMessagesCount(t *testing.T) {
te := newTest(t, e) te := newTest(t, e)
te.maxServerReceiveMsgSize = newInt(20) te.maxServerReceiveMsgSize = newInt(20)
te.maxClientReceiveMsgSize = newInt(20) te.maxClientReceiveMsgSize = newInt(20)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc, _ := te.clientConnWithConnControl() cc, _ := te.clientConnWithConnControl()
tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)}
@ -1282,7 +1282,7 @@ func (s) TestCZServerSocketMetricsKeepAlive(t *testing.T) {
Timeout: 100 * time.Millisecond, Timeout: 100 * time.Millisecond,
}) })
te.customServerOptions = append(te.customServerOptions, kpOption) te.customServerOptions = append(te.customServerOptions, kpOption)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
tc := testpb.NewTestServiceClient(cc) tc := testpb.NewTestServiceClient(cc)
@ -1342,7 +1342,7 @@ func (s) TestCZSocketGetSecurityValueTLS(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpTLSRREnv e := tcpTLSRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
te.clientConn() te.clientConn()
if err := verifyResultWithDelay(func() (bool, error) { if err := verifyResultWithDelay(func() (bool, error) {
@ -1467,7 +1467,7 @@ func (s) TestCZSubChannelTraceCreationDeletion(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}})
te.resolverScheme = r.Scheme() te.resolverScheme = r.Scheme()
@ -1560,7 +1560,7 @@ func (s) TestCZChannelAddressResolutionChange(t *testing.T) {
e := tcpClearRREnv e := tcpClearRREnv
e.balancer = "" e.balancer = ""
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
addrs := []resolver.Address{{Addr: te.srvAddr}} addrs := []resolver.Address{{Addr: te.srvAddr}}
r.InitialState(resolver.State{Addresses: addrs}) r.InitialState(resolver.State{Addresses: addrs})
@ -1663,7 +1663,7 @@ func (s) TestCZSubChannelPickedNewAddress(t *testing.T) {
e := tcpClearRREnv e := tcpClearRREnv
e.balancer = "" e.balancer = ""
te := newTest(t, e) te := newTest(t, e)
te.startServers(testServer{security: e.security}.Svc(), 3) te.startServers(&testServer{security: e.security}, 3)
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
var svrAddrs []resolver.Address var svrAddrs []resolver.Address
for _, a := range te.srvAddrs { for _, a := range te.srvAddrs {
@ -1722,7 +1722,7 @@ func (s) TestCZSubChannelConnectivityState(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}})
te.resolverScheme = r.Scheme() te.resolverScheme = r.Scheme()
@ -1816,7 +1816,7 @@ func (s) TestCZChannelConnectivityState(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}})
te.resolverScheme = r.Scheme() te.resolverScheme = r.Scheme()
@ -1939,7 +1939,7 @@ func (s) TestCZTraceOverwriteSubChannelDeletion(t *testing.T) {
te := newTest(t, e) te := newTest(t, e)
channelz.SetMaxTraceEntry(1) channelz.SetMaxTraceEntry(1)
defer channelz.ResetMaxTraceEntryToDefault() defer channelz.ResetMaxTraceEntryToDefault()
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}})
te.resolverScheme = r.Scheme() te.resolverScheme = r.Scheme()
@ -1997,7 +1997,7 @@ func (s) TestCZTraceTopChannelDeletionTraceClear(t *testing.T) {
defer czCleanupWrapper(czCleanup, t) defer czCleanupWrapper(czCleanup, t)
e := tcpClearRREnv e := tcpClearRREnv
te := newTest(t, e) te := newTest(t, e)
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
r := manual.NewBuilderWithScheme("whatever") r := manual.NewBuilderWithScheme("whatever")
r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}}) r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: te.srvAddr}}})
te.resolverScheme = r.Scheme() te.resolverScheme = r.Scheme()

View File

@ -87,7 +87,7 @@ func (s) TestCredsBundleBoth(t *testing.T) {
te.customServerOptions = []grpc.ServerOption{ te.customServerOptions = []grpc.ServerOption{
grpc.Creds(creds), grpc.Creds(creds),
} }
te.startServer(testServer{}.Svc()) te.startServer(&testServer{})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
@ -109,7 +109,7 @@ func (s) TestCredsBundleTransportCredentials(t *testing.T) {
te.customServerOptions = []grpc.ServerOption{ te.customServerOptions = []grpc.ServerOption{
grpc.Creds(creds), grpc.Creds(creds),
} }
te.startServer(testServer{}.Svc()) te.startServer(&testServer{})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
@ -125,7 +125,7 @@ func (s) TestCredsBundlePerRPCCredentials(t *testing.T) {
te.customDialOptions = []grpc.DialOption{ te.customDialOptions = []grpc.DialOption{
grpc.WithCredentialsBundle(&testCredsBundle{t: t, mode: bundlePerRPCOnly}), grpc.WithCredentialsBundle(&testCredsBundle{t: t, mode: bundlePerRPCOnly}),
} }
te.startServer(testServer{}.Svc()) te.startServer(&testServer{})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
@ -159,7 +159,7 @@ func (c *clientTimeoutCreds) Clone() credentials.TransportCredentials {
func (s) TestNonFailFastRPCSucceedOnTimeoutCreds(t *testing.T) { func (s) TestNonFailFastRPCSucceedOnTimeoutCreds(t *testing.T) {
te := newTest(t, env{name: "timeout-cred", network: "tcp", security: "empty"}) te := newTest(t, env{name: "timeout-cred", network: "tcp", security: "empty"})
te.userAgent = testAppUA te.userAgent = testAppUA
te.startServer(testServer{security: te.e.security}.Svc()) te.startServer(&testServer{security: te.e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn(grpc.WithTransportCredentials(&clientTimeoutCreds{})) cc := te.clientConn(grpc.WithTransportCredentials(&clientTimeoutCreds{}))
@ -183,7 +183,7 @@ func (s) TestGRPCMethodAccessibleToCredsViaContextRequestInfo(t *testing.T) {
const wantMethod = "/grpc.testing.TestService/EmptyCall" const wantMethod = "/grpc.testing.TestService/EmptyCall"
te := newTest(t, env{name: "context-request-info", network: "tcp"}) te := newTest(t, env{name: "context-request-info", network: "tcp"})
te.userAgent = testAppUA te.userAgent = testAppUA
te.startServer(testServer{security: te.e.security}.Svc()) te.startServer(&testServer{security: te.e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn(grpc.WithPerRPCCredentials(&methodTestCreds{})) cc := te.clientConn(grpc.WithPerRPCCredentials(&methodTestCreds{}))
@ -218,7 +218,7 @@ func (c clientAlwaysFailCred) Clone() credentials.TransportCredentials {
func (s) TestFailFastRPCErrorOnBadCertificates(t *testing.T) { func (s) TestFailFastRPCErrorOnBadCertificates(t *testing.T) {
te := newTest(t, env{name: "bad-cred", network: "tcp", security: "empty", balancer: "round_robin"}) te := newTest(t, env{name: "bad-cred", network: "tcp", security: "empty", balancer: "round_robin"})
te.startServer(testServer{security: te.e.security}.Svc()) te.startServer(&testServer{security: te.e.security})
defer te.tearDown() defer te.tearDown()
opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})} opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})}
@ -246,7 +246,7 @@ func (s) TestFailFastRPCErrorOnBadCertificates(t *testing.T) {
func (s) TestWaitForReadyRPCErrorOnBadCertificates(t *testing.T) { func (s) TestWaitForReadyRPCErrorOnBadCertificates(t *testing.T) {
te := newTest(t, env{name: "bad-cred", network: "tcp", security: "empty", balancer: "round_robin"}) te := newTest(t, env{name: "bad-cred", network: "tcp", security: "empty", balancer: "round_robin"})
te.startServer(testServer{security: te.e.security}.Svc()) te.startServer(&testServer{security: te.e.security})
defer te.tearDown() defer te.tearDown()
opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})} opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})}
@ -312,7 +312,7 @@ func testPerRPCCredentialsViaDialOptions(t *testing.T, e env) {
te := newTest(t, e) te := newTest(t, e)
te.tapHandle = authHandle te.tapHandle = authHandle
te.perRPCCreds = testPerRPCCredentials{} te.perRPCCreds = testPerRPCCredentials{}
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
@ -331,7 +331,7 @@ func (s) TestPerRPCCredentialsViaCallOptions(t *testing.T) {
func testPerRPCCredentialsViaCallOptions(t *testing.T, e env) { func testPerRPCCredentialsViaCallOptions(t *testing.T, e env) {
te := newTest(t, e) te := newTest(t, e)
te.tapHandle = authHandle te.tapHandle = authHandle
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()
@ -371,7 +371,7 @@ func testPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T, e env) {
} }
return ctx, nil return ctx, nil
} }
te.startServer(testServer{security: e.security}.Svc()) te.startServer(&testServer{security: e.security})
defer te.tearDown() defer te.tearDown()
cc := te.clientConn() cc := te.clientConn()

File diff suppressed because it is too large Load Diff

View File

@ -48,7 +48,7 @@ func (s) TestGracefulClientOnGoAway(t *testing.T) {
s := grpc.NewServer(grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionAge: maxConnAge})) s := grpc.NewServer(grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionAge: maxConnAge}))
defer s.Stop() defer s.Stop()
testpb.RegisterTestServiceService(s, ss.Svc()) testpb.RegisterTestServiceServer(s, ss)
lis, err := net.Listen("tcp", "localhost:0") lis, err := net.Listen("tcp", "localhost:0")
if err != nil { if err != nil {

View File

@ -117,7 +117,7 @@ func (s) TestGracefulStop(t *testing.T) {
}, },
} }
s := grpc.NewServer() s := grpc.NewServer()
testpb.RegisterTestServiceService(s, ss.Svc()) testpb.RegisterTestServiceServer(s, ss)
// 1. Start Server // 1. Start Server
wg := sync.WaitGroup{} wg := sync.WaitGroup{}

View File

@ -47,10 +47,6 @@ func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient {
return &testServiceClient{cc} return &testServiceClient{cc}
} }
var testServiceEmptyCallStreamDesc = &grpc.StreamDesc{
StreamName: "EmptyCall",
}
func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) {
out := new(Empty) out := new(Empty)
err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...)
@ -60,10 +56,6 @@ func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...gr
return out, nil return out, nil
} }
var testServiceUnaryCallStreamDesc = &grpc.StreamDesc{
StreamName: "UnaryCall",
}
func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
out := new(SimpleResponse) out := new(SimpleResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...)
@ -73,13 +65,8 @@ func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, op
return out, nil return out, nil
} }
var testServiceStreamingOutputCallStreamDesc = &grpc.StreamDesc{
StreamName: "StreamingOutputCall",
ServerStreams: true,
}
func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceStreamingOutputCallStreamDesc, "/grpc.testing.TestService/StreamingOutputCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/StreamingOutputCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -110,13 +97,8 @@ func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallRespo
return m, nil return m, nil
} }
var testServiceStreamingInputCallStreamDesc = &grpc.StreamDesc{
StreamName: "StreamingInputCall",
ClientStreams: true,
}
func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceStreamingInputCallStreamDesc, "/grpc.testing.TestService/StreamingInputCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/StreamingInputCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -149,14 +131,8 @@ func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCal
return m, nil return m, nil
} }
var testServiceFullDuplexCallStreamDesc = &grpc.StreamDesc{
StreamName: "FullDuplexCall",
ServerStreams: true,
ClientStreams: true,
}
func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceFullDuplexCallStreamDesc, "/grpc.testing.TestService/FullDuplexCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/FullDuplexCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -186,14 +162,8 @@ func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse,
return m, nil return m, nil
} }
var testServiceHalfDuplexCallStreamDesc = &grpc.StreamDesc{
StreamName: "HalfDuplexCall",
ServerStreams: true,
ClientStreams: true,
}
func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) {
stream, err := c.cc.NewStream(ctx, testServiceHalfDuplexCallStreamDesc, "/grpc.testing.TestService/HalfDuplexCall", opts...) stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[3], "/grpc.testing.TestService/HalfDuplexCall", opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -223,82 +193,110 @@ func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse,
return m, nil return m, nil
} }
// TestServiceService is the service API for TestService service. // TestServiceServer is the server API for TestService service.
// Fields should be assigned to their respective handler implementations only before // All implementations must embed UnimplementedTestServiceServer
// RegisterTestServiceService is called. Any unassigned fields will result in the // for forward compatibility
// handler for that method returning an Unimplemented error. type TestServiceServer interface {
type TestServiceService struct {
// One empty request followed by one empty response. // One empty request followed by one empty response.
EmptyCall func(context.Context, *Empty) (*Empty, error) EmptyCall(context.Context, *Empty) (*Empty, error)
// One request followed by one response. // One request followed by one response.
// The server returns the client payload as-is. // The server returns the client payload as-is.
UnaryCall func(context.Context, *SimpleRequest) (*SimpleResponse, error) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
// One request followed by a sequence of responses (streamed download). // One request followed by a sequence of responses (streamed download).
// The server returns the payload with client desired type and sizes. // The server returns the payload with client desired type and sizes.
StreamingOutputCall func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error
// A sequence of requests followed by one response (streamed upload). // A sequence of requests followed by one response (streamed upload).
// The server returns the aggregated size of client payload as the result. // The server returns the aggregated size of client payload as the result.
StreamingInputCall func(TestService_StreamingInputCallServer) error StreamingInputCall(TestService_StreamingInputCallServer) error
// A sequence of requests with each request served by the server immediately. // A sequence of requests with each request served by the server immediately.
// As one request could lead to multiple responses, this interface // As one request could lead to multiple responses, this interface
// demonstrates the idea of full duplexing. // demonstrates the idea of full duplexing.
FullDuplexCall func(TestService_FullDuplexCallServer) error FullDuplexCall(TestService_FullDuplexCallServer) error
// A sequence of requests followed by a sequence of responses. // A sequence of requests followed by a sequence of responses.
// The server buffers all the client requests and then serves them in order. A // The server buffers all the client requests and then serves them in order. A
// stream of responses are returned to the client when the server starts with // stream of responses are returned to the client when the server starts with
// first request. // first request.
HalfDuplexCall func(TestService_HalfDuplexCallServer) error HalfDuplexCall(TestService_HalfDuplexCallServer) error
mustEmbedUnimplementedTestServiceServer()
} }
func (s *TestServiceService) emptyCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { // UnimplementedTestServiceServer must be embedded to have forward compatible implementations.
type UnimplementedTestServiceServer struct {
}
func (UnimplementedTestServiceServer) EmptyCall(context.Context, *Empty) (*Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented")
}
func (UnimplementedTestServiceServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented")
}
func (UnimplementedTestServiceServer) StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented")
}
func (UnimplementedTestServiceServer) StreamingInputCall(TestService_StreamingInputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented")
}
func (UnimplementedTestServiceServer) FullDuplexCall(TestService_FullDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented")
}
func (UnimplementedTestServiceServer) HalfDuplexCall(TestService_HalfDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented")
}
func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {}
// UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to TestServiceServer will
// result in compilation errors.
type UnsafeTestServiceServer interface {
mustEmbedUnimplementedTestServiceServer()
}
func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) {
s.RegisterService(&_TestService_serviceDesc, srv)
}
func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Empty) in := new(Empty)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.EmptyCall(ctx, in) return srv.(TestServiceServer).EmptyCall(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.TestService/EmptyCall", FullMethod: "/grpc.testing.TestService/EmptyCall",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.EmptyCall(ctx, req.(*Empty)) return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *TestServiceService) unaryCall(_ interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimpleRequest) in := new(SimpleRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
return nil, err return nil, err
} }
if interceptor == nil { if interceptor == nil {
return s.UnaryCall(ctx, in) return srv.(TestServiceServer).UnaryCall(ctx, in)
} }
info := &grpc.UnaryServerInfo{ info := &grpc.UnaryServerInfo{
Server: s, Server: srv,
FullMethod: "/grpc.testing.TestService/UnaryCall", FullMethod: "/grpc.testing.TestService/UnaryCall",
} }
handler := func(ctx context.Context, req interface{}) (interface{}, error) { handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return s.UnaryCall(ctx, req.(*SimpleRequest)) return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest))
} }
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func (s *TestServiceService) streamingOutputCall(_ interface{}, stream grpc.ServerStream) error {
func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(StreamingOutputCallRequest) m := new(StreamingOutputCallRequest)
if err := stream.RecvMsg(m); err != nil { if err := stream.RecvMsg(m); err != nil {
return err return err
} }
return s.StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream})
}
func (s *TestServiceService) streamingInputCall(_ interface{}, stream grpc.ServerStream) error {
return s.StreamingInputCall(&testServiceStreamingInputCallServer{stream})
}
func (s *TestServiceService) fullDuplexCall(_ interface{}, stream grpc.ServerStream) error {
return s.FullDuplexCall(&testServiceFullDuplexCallServer{stream})
}
func (s *TestServiceService) halfDuplexCall(_ interface{}, stream grpc.ServerStream) error {
return s.HalfDuplexCall(&testServiceHalfDuplexCallServer{stream})
} }
type TestService_StreamingOutputCallServer interface { type TestService_StreamingOutputCallServer interface {
@ -314,6 +312,10 @@ func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallRespon
return x.ServerStream.SendMsg(m) return x.ServerStream.SendMsg(m)
} }
func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream})
}
type TestService_StreamingInputCallServer interface { type TestService_StreamingInputCallServer interface {
SendAndClose(*StreamingInputCallResponse) error SendAndClose(*StreamingInputCallResponse) error
Recv() (*StreamingInputCallRequest, error) Recv() (*StreamingInputCallRequest, error)
@ -336,6 +338,10 @@ func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest
return m, nil return m, nil
} }
func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream})
}
type TestService_FullDuplexCallServer interface { type TestService_FullDuplexCallServer interface {
Send(*StreamingOutputCallResponse) error Send(*StreamingOutputCallResponse) error
Recv() (*StreamingOutputCallRequest, error) Recv() (*StreamingOutputCallRequest, error)
@ -358,6 +364,10 @@ func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, e
return m, nil return m, nil
} }
func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream})
}
type TestService_HalfDuplexCallServer interface { type TestService_HalfDuplexCallServer interface {
Send(*StreamingOutputCallResponse) error Send(*StreamingOutputCallResponse) error
Recv() (*StreamingOutputCallRequest, error) Recv() (*StreamingOutputCallRequest, error)
@ -380,77 +390,42 @@ func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, e
return m, nil return m, nil
} }
// RegisterTestServiceService registers a service implementation with a gRPC server. var _TestService_serviceDesc = grpc.ServiceDesc{
func RegisterTestServiceService(s grpc.ServiceRegistrar, srv *TestServiceService) { ServiceName: "grpc.testing.TestService",
srvCopy := *srv HandlerType: (*TestServiceServer)(nil),
if srvCopy.EmptyCall == nil { Methods: []grpc.MethodDesc{
srvCopy.EmptyCall = func(context.Context, *Empty) (*Empty, error) { {
return nil, status.Errorf(codes.Unimplemented, "method EmptyCall not implemented") MethodName: "EmptyCall",
} Handler: _TestService_EmptyCall_Handler,
}
if srvCopy.UnaryCall == nil {
srvCopy.UnaryCall = func(context.Context, *SimpleRequest) (*SimpleResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented")
}
}
if srvCopy.StreamingOutputCall == nil {
srvCopy.StreamingOutputCall = func(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingOutputCall not implemented")
}
}
if srvCopy.StreamingInputCall == nil {
srvCopy.StreamingInputCall = func(TestService_StreamingInputCallServer) error {
return status.Errorf(codes.Unimplemented, "method StreamingInputCall not implemented")
}
}
if srvCopy.FullDuplexCall == nil {
srvCopy.FullDuplexCall = func(TestService_FullDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method FullDuplexCall not implemented")
}
}
if srvCopy.HalfDuplexCall == nil {
srvCopy.HalfDuplexCall = func(TestService_HalfDuplexCallServer) error {
return status.Errorf(codes.Unimplemented, "method HalfDuplexCall not implemented")
}
}
sd := grpc.ServiceDesc{
ServiceName: "grpc.testing.TestService",
Methods: []grpc.MethodDesc{
{
MethodName: "EmptyCall",
Handler: srvCopy.emptyCall,
},
{
MethodName: "UnaryCall",
Handler: srvCopy.unaryCall,
},
}, },
Streams: []grpc.StreamDesc{ {
{ MethodName: "UnaryCall",
StreamName: "StreamingOutputCall", Handler: _TestService_UnaryCall_Handler,
Handler: srvCopy.streamingOutputCall,
ServerStreams: true,
},
{
StreamName: "StreamingInputCall",
Handler: srvCopy.streamingInputCall,
ClientStreams: true,
},
{
StreamName: "FullDuplexCall",
Handler: srvCopy.fullDuplexCall,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "HalfDuplexCall",
Handler: srvCopy.halfDuplexCall,
ServerStreams: true,
ClientStreams: true,
},
}, },
Metadata: "test/grpc_testing/test.proto", },
} Streams: []grpc.StreamDesc{
{
s.RegisterService(&sd, nil) StreamName: "StreamingOutputCall",
Handler: _TestService_StreamingOutputCall_Handler,
ServerStreams: true,
},
{
StreamName: "StreamingInputCall",
Handler: _TestService_StreamingInputCall_Handler,
ClientStreams: true,
},
{
StreamName: "FullDuplexCall",
Handler: _TestService_FullDuplexCall_Handler,
ServerStreams: true,
ClientStreams: true,
},
{
StreamName: "HalfDuplexCall",
Handler: _TestService_HalfDuplexCall_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "test/grpc_testing/test.proto",
} }

View File

@ -140,7 +140,7 @@ func setupServer(sc *svrConfig) (s *grpc.Server, lis net.Listener, ts *testHealt
ts = newTestHealthServer() ts = newTestHealthServer()
} }
healthgrpc.RegisterHealthServer(s, ts) healthgrpc.RegisterHealthServer(s, ts)
testpb.RegisterTestServiceService(s, testServer{}.Svc()) testpb.RegisterTestServiceServer(s, &testServer{})
go s.Serve(lis) go s.Serve(lis)
return s, lis, ts, s.Stop, nil return s, lis, ts, s.Stop, nil
} }

View File

@ -64,7 +64,7 @@ func testLocalCredsE2ESucceed(network, address string) error {
s := grpc.NewServer(sopts...) s := grpc.NewServer(sopts...)
defer s.Stop() defer s.Stop()
testpb.RegisterTestServiceService(s, ss.Svc()) testpb.RegisterTestServiceServer(s, ss)
lis, err := net.Listen(network, address) lis, err := net.Listen(network, address)
if err != nil { if err != nil {
@ -162,7 +162,7 @@ func testLocalCredsE2EFail(dopts []grpc.DialOption) error {
s := grpc.NewServer(sopts...) s := grpc.NewServer(sopts...)
defer s.Stop() defer s.Stop()
testpb.RegisterTestServiceService(s, ss.Svc()) testpb.RegisterTestServiceServer(s, ss)
lis, err := net.Listen("tcp", "localhost:0") lis, err := net.Listen("tcp", "localhost:0")
if err != nil { if err != nil {