diff options
Diffstat (limited to 'vendor/google.golang.org/grpc')
152 files changed, 2525 insertions, 25486 deletions
diff --git a/vendor/google.golang.org/grpc/.github/ISSUE_TEMPLATE b/vendor/google.golang.org/grpc/.github/ISSUE_TEMPLATE deleted file mode 100644 index 642f85a16..000000000 --- a/vendor/google.golang.org/grpc/.github/ISSUE_TEMPLATE +++ /dev/null @@ -1,14 +0,0 @@ -Please answer these questions before submitting your issue. - -### What version of gRPC are you using? - -### What version of Go are you using (`go version`)? - -### What operating system (Linux, Windows, …) and version? - -### What did you do? -If possible, provide a recipe for reproducing the error. - -### What did you expect to see? - -### What did you see instead? diff --git a/vendor/google.golang.org/grpc/.travis.yml b/vendor/google.golang.org/grpc/.travis.yml index 22bf25004..13af5396d 100644 --- a/vendor/google.golang.org/grpc/.travis.yml +++ b/vendor/google.golang.org/grpc/.travis.yml @@ -1,6 +1,7 @@ language: go go: + - 1.6.x - 1.7.x - 1.8.x - 1.9.x @@ -8,13 +9,15 @@ go: matrix: include: - go: 1.9.x - env: ARCH=386 + env: RUN386=1 go_import_path: google.golang.org/grpc before_install: - - if [[ "$TRAVIS_GO_VERSION" = 1.9* && "$ARCH" != "386" ]]; then ./vet.sh -install || exit 1; fi + - if [[ "$TRAVIS_GO_VERSION" = 1.9* && "$GOARCH" != "386" ]]; then ./vet.sh -install || exit 1; fi script: - - if [[ "$TRAVIS_GO_VERSION" = 1.9* && "$ARCH" != "386" ]]; then ./vet.sh || exit 1; fi - - make test testrace + - if [[ -n "$RUN386" ]]; then export GOARCH=386; fi + - if [[ "$TRAVIS_GO_VERSION" = 1.9* && "$GOARCH" != "386" ]]; then ./vet.sh || exit 1; fi + - make test || exit 1 + - if [[ "$GOARCH" != "386" ]]; then make testrace; fi diff --git a/vendor/google.golang.org/grpc/Documentation/gomock-example.md b/vendor/google.golang.org/grpc/Documentation/gomock-example.md deleted file mode 100644 index 54743e897..000000000 --- a/vendor/google.golang.org/grpc/Documentation/gomock-example.md +++ /dev/null @@ -1,182 +0,0 @@ -# Mocking Service for gRPC - -[Example code unary RPC](https://github.com/grpc/grpc-go/tree/master/examples/helloworld/mock_helloworld) - -[Example code streaming RPC](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/mock_routeguide) - -## Why? - -To test client-side logic without the overhead of connecting to a real server. Mocking enables users to write light-weight unit tests to check functionalities on client-side without invoking RPC calls to a server. - -## Idea: Mock the client stub that connects to the server. - -We use Gomock to mock the client interface (in the generated code) and programmatically set its methods to expect and return pre-determined values. This enables users to write tests around the client logic and use this mocked stub while making RPC calls. - -## How to use Gomock? - -Documentation on Gomock can be found [here](https://github.com/golang/mock). -A quick reading of the documentation should enable users to follow the code below. - -Consider a gRPC service based on following proto file: - -```proto -//helloworld.proto - -package helloworld; - -message HelloRequest { - string name = 1; -} - -message HelloReply { - string name = 1; -} - -service Greeter { - rpc SayHello (HelloRequest) returns (HelloReply) {} -} -``` - -The generated file helloworld.pb.go will have a client interface for each service defined in the proto file. This interface will have methods corresponding to each rpc inside that service. - -```Go -type GreeterClient interface { - SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) -} -``` - -The generated code also contains a struct that implements this interface. - -```Go -type greeterClient struct { - cc *grpc.ClientConn -} -func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error){ - // ... - // gRPC specific code here - // ... -} -``` - -Along with this the generated code has a method to create an instance of this struct. -```Go -func NewGreeterClient(cc *grpc.ClientConn) GreeterClient -``` - -The user code uses this function to create an instance of the struct greeterClient which then can be used to make rpc calls to the server. -We will mock this interface GreeterClient and use an instance of that mock to make rpc calls. These calls instead of going to server will return pre-determined values. - -To create a mock we’ll use [mockgen](https://github.com/golang/mock#running-mockgen). -From the directory ``` examples/helloworld/ ``` run ``` mockgen google.golang.org/grpc/examples/helloworld/helloworld GreeterClient > mock_helloworld/hw_mock.go ``` - -Notice that in the above command we specify GreeterClient as the interface to be mocked. - -The user test code can import the package generated by mockgen along with library package gomock to write unit tests around client-side logic. -```Go -import "github.com/golang/mock/gomock" -import hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld" -``` - -An instance of the mocked interface can be created as: -```Go -mockGreeterClient := hwmock.NewMockGreeterClient(ctrl) -``` -This mocked object can be programmed to expect calls to its methods and return pre-determined values. For instance, we can program mockGreeterClient to expect a call to its method SayHello and return a HelloReply with message “Mocked RPC”. - -```Go -mockGreeterClient.EXPECT().SayHello( - gomock.Any(), // expect any value for first parameter - gomock.Any(), // expect any value for second parameter -).Return(&helloworld.HelloReply{Message: “Mocked RPC”}, nil) -``` - -gomock.Any() indicates that the parameter can have any value or type. We can indicate specific values for built-in types with gomock.Eq(). -However, if the test code needs to specify the parameter to have a proto message type, we can replace gomock.Any() with an instance of a struct that implements gomock.Matcher interface. - -```Go -type rpcMsg struct { - msg proto.Message -} - -func (r *rpcMsg) Matches(msg interface{}) bool { - m, ok := msg.(proto.Message) - if !ok { - return false - } - return proto.Equal(m, r.msg) -} - -func (r *rpcMsg) String() string { - return fmt.Sprintf("is %s", r.msg) -} - -... - -req := &helloworld.HelloRequest{Name: "unit_test"} -mockGreeterClient.EXPECT().SayHello( - gomock.Any(), - &rpcMsg{msg: req}, -).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil) -``` - -## Mock streaming RPCs: - -For our example we consider the case of bi-directional streaming RPCs. Concretely, we'll write a test for RouteChat function from the route guide example to demonstrate how to write mocks for streams. - -RouteChat is a bi-directional streaming RPC, which means calling RouteChat returns a stream that can __Send__ and __Recv__ messages to and from the server, respectively. We'll start by creating a mock of this stream interface returned by RouteChat and then we'll mock the client interface and set expectation on the method RouteChat to return our mocked stream. - -### Generating mocking code: -Like before we'll use [mockgen](https://github.com/golang/mock#running-mockgen). From the `examples/route_guide` directory run: `mockgen google.golang.org/grpc/examples/route_guide/routeguide RouteGuideClient,RouteGuide_RouteChatClient > mock_route_guide/rg_mock.go` - -Notice that we are mocking both client(`RouteGuideClient`) and stream(`RouteGuide_RouteChatClient`) interfaces here. - -This will create a file `rg_mock.go` under directory `mock_route_guide`. This file contins all the mocking code we need to write our test. - -In our test code, like before, we import the this mocking code along with the generated code - -```go -import ( - rgmock "google.golang.org/grpc/examples/route_guide/mock_routeguide" - rgpb "google.golang.org/grpc/examples/route_guide/routeguide" -) -``` - -Now conside a test that takes the RouteGuide client object as a parameter, makes a RouteChat rpc call and sends a message on the resulting stream. Furthermore, this test expects to see the same message to be received on the stream. - -```go -var msg = ... - -// Creates a RouteChat call and sends msg on it. -// Checks if the received message was equal to msg. -func testRouteChat(client rgb.RouteChatClient) error{ - ... -} -``` - -We can inject our mock in here by simply passing it as an argument to the method. - -Creating mock for stream interface: - -```go - stream := rgmock.NewMockRouteGuide_RouteChatClient(ctrl) -} -``` - -Setting Expectations: - -```go - stream.EXPECT().Send(gomock.Any()).Return(nil) - stream.EXPECT().Recv().Return(msg, nil) -``` - -Creating mock for client interface: - -```go - rgclient := rgmock.NewMockRouteGuideClient(ctrl) -``` - -Setting Expectations: - -```go - rgclient.EXPECT().RouteChat(gomock.Any()).Return(stream, nil) -``` diff --git a/vendor/google.golang.org/grpc/Documentation/grpc-auth-support.md b/vendor/google.golang.org/grpc/Documentation/grpc-auth-support.md deleted file mode 100644 index 1b6b14e9d..000000000 --- a/vendor/google.golang.org/grpc/Documentation/grpc-auth-support.md +++ /dev/null @@ -1,41 +0,0 @@ -# Authentication - -As outlined in the [gRPC authentication guide](https://grpc.io/docs/guides/auth.html) there are a number of different mechanisms for asserting identity between an client and server. We'll present some code-samples here demonstrating how to provide TLS support encryption and identity assertions as well as passing OAuth2 tokens to services that support it. - -# Enabling TLS on a gRPC client - -```Go -conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""))) -``` - -# Enabling TLS on a gRPC server - -```Go -creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) -if err != nil { - log.Fatalf("Failed to generate credentials %v", err) -} -lis, err := net.Listen("tcp", ":0") -server := grpc.NewServer(grpc.Creds(creds)) -... -server.Serve(lis) -``` - -# Authenticating with Google - -## Google Compute Engine (GCE) - -```Go -conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(oauth.NewComputeEngine())) -``` - -## JWT - -```Go -jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope) -if err != nil { - log.Fatalf("Failed to create JWT credentials: %v", err) -} -conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(jwtCreds)) -``` - diff --git a/vendor/google.golang.org/grpc/Documentation/grpc-metadata.md b/vendor/google.golang.org/grpc/Documentation/grpc-metadata.md deleted file mode 100644 index c9a88c689..000000000 --- a/vendor/google.golang.org/grpc/Documentation/grpc-metadata.md +++ /dev/null @@ -1,204 +0,0 @@ -# Metadata - -gRPC supports sending metadata between client and server. -This doc shows how to send and receive metadata in gRPC-go. - -## Background - -Four kinds of service method: - -- [Unary RPC](https://grpc.io/docs/guides/concepts.html#unary-rpc) -- [Server streaming RPC](https://grpc.io/docs/guides/concepts.html#server-streaming-rpc) -- [Client streaming RPC](https://grpc.io/docs/guides/concepts.html#client-streaming-rpc) -- [Bidirectional streaming RPC](https://grpc.io/docs/guides/concepts.html#bidirectional-streaming-rpc) - -And concept of [metadata](https://grpc.io/docs/guides/concepts.html#metadata). - -## Constructing metadata - -A metadata can be created using package [metadata](https://godoc.org/google.golang.org/grpc/metadata). -The type MD is actually a map from string to a list of strings: - -```go -type MD map[string][]string -``` - -Metadata can be read like a normal map. -Note that the value type of this map is `[]string`, -so that users can attach multiple values using a single key. - -### Creating a new metadata - -A metadata can be created from a `map[string]string` using function `New`: - -```go -md := metadata.New(map[string]string{"key1": "val1", "key2": "val2"}) -``` - -Another way is to use `Pairs`. -Values with the same key will be merged into a list: - -```go -md := metadata.Pairs( - "key1", "val1", - "key1", "val1-2", // "key1" will have map value []string{"val1", "val1-2"} - "key2", "val2", -) -``` - -__Note:__ all the keys will be automatically converted to lowercase, -so "key1" and "kEy1" will be the same key and their values will be merged into the same list. -This happens for both `New` and `Pairs`. - -### Storing binary data in metadata - -In metadata, keys are always strings. But values can be strings or binary data. -To store binary data value in metadata, simply add "-bin" suffix to the key. -The values with "-bin" suffixed keys will be encoded when creating the metadata: - -```go -md := metadata.Pairs( - "key", "string value", - "key-bin", string([]byte{96, 102}), // this binary data will be encoded (base64) before sending - // and will be decoded after being transferred. -) -``` - -## Retrieving metadata from context - -Metadata can be retrieved from context using `FromIncomingContext`: - -```go -func (s *server) SomeRPC(ctx context.Context, in *pb.SomeRequest) (*pb.SomeResponse, err) { - md, ok := metadata.FromIncomingContext(ctx) - // do something with metadata -} -``` - -## Sending and receiving metadata - client side - -[//]: # "TODO: uncomment next line after example source added" -[//]: # "Real metadata sending and receiving examples are available [here](TODO:example_dir)." - -### Sending metadata - -To send metadata to server, the client can wrap the metadata into a context using `NewOutgoingContext`, and make the RPC with this context: - -```go -md := metadata.Pairs("key", "val") - -// create a new context with this metadata -ctx := metadata.NewOutgoingContext(context.Background(), md) - -// make unary RPC -response, err := client.SomeRPC(ctx, someRequest) - -// or make streaming RPC -stream, err := client.SomeStreamingRPC(ctx) -``` - -To read this back from the context on the client (e.g. in an interceptor) before the RPC is sent, use `FromOutgoingContext`. - -### Receiving metadata - -Metadata that a client can receive includes header and trailer. - -#### Unary call - -Header and trailer sent along with a unary call can be retrieved using function [Header](https://godoc.org/google.golang.org/grpc#Header) and [Trailer](https://godoc.org/google.golang.org/grpc#Trailer) in [CallOption](https://godoc.org/google.golang.org/grpc#CallOption): - -```go -var header, trailer metadata.MD // variable to store header and trailer -r, err := client.SomeRPC( - ctx, - someRequest, - grpc.Header(&header), // will retrieve header - grpc.Trailer(&trailer), // will retrieve trailer -) - -// do something with header and trailer -``` - -#### Streaming call - -For streaming calls including: - -- Server streaming RPC -- Client streaming RPC -- Bidirectional streaming RPC - -Header and trailer can be retrieved from the returned stream using function `Header` and `Trailer` in interface [ClientStream](https://godoc.org/google.golang.org/grpc#ClientStream): - -```go -stream, err := client.SomeStreamingRPC(ctx) - -// retrieve header -header, err := stream.Header() - -// retrieve trailer -trailer := stream.Trailer() - -``` - -## Sending and receiving metadata - server side - -[//]: # "TODO: uncomment next line after example source added" -[//]: # "Real metadata sending and receiving examples are available [here](TODO:example_dir)." - -### Receiving metadata - -To read metadata sent by the client, the server needs to retrieve it from RPC context. -If it is a unary call, the RPC handler's context can be used. -For streaming calls, the server needs to get context from the stream. - -#### Unary call - -```go -func (s *server) SomeRPC(ctx context.Context, in *pb.someRequest) (*pb.someResponse, error) { - md, ok := metadata.FromIncomingContext(ctx) - // do something with metadata -} -``` - -#### Streaming call - -```go -func (s *server) SomeStreamingRPC(stream pb.Service_SomeStreamingRPCServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) // get context from stream - // do something with metadata -} -``` - -### Sending metadata - -#### Unary call - -To send header and trailer to client in unary call, the server can call [SendHeader](https://godoc.org/google.golang.org/grpc#SendHeader) and [SetTrailer](https://godoc.org/google.golang.org/grpc#SetTrailer) functions in module [grpc](https://godoc.org/google.golang.org/grpc). -These two functions take a context as the first parameter. -It should be the RPC handler's context or one derived from it: - -```go -func (s *server) SomeRPC(ctx context.Context, in *pb.someRequest) (*pb.someResponse, error) { - // create and send header - header := metadata.Pairs("header-key", "val") - grpc.SendHeader(ctx, header) - // create and set trailer - trailer := metadata.Pairs("trailer-key", "val") - grpc.SetTrailer(ctx, trailer) -} -``` - -#### Streaming call - -For streaming calls, header and trailer can be sent using function `SendHeader` and `SetTrailer` in interface [ServerStream](https://godoc.org/google.golang.org/grpc#ServerStream): - -```go -func (s *server) SomeStreamingRPC(stream pb.Service_SomeStreamingRPCServer) error { - // create and send header - header := metadata.Pairs("header-key", "val") - stream.SendHeader(header) - // create and set trailer - trailer := metadata.Pairs("trailer-key", "val") - stream.SetTrailer(trailer) -} -``` diff --git a/vendor/google.golang.org/grpc/Documentation/server-reflection-tutorial.md b/vendor/google.golang.org/grpc/Documentation/server-reflection-tutorial.md deleted file mode 100644 index ca8e30cb4..000000000 --- a/vendor/google.golang.org/grpc/Documentation/server-reflection-tutorial.md +++ /dev/null @@ -1,152 +0,0 @@ -# gRPC Server Reflection Tutorial - -gRPC Server Reflection provides information about publicly-accessible gRPC -services on a server, and assists clients at runtime to construct RPC -requests and responses without precompiled service information. It is used by -gRPC CLI, which can be used to introspect server protos and send/receive test -RPCs. - -## Enable Server Reflection - -gRPC-go Server Reflection is implemented in package [reflection](https://github.com/grpc/grpc-go/tree/master/reflection). To enable server reflection, you need to import this package and register reflection service on your gRPC server. - -For example, to enable server reflection in `example/helloworld`, we need to make the following changes: - -```diff ---- a/examples/helloworld/greeter_server/main.go -+++ b/examples/helloworld/greeter_server/main.go -@@ -40,6 +40,7 @@ import ( - "golang.org/x/net/context" - "google.golang.org/grpc" - pb "google.golang.org/grpc/examples/helloworld/helloworld" -+ "google.golang.org/grpc/reflection" - ) - - const ( -@@ -61,6 +62,8 @@ func main() { - } - s := grpc.NewServer() - pb.RegisterGreeterServer(s, &server{}) -+ // Register reflection service on gRPC server. -+ reflection.Register(s) - if err := s.Serve(lis); err != nil { - log.Fatalf("failed to serve: %v", err) - } -``` - -We have made this change in `example/helloworld`, and we will use it as an example to show the use of gRPC server reflection and gRPC CLI in this tutorial. - -## gRPC CLI - -After enabling Server Reflection in a server application, you can use gRPC CLI to check its services. -gRPC CLI is only available in c++. Instructions on how to use gRPC CLI can be found at [command_line_tool.md](https://github.com/grpc/grpc/blob/master/doc/command_line_tool.md). - -To build gRPC CLI: - -```sh -git clone https://github.com/grpc/grpc -cd grpc -make grpc_cli -cd bins/opt # grpc_cli is in directory bins/opt/ -``` - -## Use gRPC CLI to check services - -First, start the helloworld server in grpc-go directory: - -```sh -$ cd <grpc-go-directory> -$ go run examples/helloworld/greeter_server/main.go -``` - -Open a new terminal and make sure you are in the directory where grpc_cli lives: - -```sh -$ cd <grpc-cpp-dirctory>/bins/opt -``` - -### List services - -`grpc_cli ls` command lists services and methods exposed at a given port: - -- List all the services exposed at a given port - - ```sh - $ ./grpc_cli ls localhost:50051 - ``` - - output: - ```sh - helloworld.Greeter - grpc.reflection.v1alpha.ServerReflection - ``` - -- List one service with details - - `grpc_cli ls` command inspects a service given its full name (in the format of - \<package\>.\<service\>). It can print information with a long listing format - when `-l` flag is set. This flag can be used to get more details about a - service. - - ```sh - $ ./grpc_cli ls localhost:50051 helloworld.Greeter -l - ``` - - output: - ```sh - filename: helloworld.proto - package: helloworld; - service Greeter { - rpc SayHello(helloworld.HelloRequest) returns (helloworld.HelloReply) {} - } - - ``` - -### List methods - -- List one method with details - - `grpc_cli ls` command also inspects a method given its full name (in the - format of \<package\>.\<service\>.\<method\>). - - ```sh - $ ./grpc_cli ls localhost:50051 helloworld.Greeter.SayHello -l - ``` - - output: - ```sh - rpc SayHello(helloworld.HelloRequest) returns (helloworld.HelloReply) {} - ``` - -### Inspect message types - -We can use`grpc_cli type` command to inspect request/response types given the -full name of the type (in the format of \<package\>.\<type\>). - -- Get information about the request type - - ```sh - $ ./grpc_cli type localhost:50051 helloworld.HelloRequest - ``` - - output: - ```sh - message HelloRequest { - optional string name = 1[json_name = "name"]; - } - ``` - -### Call a remote method - -We can send RPCs to a server and get responses using `grpc_cli call` command. - -- Call a unary method - - ```sh - $ ./grpc_cli call localhost:50051 SayHello "name: 'gRPC CLI'" - ``` - - output: - ```sh - message: "Hello gRPC CLI" - ``` diff --git a/vendor/google.golang.org/grpc/Makefile b/vendor/google.golang.org/grpc/Makefile index 39606b564..c44534376 100644 --- a/vendor/google.golang.org/grpc/Makefile +++ b/vendor/google.golang.org/grpc/Makefile @@ -23,10 +23,10 @@ proto: go generate google.golang.org/grpc/... test: testdeps - go test -cpu 1,4 google.golang.org/grpc/... + go test -cpu 1,4 -timeout 5m google.golang.org/grpc/... testrace: testdeps - go test -race -cpu 1,4 google.golang.org/grpc/... + go test -race -cpu 1,4 -timeout 7m google.golang.org/grpc/... clean: go clean -i google.golang.org/grpc/... diff --git a/vendor/google.golang.org/grpc/README.md b/vendor/google.golang.org/grpc/README.md index 622a5dc3e..118327bb1 100644 --- a/vendor/google.golang.org/grpc/README.md +++ b/vendor/google.golang.org/grpc/README.md @@ -1,6 +1,6 @@ # gRPC-Go -[](https://travis-ci.org/grpc/grpc-go) [](https://godoc.org/google.golang.org/grpc) +[](https://travis-ci.org/grpc/grpc-go) [](https://godoc.org/google.golang.org/grpc) [](https://goreportcard.com/report/github.com/grpc/grpc-go) The Go implementation of [gRPC](https://grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start: Go](https://grpc.io/docs/quickstart/go.html) guide. @@ -16,7 +16,8 @@ $ go get -u google.golang.org/grpc Prerequisites ------------- -This requires Go 1.7 or later. +This requires Go 1.6 or later. Go 1.7 will be required as of the next gRPC-Go +release (1.8). Constraints ----------- diff --git a/vendor/google.golang.org/grpc/backoff.go b/vendor/google.golang.org/grpc/backoff.go index 090fbe87c..c40facce5 100644 --- a/vendor/google.golang.org/grpc/backoff.go +++ b/vendor/google.golang.org/grpc/backoff.go @@ -25,14 +25,12 @@ import ( // DefaultBackoffConfig uses values specified for backoff in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. -var ( - DefaultBackoffConfig = BackoffConfig{ - MaxDelay: 120 * time.Second, - baseDelay: 1.0 * time.Second, - factor: 1.6, - jitter: 0.2, - } -) +var DefaultBackoffConfig = BackoffConfig{ + MaxDelay: 120 * time.Second, + baseDelay: 1.0 * time.Second, + factor: 1.6, + jitter: 0.2, +} // backoffStrategy defines the methodology for backing off after a grpc // connection failure. diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index 84e10b630..cd2682f5f 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -33,8 +33,6 @@ import ( var ( // m is a map from name to balancer builder. m = make(map[string]Builder) - // defaultBuilder is the default balancer to use. - defaultBuilder Builder // TODO(bar) install pickfirst as default. ) // Register registers the balancer builder to the balancer map. @@ -44,13 +42,12 @@ func Register(b Builder) { } // Get returns the resolver builder registered with the given name. -// If no builder is register with the name, the default pickfirst will -// be used. +// If no builder is register with the name, nil will be returned. func Get(name string) Builder { if b, ok := m[name]; ok { return b } - return defaultBuilder + return nil } // SubConn represents a gRPC sub connection. @@ -161,7 +158,7 @@ type Picker interface { // If a SubConn is returned: // - If it is READY, gRPC will send the RPC on it; // - If it is not ready, or becomes not ready after it's returned, gRPC will block - // this call until a new picker is updated and will call pick on the new picker. + // until UpdateBalancerState() is called and will call pick on the new picker. // // If the returned error is not nil: // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState() diff --git a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go index 99e71cd39..9d2fbcd84 100644 --- a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go +++ b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go @@ -56,7 +56,7 @@ func (*rrBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balan } func (*rrBuilder) Name() string { - return "roundrobin" + return "round_robin" } type rrBalancer struct { diff --git a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go index 505ddaf9d..7f953ff00 100644 --- a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go +++ b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go @@ -16,7 +16,7 @@ * */ -package roundrobin +package roundrobin_test import ( "fmt" @@ -27,6 +27,7 @@ import ( "golang.org/x/net/context" "google.golang.org/grpc" + "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" _ "google.golang.org/grpc/grpclog/glogger" "google.golang.org/grpc/peer" @@ -36,6 +37,8 @@ import ( "google.golang.org/grpc/test/leakcheck" ) +var rr = balancer.Get("round_robin") + type testServer struct { testpb.TestServiceServer } @@ -99,7 +102,7 @@ func TestOneBackend(t *testing.T) { } defer test.cleanup() - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(newBuilder())) + cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(rr)) if err != nil { t.Fatalf("failed to dial: %v", err) } @@ -115,7 +118,7 @@ func TestOneBackend(t *testing.T) { r.NewAddress([]resolver.Address{{Addr: test.addresses[0]}}) // The second RPC should succeed. if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } } @@ -131,7 +134,7 @@ func TestBackendsRoundRobin(t *testing.T) { } defer test.cleanup() - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(newBuilder())) + cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(rr)) if err != nil { t.Fatalf("failed to dial: %v", err) } @@ -156,7 +159,7 @@ func TestBackendsRoundRobin(t *testing.T) { var connected bool for i := 0; i < 1000; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } if p.Addr.String() == test.addresses[si] { connected = true @@ -171,7 +174,7 @@ func TestBackendsRoundRobin(t *testing.T) { for i := 0; i < 3*backendCount; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } if p.Addr.String() != test.addresses[i%backendCount] { t.Fatalf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) @@ -190,7 +193,7 @@ func TestAddressesRemoved(t *testing.T) { } defer test.cleanup() - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(newBuilder())) + cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(rr)) if err != nil { t.Fatalf("failed to dial: %v", err) } @@ -206,7 +209,7 @@ func TestAddressesRemoved(t *testing.T) { r.NewAddress([]resolver.Address{{Addr: test.addresses[0]}}) // The second RPC should succeed. if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } r.NewAddress([]resolver.Address{}) @@ -232,7 +235,7 @@ func TestCloseWithPendingRPC(t *testing.T) { } defer test.cleanup() - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(newBuilder())) + cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(rr)) if err != nil { t.Fatalf("failed to dial: %v", err) } @@ -266,7 +269,7 @@ func TestNewAddressWhileBlocking(t *testing.T) { } defer test.cleanup() - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(newBuilder())) + cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(rr)) if err != nil { t.Fatalf("failed to dial: %v", err) } @@ -315,7 +318,7 @@ func TestOneServerDown(t *testing.T) { } defer test.cleanup() - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(newBuilder())) + cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(rr)) if err != nil { t.Fatalf("failed to dial: %v", err) } @@ -340,7 +343,7 @@ func TestOneServerDown(t *testing.T) { var connected bool for i := 0; i < 1000; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } if p.Addr.String() == test.addresses[si] { connected = true @@ -355,7 +358,7 @@ func TestOneServerDown(t *testing.T) { for i := 0; i < 3*backendCount; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } if p.Addr.String() != test.addresses[i%backendCount] { t.Fatalf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) @@ -369,7 +372,11 @@ func TestOneServerDown(t *testing.T) { var targetSeen int for i := 0; i < 1000; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Logf("EmptyCall() = _, %v, want _, <nil>", err) + // Due to a race, this RPC could possibly get the connection that + // was closing, and this RPC may fail. Keep trying when this + // happens. + continue } switch p.Addr.String() { case test.addresses[backendCount-1]: @@ -388,7 +395,7 @@ func TestOneServerDown(t *testing.T) { } for i := 0; i < 3*backendCount; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } if p.Addr.String() != test.addresses[i%backendCount] { t.Errorf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) @@ -408,7 +415,7 @@ func TestAllServersDown(t *testing.T) { } defer test.cleanup() - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(newBuilder())) + cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerBuilder(rr)) if err != nil { t.Fatalf("failed to dial: %v", err) } @@ -433,7 +440,7 @@ func TestAllServersDown(t *testing.T) { var connected bool for i := 0; i < 1000; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } if p.Addr.String() == test.addresses[si] { connected = true @@ -448,7 +455,7 @@ func TestAllServersDown(t *testing.T) { for i := 0; i < 3*backendCount; i++ { if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) + t.Fatalf("EmptyCall() = _, %v, want _, <nil>", err) } if p.Addr.String() != test.addresses[i%backendCount] { t.Fatalf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) diff --git a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go index e4a95fd5c..ebfee4a88 100644 --- a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go +++ b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go @@ -73,7 +73,7 @@ func (b *scStateUpdateBuffer) load() { } } -// get returns the channel that receives a recvMsg in the buffer. +// get returns the channel that the scStateUpdate will be sent to. // // Upon receiving, the caller should call load to send another // scStateChangeTuple onto the channel if there is any. @@ -96,6 +96,8 @@ type ccBalancerWrapper struct { stateChangeQueue *scStateUpdateBuffer resolverUpdateCh chan *resolverUpdate done chan struct{} + + subConns map[*acBalancerWrapper]struct{} } func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper { @@ -104,6 +106,7 @@ func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.Bui stateChangeQueue: newSCStateUpdateBuffer(), resolverUpdateCh: make(chan *resolverUpdate, 1), done: make(chan struct{}), + subConns: make(map[*acBalancerWrapper]struct{}), } go ccb.watcher() ccb.balancer = b.Build(ccb, bopts) @@ -117,8 +120,20 @@ func (ccb *ccBalancerWrapper) watcher() { select { case t := <-ccb.stateChangeQueue.get(): ccb.stateChangeQueue.load() + select { + case <-ccb.done: + ccb.balancer.Close() + return + default: + } ccb.balancer.HandleSubConnStateChange(t.sc, t.state) case t := <-ccb.resolverUpdateCh: + select { + case <-ccb.done: + ccb.balancer.Close() + return + default: + } ccb.balancer.HandleResolvedAddrs(t.addrs, t.err) case <-ccb.done: } @@ -126,6 +141,9 @@ func (ccb *ccBalancerWrapper) watcher() { select { case <-ccb.done: ccb.balancer.Close() + for acbw := range ccb.subConns { + ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) + } return default: } @@ -165,27 +183,28 @@ func (ccb *ccBalancerWrapper) handleResolvedAddrs(addrs []resolver.Address, err } func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - grpclog.Infof("ccBalancerWrapper: new subconn: %v", addrs) ac, err := ccb.cc.newAddrConn(addrs) if err != nil { return nil, err } acbw := &acBalancerWrapper{ac: ac} + acbw.ac.mu.Lock() ac.acbw = acbw + acbw.ac.mu.Unlock() + ccb.subConns[acbw] = struct{}{} return acbw, nil } func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) { - grpclog.Infof("ccBalancerWrapper: removing subconn") acbw, ok := sc.(*acBalancerWrapper) if !ok { return } + delete(ccb.subConns, acbw) ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) } func (ccb *ccBalancerWrapper) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - grpclog.Infof("ccBalancerWrapper: updating state and picker called by balancer: %v, %p", s, p) ccb.cc.csMgr.updateState(s) ccb.cc.blockingpicker.updatePicker(p) } @@ -202,7 +221,6 @@ type acBalancerWrapper struct { } func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { - grpclog.Infof("acBalancerWrapper: UpdateAddresses called with %v", addrs) acbw.mu.Lock() defer acbw.mu.Unlock() if !acbw.ac.tryUpdateAddrs(addrs) { @@ -228,9 +246,11 @@ func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { return } acbw.ac = ac + ac.mu.Lock() ac.acbw = acbw + ac.mu.Unlock() if acState != connectivity.Idle { - ac.connect(false) + ac.connect() } } } @@ -238,7 +258,7 @@ func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { func (acbw *acBalancerWrapper) Connect() { acbw.mu.Lock() defer acbw.mu.Unlock() - acbw.ac.connect(false) + acbw.ac.connect() } func (acbw *acBalancerWrapper) getAddrConn() *addrConn { diff --git a/vendor/google.golang.org/grpc/balancer_switching_test.go b/vendor/google.golang.org/grpc/balancer_switching_test.go new file mode 100644 index 000000000..92c196d38 --- /dev/null +++ b/vendor/google.golang.org/grpc/balancer_switching_test.go @@ -0,0 +1,133 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "fmt" + "math" + "testing" + "time" + + "golang.org/x/net/context" + _ "google.golang.org/grpc/grpclog/glogger" + "google.golang.org/grpc/resolver" + "google.golang.org/grpc/resolver/manual" + "google.golang.org/grpc/test/leakcheck" +) + +func checkPickFirst(cc *ClientConn, servers []*server) error { + var ( + req = "port" + reply string + err error + ) + connected := false + for i := 0; i < 1000; i++ { + if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); ErrorDesc(err) == servers[0].port { + if connected { + // connected is set to false if peer is not server[0]. So if + // connected is true here, this is the second time we saw + // server[0] in a row. Break because pickfirst is in effect. + break + } + connected = true + } else { + connected = false + } + time.Sleep(time.Millisecond) + } + if !connected { + return fmt.Errorf("pickfirst is not in effect after 1 second, EmptyCall() = _, %v, want _, %v", err, servers[0].port) + } + // The following RPCs should all succeed with the first server. + for i := 0; i < 3; i++ { + err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc) + if ErrorDesc(err) != servers[0].port { + return fmt.Errorf("Index %d: want peer %v, got peer %v", i, servers[0].port, err) + } + } + return nil +} + +func checkRoundRobin(cc *ClientConn, servers []*server) error { + var ( + req = "port" + reply string + err error + ) + + // Make sure connections to all servers are up. + for i := 0; i < 2; i++ { + // Do this check twice, otherwise the first RPC's transport may still be + // picked by the closing pickfirst balancer, and the test becomes flaky. + for _, s := range servers { + var up bool + for i := 0; i < 1000; i++ { + if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); ErrorDesc(err) == s.port { + up = true + break + } + time.Sleep(time.Millisecond) + } + if !up { + return fmt.Errorf("server %v is not up within 1 second", s.port) + } + } + } + + serverCount := len(servers) + for i := 0; i < 3*serverCount; i++ { + err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc) + if ErrorDesc(err) != servers[i%serverCount].port { + return fmt.Errorf("Index %d: want peer %v, got peer %v", i, servers[i%serverCount].port, err) + } + } + return nil +} + +func TestSwitchBalancer(t *testing.T) { + defer leakcheck.Check(t) + r, rcleanup := manual.GenerateAndRegisterManualResolver() + defer rcleanup() + + numServers := 2 + servers, _, scleanup := startServers(t, numServers, math.MaxInt32) + defer scleanup() + + cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) + if err != nil { + t.Fatalf("failed to dial: %v", err) + } + defer cc.Close() + r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) + // The default balancer is pickfirst. + if err := checkPickFirst(cc, servers); err != nil { + t.Fatalf("check pickfirst returned non-nil error: %v", err) + } + // Switch to roundrobin. + cc.handleServiceConfig(`{"loadBalancingPolicy": "round_robin"}`) + if err := checkRoundRobin(cc, servers); err != nil { + t.Fatalf("check roundrobin returned non-nil error: %v", err) + } + // Switch to pickfirst. + cc.handleServiceConfig(`{"loadBalancingPolicy": "pick_first"}`) + if err := checkPickFirst(cc, servers); err != nil { + t.Fatalf("check pickfirst returned non-nil error: %v", err) + } +} diff --git a/vendor/google.golang.org/grpc/balancer_test.go b/vendor/google.golang.org/grpc/balancer_test.go index 29dbe0a67..a1558f027 100644 --- a/vendor/google.golang.org/grpc/balancer_test.go +++ b/vendor/google.golang.org/grpc/balancer_test.go @@ -31,6 +31,10 @@ import ( _ "google.golang.org/grpc/grpclog/glogger" "google.golang.org/grpc/naming" "google.golang.org/grpc/test/leakcheck" + + // V1 balancer tests use passthrough resolver instead of dns. + // TODO(bar) remove this when removing v1 balaner entirely. + _ "google.golang.org/grpc/resolver/passthrough" ) type testWatcher struct { @@ -117,7 +121,7 @@ func TestNameDiscovery(t *testing.T) { numServers := 2 servers, r, cleanup := startServers(t, numServers, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -151,7 +155,7 @@ func TestEmptyAddrs(t *testing.T) { defer leakcheck.Check(t) servers, r, cleanup := startServers(t, 1, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -185,7 +189,7 @@ func TestRoundRobin(t *testing.T) { numServers := 3 servers, r, cleanup := startServers(t, numServers, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -230,7 +234,7 @@ func TestCloseWithPendingRPC(t *testing.T) { defer leakcheck.Check(t) servers, r, cleanup := startServers(t, 1, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -282,7 +286,7 @@ func TestGetOnWaitChannel(t *testing.T) { defer leakcheck.Check(t) servers, r, cleanup := startServers(t, 1, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -328,7 +332,7 @@ func TestOneServerDown(t *testing.T) { numServers := 2 servers, r, cleanup := startServers(t, numServers, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -381,7 +385,7 @@ func TestOneAddressRemoval(t *testing.T) { numServers := 2 servers, r, cleanup := startServers(t, numServers, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -439,7 +443,7 @@ func TestOneAddressRemoval(t *testing.T) { func checkServerUp(t *testing.T, currentServer *server) { req := "port" port := currentServer.port - cc, err := Dial("localhost:"+port, WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///localhost:"+port, WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -457,7 +461,7 @@ func TestPickFirstEmptyAddrs(t *testing.T) { defer leakcheck.Check(t) servers, r, cleanup := startServers(t, 1, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -489,7 +493,7 @@ func TestPickFirstCloseWithPendingRPC(t *testing.T) { defer leakcheck.Check(t) servers, r, cleanup := startServers(t, 1, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -543,7 +547,7 @@ func TestPickFirstOrderAllServerUp(t *testing.T) { numServers := 3 servers, r, cleanup := startServers(t, numServers, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -656,7 +660,7 @@ func TestPickFirstOrderOneServerDown(t *testing.T) { numServers := 3 servers, r, cleanup := startServers(t, numServers, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } @@ -747,7 +751,7 @@ func TestPickFirstOneAddressRemoval(t *testing.T) { numServers := 2 servers, r, cleanup := startServers(t, numServers, math.MaxUint32) defer cleanup() - cc, err := Dial("localhost:"+servers[0].port, WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) + cc, err := Dial("passthrough:///localhost:"+servers[0].port, WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) if err != nil { t.Fatalf("Failed to create ClientConn: %v", err) } diff --git a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go index 9d0616080..6cb39071c 100644 --- a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go +++ b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go @@ -19,6 +19,7 @@ package grpc import ( + "strings" "sync" "golang.org/x/net/context" @@ -34,20 +35,27 @@ type balancerWrapperBuilder struct { } func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { - bwb.b.Start(cc.Target(), BalancerConfig{ + targetAddr := cc.Target() + targetSplitted := strings.Split(targetAddr, ":///") + if len(targetSplitted) >= 2 { + targetAddr = targetSplitted[1] + } + + bwb.b.Start(targetAddr, BalancerConfig{ DialCreds: opts.DialCreds, Dialer: opts.Dialer, }) _, pickfirst := bwb.b.(*pickFirst) bw := &balancerWrapper{ - balancer: bwb.b, - pickfirst: pickfirst, - cc: cc, - startCh: make(chan struct{}), - conns: make(map[resolver.Address]balancer.SubConn), - connSt: make(map[balancer.SubConn]*scState), - csEvltr: &connectivityStateEvaluator{}, - state: connectivity.Idle, + balancer: bwb.b, + pickfirst: pickfirst, + cc: cc, + targetAddr: targetAddr, + startCh: make(chan struct{}), + conns: make(map[resolver.Address]balancer.SubConn), + connSt: make(map[balancer.SubConn]*scState), + csEvltr: &connectivityStateEvaluator{}, + state: connectivity.Idle, } cc.UpdateBalancerState(connectivity.Idle, bw) go bw.lbWatcher() @@ -68,7 +76,8 @@ type balancerWrapper struct { balancer Balancer // The v1 balancer. pickfirst bool - cc balancer.ClientConn + cc balancer.ClientConn + targetAddr string // Target without the scheme. // To aggregate the connectivity state. csEvltr *connectivityStateEvaluator @@ -88,12 +97,11 @@ type balancerWrapper struct { // connections accordingly. func (bw *balancerWrapper) lbWatcher() { <-bw.startCh - grpclog.Infof("balancerWrapper: is pickfirst: %v\n", bw.pickfirst) notifyCh := bw.balancer.Notify() if notifyCh == nil { // There's no resolver in the balancer. Connect directly. a := resolver.Address{ - Addr: bw.cc.Target(), + Addr: bw.targetAddr, Type: resolver.Backend, } sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) @@ -103,7 +111,7 @@ func (bw *balancerWrapper) lbWatcher() { bw.mu.Lock() bw.conns[a] = sc bw.connSt[sc] = &scState{ - addr: Address{Addr: bw.cc.Target()}, + addr: Address{Addr: bw.targetAddr}, s: connectivity.Idle, } bw.mu.Unlock() @@ -221,7 +229,6 @@ func (bw *balancerWrapper) lbWatcher() { } func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("balancerWrapper: handle subconn state change: %p, %v", sc, s) bw.mu.Lock() defer bw.mu.Unlock() scSt, ok := bw.connSt[sc] diff --git a/vendor/google.golang.org/grpc/benchmark/benchmain/main.go b/vendor/google.golang.org/grpc/benchmark/benchmain/main.go deleted file mode 100644 index 0cc1f25e6..000000000 --- a/vendor/google.golang.org/grpc/benchmark/benchmain/main.go +++ /dev/null @@ -1,499 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* -Package main provides benchmark with setting flags. - -An example to run some benchmarks with profiling enabled: - -go run benchmark/benchmain/main.go -benchtime=10s -workloads=all \ - -compression=on -maxConcurrentCalls=1 -trace=off \ - -reqSizeBytes=1,1048576 -respSizeBytes=1,1048576 -networkMode=Local \ - -cpuProfile=cpuProf -memProfile=memProf -memProfileRate=10000 -resultFile=result - -As a suggestion, when creating a branch, you can run this benchmark and save the result -file "-resultFile=basePerf", and later when you at the middle of the work or finish the -work, you can get the benchmark result and compare it with the base anytime. - -Assume there are two result files names as "basePerf" and "curPerf" created by adding --resultFile=basePerf and -resultFile=curPerf. - To format the curPerf, run: - go run benchmark/benchresult/main.go curPerf - To observe how the performance changes based on a base result, run: - go run benchmark/benchresult/main.go basePerf curPerf -*/ -package main - -import ( - "encoding/gob" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "os" - "reflect" - "runtime" - "runtime/pprof" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - bm "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/latency" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/grpclog" -) - -const ( - modeOn = "on" - modeOff = "off" - modeBoth = "both" -) - -var allCompressionModes = []string{modeOn, modeOff, modeBoth} -var allTraceModes = []string{modeOn, modeOff, modeBoth} - -const ( - workloadsUnary = "unary" - workloadsStreaming = "streaming" - workloadsAll = "all" -) - -var allWorkloads = []string{workloadsUnary, workloadsStreaming, workloadsAll} - -var ( - runMode = []bool{true, true} // {runUnary, runStream} - // When set the latency to 0 (no delay), the result is slower than the real result with no delay - // because latency simulation section has extra operations - ltc = []time.Duration{0, 40 * time.Millisecond} // if non-positive, no delay. - kbps = []int{0, 10240} // if non-positive, infinite - mtu = []int{0} // if non-positive, infinite - maxConcurrentCalls = []int{1, 8, 64, 512} - reqSizeBytes = []int{1, 1024, 1024 * 1024} - respSizeBytes = []int{1, 1024, 1024 * 1024} - enableTrace []bool - benchtime time.Duration - memProfile, cpuProfile string - memProfileRate int - enableCompressor []bool - networkMode string - benchmarkResultFile string - networks = map[string]latency.Network{ - "Local": latency.Local, - "LAN": latency.LAN, - "WAN": latency.WAN, - "Longhaul": latency.Longhaul, - } -) - -func unaryBenchmark(startTimer func(), stopTimer func(int32), benchFeatures stats.Features, benchtime time.Duration, s *stats.Stats) { - caller, close := makeFuncUnary(benchFeatures) - defer close() - runBenchmark(caller, startTimer, stopTimer, benchFeatures, benchtime, s) -} - -func streamBenchmark(startTimer func(), stopTimer func(int32), benchFeatures stats.Features, benchtime time.Duration, s *stats.Stats) { - caller, close := makeFuncStream(benchFeatures) - defer close() - runBenchmark(caller, startTimer, stopTimer, benchFeatures, benchtime, s) -} - -func makeFuncUnary(benchFeatures stats.Features) (func(int), func()) { - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - opts := []grpc.DialOption{} - sopts := []grpc.ServerOption{} - if benchFeatures.EnableCompressor { - sopts = append(sopts, - grpc.RPCCompressor(nopCompressor{}), - grpc.RPCDecompressor(nopDecompressor{}), - ) - opts = append(opts, - grpc.WithCompressor(nopCompressor{}), - grpc.WithDecompressor(nopDecompressor{}), - ) - } - sopts = append(sopts, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - opts = append(opts, grpc.WithDialer(func(address string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", address, timeout) - })) - opts = append(opts, grpc.WithInsecure()) - - target, stopper := bm.StartServer(bm.ServerInfo{Addr: "localhost:0", Type: "protobuf", Network: nw}, sopts...) - conn := bm.NewClientConn(target, opts...) - tc := testpb.NewBenchmarkServiceClient(conn) - return func(int) { - unaryCaller(tc, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - }, func() { - conn.Close() - stopper() - } -} - -func makeFuncStream(benchFeatures stats.Features) (func(int), func()) { - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - opts := []grpc.DialOption{} - sopts := []grpc.ServerOption{} - if benchFeatures.EnableCompressor { - sopts = append(sopts, - grpc.RPCCompressor(grpc.NewGZIPCompressor()), - grpc.RPCDecompressor(grpc.NewGZIPDecompressor()), - ) - opts = append(opts, - grpc.WithCompressor(grpc.NewGZIPCompressor()), - grpc.WithDecompressor(grpc.NewGZIPDecompressor()), - ) - } - sopts = append(sopts, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - opts = append(opts, grpc.WithDialer(func(address string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", address, timeout) - })) - opts = append(opts, grpc.WithInsecure()) - - target, stopper := bm.StartServer(bm.ServerInfo{Addr: "localhost:0", Type: "protobuf", Network: nw}, sopts...) - conn := bm.NewClientConn(target, opts...) - tc := testpb.NewBenchmarkServiceClient(conn) - streams := make([]testpb.BenchmarkService_StreamingCallClient, benchFeatures.MaxConcurrentCalls) - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - stream, err := tc.StreamingCall(context.Background()) - if err != nil { - grpclog.Fatalf("%v.StreamingCall(_) = _, %v", tc, err) - } - streams[i] = stream - } - return func(pos int) { - streamCaller(streams[pos], benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - }, func() { - conn.Close() - stopper() - } -} - -func unaryCaller(client testpb.BenchmarkServiceClient, reqSize, respSize int) { - if err := bm.DoUnaryCall(client, reqSize, respSize); err != nil { - grpclog.Fatalf("DoUnaryCall failed: %v", err) - } -} - -func streamCaller(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) { - if err := bm.DoStreamingRoundTrip(stream, reqSize, respSize); err != nil { - grpclog.Fatalf("DoStreamingRoundTrip failed: %v", err) - } -} - -func runBenchmark(caller func(int), startTimer func(), stopTimer func(int32), benchFeatures stats.Features, benchtime time.Duration, s *stats.Stats) { - // Warm up connection. - for i := 0; i < 10; i++ { - caller(0) - } - // Run benchmark. - startTimer() - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(benchFeatures.MaxConcurrentCalls) - bmEnd := time.Now().Add(benchtime) - var count int32 - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - go func(pos int) { - for { - t := time.Now() - if t.After(bmEnd) { - break - } - start := time.Now() - caller(pos) - elapse := time.Since(start) - atomic.AddInt32(&count, 1) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }(i) - } - wg.Wait() - stopTimer(count) -} - -// Initiate main function to get settings of features. -func init() { - var ( - workloads, traceMode, compressorMode, readLatency string - readKbps, readMtu, readMaxConcurrentCalls intSliceType - readReqSizeBytes, readRespSizeBytes intSliceType - ) - flag.StringVar(&workloads, "workloads", workloadsAll, - fmt.Sprintf("Workloads to execute - One of: %v", strings.Join(allWorkloads, ", "))) - flag.StringVar(&traceMode, "trace", modeOff, - fmt.Sprintf("Trace mode - One of: %v", strings.Join(allTraceModes, ", "))) - flag.StringVar(&readLatency, "latency", "", "Simulated one-way network latency - may be a comma-separated list") - flag.DurationVar(&benchtime, "benchtime", time.Second, "Configures the amount of time to run each benchmark") - flag.Var(&readKbps, "kbps", "Simulated network throughput (in kbps) - may be a comma-separated list") - flag.Var(&readMtu, "mtu", "Simulated network MTU (Maximum Transmission Unit) - may be a comma-separated list") - flag.Var(&readMaxConcurrentCalls, "maxConcurrentCalls", "Number of concurrent RPCs during benchmarks") - flag.Var(&readReqSizeBytes, "reqSizeBytes", "Request size in bytes - may be a comma-separated list") - flag.Var(&readRespSizeBytes, "respSizeBytes", "Response size in bytes - may be a comma-separated list") - flag.StringVar(&memProfile, "memProfile", "", "Enables memory profiling output to the filename provided.") - flag.IntVar(&memProfileRate, "memProfileRate", 512*1024, "Configures the memory profiling rate. \n"+ - "memProfile should be set before setting profile rate. To include every allocated block in the profile, "+ - "set MemProfileRate to 1. To turn off profiling entirely, set MemProfileRate to 0. 512 * 1024 by default.") - flag.StringVar(&cpuProfile, "cpuProfile", "", "Enables CPU profiling output to the filename provided") - flag.StringVar(&compressorMode, "compression", modeOff, - fmt.Sprintf("Compression mode - One of: %v", strings.Join(allCompressionModes, ", "))) - flag.StringVar(&benchmarkResultFile, "resultFile", "", "Save the benchmark result into a binary file") - flag.StringVar(&networkMode, "networkMode", "", "Network mode includes LAN, WAN, Local and Longhaul") - flag.Parse() - if flag.NArg() != 0 { - log.Fatal("Error: unparsed arguments: ", flag.Args()) - } - switch workloads { - case workloadsUnary: - runMode[0] = true - runMode[1] = false - case workloadsStreaming: - runMode[0] = false - runMode[1] = true - case workloadsAll: - runMode[0] = true - runMode[1] = true - default: - log.Fatalf("Unknown workloads setting: %v (want one of: %v)", - workloads, strings.Join(allWorkloads, ", ")) - } - enableCompressor = setMode(compressorMode) - enableTrace = setMode(traceMode) - // Time input formats as (time + unit). - readTimeFromInput(<c, readLatency) - readIntFromIntSlice(&kbps, readKbps) - readIntFromIntSlice(&mtu, readMtu) - readIntFromIntSlice(&maxConcurrentCalls, readMaxConcurrentCalls) - readIntFromIntSlice(&reqSizeBytes, readReqSizeBytes) - readIntFromIntSlice(&respSizeBytes, readRespSizeBytes) - // Re-write latency, kpbs and mtu if network mode is set. - if network, ok := networks[networkMode]; ok { - ltc = []time.Duration{network.Latency} - kbps = []int{network.Kbps} - mtu = []int{network.MTU} - } -} - -func setMode(name string) []bool { - switch name { - case modeOn: - return []bool{true} - case modeOff: - return []bool{false} - case modeBoth: - return []bool{false, true} - default: - log.Fatalf("Unknown %s setting: %v (want one of: %v)", - name, name, strings.Join(allCompressionModes, ", ")) - return []bool{} - } -} - -type intSliceType []int - -func (intSlice *intSliceType) String() string { - return fmt.Sprintf("%v", *intSlice) -} - -func (intSlice *intSliceType) Set(value string) error { - if len(*intSlice) > 0 { - return errors.New("interval flag already set") - } - for _, num := range strings.Split(value, ",") { - next, err := strconv.Atoi(num) - if err != nil { - return err - } - *intSlice = append(*intSlice, next) - } - return nil -} - -func readIntFromIntSlice(values *[]int, replace intSliceType) { - // If not set replace in the flag, just return to run the default settings. - if len(replace) == 0 { - return - } - *values = replace -} - -func readTimeFromInput(values *[]time.Duration, replace string) { - if strings.Compare(replace, "") != 0 { - *values = []time.Duration{} - for _, ltc := range strings.Split(replace, ",") { - duration, err := time.ParseDuration(ltc) - if err != nil { - log.Fatal(err.Error()) - } - *values = append(*values, duration) - } - } -} - -func main() { - before() - featuresPos := make([]int, 8) - // 0:enableTracing 1:ltc 2:kbps 3:mtu 4:maxC 5:reqSize 6:respSize - featuresNum := []int{len(enableTrace), len(ltc), len(kbps), len(mtu), - len(maxConcurrentCalls), len(reqSizeBytes), len(respSizeBytes), len(enableCompressor)} - initalPos := make([]int, len(featuresPos)) - s := stats.NewStats(10) - s.SortLatency() - var memStats runtime.MemStats - var results testing.BenchmarkResult - var startAllocs, startBytes uint64 - var startTime time.Time - start := true - var startTimer = func() { - runtime.ReadMemStats(&memStats) - startAllocs = memStats.Mallocs - startBytes = memStats.TotalAlloc - startTime = time.Now() - } - var stopTimer = func(count int32) { - runtime.ReadMemStats(&memStats) - results = testing.BenchmarkResult{N: int(count), T: time.Now().Sub(startTime), - Bytes: 0, MemAllocs: memStats.Mallocs - startAllocs, MemBytes: memStats.TotalAlloc - startBytes} - } - sharedPos := make([]bool, len(featuresPos)) - for i := 0; i < len(featuresPos); i++ { - if featuresNum[i] <= 1 { - sharedPos[i] = true - } - } - - // Run benchmarks - resultSlice := []stats.BenchResults{} - for !reflect.DeepEqual(featuresPos, initalPos) || start { - start = false - benchFeature := stats.Features{ - NetworkMode: networkMode, - EnableTrace: enableTrace[featuresPos[0]], - Latency: ltc[featuresPos[1]], - Kbps: kbps[featuresPos[2]], - Mtu: mtu[featuresPos[3]], - MaxConcurrentCalls: maxConcurrentCalls[featuresPos[4]], - ReqSizeBytes: reqSizeBytes[featuresPos[5]], - RespSizeBytes: respSizeBytes[featuresPos[6]], - EnableCompressor: enableCompressor[featuresPos[7]], - } - - grpc.EnableTracing = enableTrace[featuresPos[0]] - if runMode[0] { - unaryBenchmark(startTimer, stopTimer, benchFeature, benchtime, s) - s.SetBenchmarkResult("Unary", benchFeature, results.N, - results.AllocedBytesPerOp(), results.AllocsPerOp(), sharedPos) - fmt.Println(s.BenchString()) - fmt.Println(s.String()) - resultSlice = append(resultSlice, s.GetBenchmarkResults()) - s.Clear() - } - if runMode[1] { - streamBenchmark(startTimer, stopTimer, benchFeature, benchtime, s) - s.SetBenchmarkResult("Stream", benchFeature, results.N, - results.AllocedBytesPerOp(), results.AllocsPerOp(), sharedPos) - fmt.Println(s.BenchString()) - fmt.Println(s.String()) - resultSlice = append(resultSlice, s.GetBenchmarkResults()) - s.Clear() - } - bm.AddOne(featuresPos, featuresNum) - } - after(resultSlice) -} - -func before() { - if memProfile != "" { - runtime.MemProfileRate = memProfileRate - } - if cpuProfile != "" { - f, err := os.Create(cpuProfile) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: %s\n", err) - return - } - if err := pprof.StartCPUProfile(f); err != nil { - fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s\n", err) - f.Close() - return - } - } -} - -func after(data []stats.BenchResults) { - if cpuProfile != "" { - pprof.StopCPUProfile() // flushes profile to disk - } - if memProfile != "" { - f, err := os.Create(memProfile) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: %s\n", err) - os.Exit(2) - } - runtime.GC() // materialize all statistics - if err = pprof.WriteHeapProfile(f); err != nil { - fmt.Fprintf(os.Stderr, "testing: can't write heap profile %s: %s\n", memProfile, err) - os.Exit(2) - } - f.Close() - } - if benchmarkResultFile != "" { - f, err := os.Create(benchmarkResultFile) - if err != nil { - log.Fatalf("testing: can't write benchmark result %s: %s\n", benchmarkResultFile, err) - } - dataEncoder := gob.NewEncoder(f) - dataEncoder.Encode(data) - f.Close() - } -} - -// nopCompressor is a compressor that just copies data. -type nopCompressor struct{} - -func (nopCompressor) Do(w io.Writer, p []byte) error { - n, err := w.Write(p) - if err != nil { - return err - } - if n != len(p) { - return fmt.Errorf("nopCompressor.Write: wrote %v bytes; want %v", n, len(p)) - } - return nil -} - -func (nopCompressor) Type() string { return "nop" } - -// nopDecompressor is a decompressor that just copies data. -type nopDecompressor struct{} - -func (nopDecompressor) Do(r io.Reader) ([]byte, error) { return ioutil.ReadAll(r) } -func (nopDecompressor) Type() string { return "nop" } diff --git a/vendor/google.golang.org/grpc/benchmark/benchmark.go b/vendor/google.golang.org/grpc/benchmark/benchmark.go deleted file mode 100644 index f09fa4543..000000000 --- a/vendor/google.golang.org/grpc/benchmark/benchmark.go +++ /dev/null @@ -1,364 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc -I grpc_testing --go_out=plugins=grpc:grpc_testing grpc_testing/control.proto grpc_testing/messages.proto grpc_testing/payloads.proto grpc_testing/services.proto grpc_testing/stats.proto - -/* -Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks. -*/ -package benchmark - -import ( - "fmt" - "io" - "net" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/latency" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/grpclog" -) - -// AddOne add 1 to the features slice -func AddOne(features []int, featuresMaxPosition []int) { - for i := len(features) - 1; i >= 0; i-- { - features[i] = (features[i] + 1) - if features[i]/featuresMaxPosition[i] == 0 { - break - } - features[i] = features[i] % featuresMaxPosition[i] - } -} - -// Allows reuse of the same testpb.Payload object. -func setPayload(p *testpb.Payload, t testpb.PayloadType, size int) { - if size < 0 { - grpclog.Fatalf("Requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - grpclog.Fatalf("PayloadType UNCOMPRESSABLE is not supported") - default: - grpclog.Fatalf("Unsupported payload type: %d", t) - } - p.Type = t - p.Body = body - return -} - -func newPayload(t testpb.PayloadType, size int) *testpb.Payload { - p := new(testpb.Payload) - setPayload(p, t, size) - return p -} - -type testServer struct { -} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - return &testpb.SimpleResponse{ - Payload: newPayload(in.ResponseType, int(in.ResponseSize)), - }, nil -} - -func (s *testServer) StreamingCall(stream testpb.BenchmarkService_StreamingCallServer) error { - response := &testpb.SimpleResponse{ - Payload: new(testpb.Payload), - } - in := new(testpb.SimpleRequest) - for { - // use ServerStream directly to reuse the same testpb.SimpleRequest object - err := stream.(grpc.ServerStream).RecvMsg(in) - if err == io.EOF { - // read done. - return nil - } - if err != nil { - return err - } - setPayload(response.Payload, in.ResponseType, int(in.ResponseSize)) - if err := stream.Send(response); err != nil { - return err - } - } -} - -// byteBufServer is a gRPC server that sends and receives byte buffer. -// The purpose is to benchmark the gRPC performance without protobuf serialization/deserialization overhead. -type byteBufServer struct { - respSize int32 -} - -// 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. -func (s *byteBufServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - return &testpb.SimpleResponse{}, nil -} - -func (s *byteBufServer) StreamingCall(stream testpb.BenchmarkService_StreamingCallServer) error { - for { - var in []byte - err := stream.(grpc.ServerStream).RecvMsg(&in) - if err == io.EOF { - return nil - } - if err != nil { - return err - } - out := make([]byte, s.respSize) - if err := stream.(grpc.ServerStream).SendMsg(&out); err != nil { - return err - } - } -} - -// ServerInfo contains the information to create a gRPC benchmark server. -type ServerInfo struct { - // Addr is the address of the server. - Addr string - - // Type is the type of the server. - // It should be "protobuf" or "bytebuf". - Type string - - // Metadata is an optional configuration. - // For "protobuf", it's ignored. - // For "bytebuf", it should be an int representing response size. - Metadata interface{} - - // Network can simulate latency - Network *latency.Network -} - -// StartServer starts a gRPC server serving a benchmark service according to info. -// It returns its listen address and a function to stop the server. -func StartServer(info ServerInfo, opts ...grpc.ServerOption) (string, func()) { - lis, err := net.Listen("tcp", info.Addr) - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - nw := info.Network - if nw != nil { - lis = nw.Listener(lis) - } - opts = append(opts, grpc.WriteBufferSize(128*1024)) - opts = append(opts, grpc.ReadBufferSize(128*1024)) - s := grpc.NewServer(opts...) - switch info.Type { - case "protobuf": - testpb.RegisterBenchmarkServiceServer(s, &testServer{}) - case "bytebuf": - respSize, ok := info.Metadata.(int32) - if !ok { - grpclog.Fatalf("failed to StartServer, invalid metadata: %v, for Type: %v", info.Metadata, info.Type) - } - testpb.RegisterBenchmarkServiceServer(s, &byteBufServer{respSize: respSize}) - default: - grpclog.Fatalf("failed to StartServer, unknown Type: %v", info.Type) - } - go s.Serve(lis) - return lis.Addr().String(), func() { - s.Stop() - } -} - -// DoUnaryCall performs an unary RPC with given stub and request and response sizes. -func DoUnaryCall(tc testpb.BenchmarkServiceClient, reqSize, respSize int) error { - pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSize) - req := &testpb.SimpleRequest{ - ResponseType: pl.Type, - ResponseSize: int32(respSize), - Payload: pl, - } - if _, err := tc.UnaryCall(context.Background(), req); err != nil { - return fmt.Errorf("/BenchmarkService/UnaryCall(_, _) = _, %v, want _, <nil>", err) - } - return nil -} - -// DoStreamingRoundTrip performs a round trip for a single streaming rpc. -func DoStreamingRoundTrip(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) error { - pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSize) - req := &testpb.SimpleRequest{ - ResponseType: pl.Type, - ResponseSize: int32(respSize), - Payload: pl, - } - if err := stream.Send(req); err != nil { - return fmt.Errorf("/BenchmarkService/StreamingCall.Send(_) = %v, want <nil>", err) - } - if _, err := stream.Recv(); err != nil { - // EOF is a valid error here. - if err == io.EOF { - return nil - } - return fmt.Errorf("/BenchmarkService/StreamingCall.Recv(_) = %v, want <nil>", err) - } - return nil -} - -// DoByteBufStreamingRoundTrip performs a round trip for a single streaming rpc, using a custom codec for byte buffer. -func DoByteBufStreamingRoundTrip(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) error { - out := make([]byte, reqSize) - if err := stream.(grpc.ClientStream).SendMsg(&out); err != nil { - return fmt.Errorf("/BenchmarkService/StreamingCall.(ClientStream).SendMsg(_) = %v, want <nil>", err) - } - var in []byte - if err := stream.(grpc.ClientStream).RecvMsg(&in); err != nil { - // EOF is a valid error here. - if err == io.EOF { - return nil - } - return fmt.Errorf("/BenchmarkService/StreamingCall.(ClientStream).RecvMsg(_) = %v, want <nil>", err) - } - return nil -} - -// NewClientConn creates a gRPC client connection to addr. -func NewClientConn(addr string, opts ...grpc.DialOption) *grpc.ClientConn { - opts = append(opts, grpc.WithWriteBufferSize(128*1024)) - opts = append(opts, grpc.WithReadBufferSize(128*1024)) - conn, err := grpc.Dial(addr, opts...) - if err != nil { - grpclog.Fatalf("NewClientConn(%q) failed to create a ClientConn %v", addr, err) - } - return conn -} - -func runUnary(b *testing.B, benchFeatures stats.Features) { - s := stats.AddStats(b, 38) - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - target, stopper := StartServer(ServerInfo{Addr: "localhost:0", Type: "protobuf", Network: nw}, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - defer stopper() - conn := NewClientConn( - target, grpc.WithInsecure(), - grpc.WithDialer(func(address string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", address, timeout) - }), - ) - tc := testpb.NewBenchmarkServiceClient(conn) - - // Warm up connection. - for i := 0; i < 10; i++ { - unaryCaller(tc, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - } - ch := make(chan int, benchFeatures.MaxConcurrentCalls*4) - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(benchFeatures.MaxConcurrentCalls) - - // Distribute the b.N calls over maxConcurrentCalls workers. - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - go func() { - for range ch { - start := time.Now() - unaryCaller(tc, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - elapse := time.Since(start) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }() - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - ch <- i - } - close(ch) - wg.Wait() - b.StopTimer() - conn.Close() -} - -func runStream(b *testing.B, benchFeatures stats.Features) { - s := stats.AddStats(b, 38) - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - target, stopper := StartServer(ServerInfo{Addr: "localhost:0", Type: "protobuf", Network: nw}, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - defer stopper() - conn := NewClientConn( - target, grpc.WithInsecure(), - grpc.WithDialer(func(address string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", address, timeout) - }), - ) - tc := testpb.NewBenchmarkServiceClient(conn) - - // Warm up connection. - stream, err := tc.StreamingCall(context.Background()) - if err != nil { - b.Fatalf("%v.StreamingCall(_) = _, %v", tc, err) - } - for i := 0; i < 10; i++ { - streamCaller(stream, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - } - - ch := make(chan struct{}, benchFeatures.MaxConcurrentCalls*4) - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(benchFeatures.MaxConcurrentCalls) - - // Distribute the b.N calls over maxConcurrentCalls workers. - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - stream, err := tc.StreamingCall(context.Background()) - if err != nil { - b.Fatalf("%v.StreamingCall(_) = _, %v", tc, err) - } - go func() { - for range ch { - start := time.Now() - streamCaller(stream, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - elapse := time.Since(start) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }() - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - ch <- struct{}{} - } - close(ch) - wg.Wait() - b.StopTimer() - conn.Close() -} -func unaryCaller(client testpb.BenchmarkServiceClient, reqSize, respSize int) { - if err := DoUnaryCall(client, reqSize, respSize); err != nil { - grpclog.Fatalf("DoUnaryCall failed: %v", err) - } -} - -func streamCaller(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) { - if err := DoStreamingRoundTrip(stream, reqSize, respSize); err != nil { - grpclog.Fatalf("DoStreamingRoundTrip failed: %v", err) - } -} diff --git a/vendor/google.golang.org/grpc/benchmark/benchmark_test.go b/vendor/google.golang.org/grpc/benchmark/benchmark_test.go deleted file mode 100644 index 8dc7d3c55..000000000 --- a/vendor/google.golang.org/grpc/benchmark/benchmark_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package benchmark - -import ( - "fmt" - "os" - "reflect" - "testing" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark/stats" -) - -func BenchmarkClient(b *testing.B) { - enableTrace := []bool{true, false} // run both enable and disable by default - // When set the latency to 0 (no delay), the result is slower than the real result with no delay - // because latency simulation section has extra operations - latency := []time.Duration{0, 40 * time.Millisecond} // if non-positive, no delay. - kbps := []int{0, 10240} // if non-positive, infinite - mtu := []int{0} // if non-positive, infinite - maxConcurrentCalls := []int{1, 8, 64, 512} - reqSizeBytes := []int{1, 1024 * 1024} - respSizeBytes := []int{1, 1024 * 1024} - featuresCurPos := make([]int, 7) - - // 0:enableTracing 1:md 2:ltc 3:kbps 4:mtu 5:maxC 6:connCount 7:reqSize 8:respSize - featuresMaxPosition := []int{len(enableTrace), len(latency), len(kbps), len(mtu), len(maxConcurrentCalls), len(reqSizeBytes), len(respSizeBytes)} - initalPos := make([]int, len(featuresCurPos)) - - // run benchmarks - start := true - for !reflect.DeepEqual(featuresCurPos, initalPos) || start { - start = false - tracing := "Trace" - if !enableTrace[featuresCurPos[0]] { - tracing = "noTrace" - } - - benchFeature := stats.Features{ - EnableTrace: enableTrace[featuresCurPos[0]], - Latency: latency[featuresCurPos[1]], - Kbps: kbps[featuresCurPos[2]], - Mtu: mtu[featuresCurPos[3]], - MaxConcurrentCalls: maxConcurrentCalls[featuresCurPos[4]], - ReqSizeBytes: reqSizeBytes[featuresCurPos[5]], - RespSizeBytes: respSizeBytes[featuresCurPos[6]], - } - - grpc.EnableTracing = enableTrace[featuresCurPos[0]] - b.Run(fmt.Sprintf("Unary-%s-%s", - tracing, benchFeature.String()), func(b *testing.B) { - runUnary(b, benchFeature) - }) - - b.Run(fmt.Sprintf("Stream-%s-%s", - tracing, benchFeature.String()), func(b *testing.B) { - runStream(b, benchFeature) - }) - AddOne(featuresCurPos, featuresMaxPosition) - } -} - -func TestMain(m *testing.M) { - os.Exit(stats.RunTestMain(m)) -} diff --git a/vendor/google.golang.org/grpc/benchmark/benchresult/main.go b/vendor/google.golang.org/grpc/benchmark/benchresult/main.go deleted file mode 100644 index 40226cff1..000000000 --- a/vendor/google.golang.org/grpc/benchmark/benchresult/main.go +++ /dev/null @@ -1,133 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* -To format the benchmark result: - go run benchmark/benchresult/main.go resultfile - -To see the performance change based on a old result: - go run benchmark/benchresult/main.go resultfile_old resultfile -It will print the comparison result of intersection benchmarks between two files. - -*/ -package main - -import ( - "encoding/gob" - "fmt" - "log" - "os" - "strconv" - "strings" - "time" - - "google.golang.org/grpc/benchmark/stats" -) - -func createMap(fileName string, m map[string]stats.BenchResults) { - f, err := os.Open(fileName) - if err != nil { - log.Fatalf("Read file %s error: %s\n", fileName, err) - } - defer f.Close() - var data []stats.BenchResults - decoder := gob.NewDecoder(f) - if err = decoder.Decode(&data); err != nil { - log.Fatalf("Decode file %s error: %s\n", fileName, err) - } - for _, d := range data { - m[d.RunMode+"-"+d.Features.String()] = d - } -} - -func intChange(title string, val1, val2 int64) string { - return fmt.Sprintf("%10s %12s %12s %8.2f%%\n", title, strconv.FormatInt(val1, 10), - strconv.FormatInt(val2, 10), float64(val2-val1)*100/float64(val1)) -} - -func timeChange(title int, val1, val2 time.Duration) string { - return fmt.Sprintf("%10s %12s %12s %8.2f%%\n", strconv.Itoa(title)+" latency", val1.String(), - val2.String(), float64(val2-val1)*100/float64(val1)) -} - -func compareTwoMap(m1, m2 map[string]stats.BenchResults) { - for k2, v2 := range m2 { - if v1, ok := m1[k2]; ok { - changes := k2 + "\n" - changes += fmt.Sprintf("%10s %12s %12s %8s\n", "Title", "Before", "After", "Percentage") - changes += intChange("Bytes/op", v1.AllocedBytesPerOp, v2.AllocedBytesPerOp) - changes += intChange("Allocs/op", v1.AllocsPerOp, v2.AllocsPerOp) - changes += timeChange(v1.Latency[1].Percent, v1.Latency[1].Value, v2.Latency[1].Value) - changes += timeChange(v1.Latency[2].Percent, v1.Latency[2].Value, v2.Latency[2].Value) - fmt.Printf("%s\n", changes) - } - } -} - -func compareBenchmark(file1, file2 string) { - var BenchValueFile1 map[string]stats.BenchResults - var BenchValueFile2 map[string]stats.BenchResults - BenchValueFile1 = make(map[string]stats.BenchResults) - BenchValueFile2 = make(map[string]stats.BenchResults) - - createMap(file1, BenchValueFile1) - createMap(file2, BenchValueFile2) - - compareTwoMap(BenchValueFile1, BenchValueFile2) -} - -func printline(benchName, ltc50, ltc90, allocByte, allocsOp interface{}) { - fmt.Printf("%-80v%12v%12v%12v%12v\n", benchName, ltc50, ltc90, allocByte, allocsOp) -} - -func formatBenchmark(fileName string) { - f, err := os.Open(fileName) - if err != nil { - log.Fatalf("Read file %s error: %s\n", fileName, err) - } - defer f.Close() - var data []stats.BenchResults - decoder := gob.NewDecoder(f) - if err = decoder.Decode(&data); err != nil { - log.Fatalf("Decode file %s error: %s\n", fileName, err) - } - if len(data) == 0 { - log.Fatalf("No data in file %s\n", fileName) - } - printPos := data[0].SharedPosion - fmt.Println("\nShared features:\n" + strings.Repeat("-", 20)) - fmt.Print(stats.PartialPrintString(printPos, data[0].Features, true)) - fmt.Println(strings.Repeat("-", 35)) - for i := 0; i < len(data[0].SharedPosion); i++ { - printPos[i] = !printPos[i] - } - printline("Name", "latency-50", "latency-90", "Alloc (B)", "Alloc (#)") - for _, d := range data { - name := d.RunMode + stats.PartialPrintString(printPos, d.Features, false) - printline(name, d.Latency[1].Value.String(), d.Latency[2].Value.String(), - d.AllocedBytesPerOp, d.AllocsPerOp) - } -} - -func main() { - if len(os.Args) == 2 { - formatBenchmark(os.Args[1]) - } else { - compareBenchmark(os.Args[1], os.Args[2]) - } -} diff --git a/vendor/google.golang.org/grpc/benchmark/client/main.go b/vendor/google.golang.org/grpc/benchmark/client/main.go deleted file mode 100644 index 9aa587e3a..000000000 --- a/vendor/google.golang.org/grpc/benchmark/client/main.go +++ /dev/null @@ -1,180 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "math" - "net" - "net/http" - _ "net/http/pprof" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/grpclog" -) - -var ( - server = flag.String("server", "", "The server address") - maxConcurrentRPCs = flag.Int("max_concurrent_rpcs", 1, "The max number of concurrent RPCs") - duration = flag.Int("duration", math.MaxInt32, "The duration in seconds to run the benchmark client") - trace = flag.Bool("trace", true, "Whether tracing is on") - rpcType = flag.Int("rpc_type", 0, - `Configure different client rpc type. Valid options are: - 0 : unary call; - 1 : streaming call.`) -) - -func unaryCaller(client testpb.BenchmarkServiceClient) { - benchmark.DoUnaryCall(client, 1, 1) -} - -func streamCaller(stream testpb.BenchmarkService_StreamingCallClient) { - benchmark.DoStreamingRoundTrip(stream, 1, 1) -} - -func buildConnection() (s *stats.Stats, conn *grpc.ClientConn, tc testpb.BenchmarkServiceClient) { - s = stats.NewStats(256) - conn = benchmark.NewClientConn(*server) - tc = testpb.NewBenchmarkServiceClient(conn) - return s, conn, tc -} - -func closeLoopUnary() { - s, conn, tc := buildConnection() - - for i := 0; i < 100; i++ { - unaryCaller(tc) - } - ch := make(chan int, *maxConcurrentRPCs*4) - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(*maxConcurrentRPCs) - - for i := 0; i < *maxConcurrentRPCs; i++ { - go func() { - for range ch { - start := time.Now() - unaryCaller(tc) - elapse := time.Since(start) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }() - } - // Stop the client when time is up. - done := make(chan struct{}) - go func() { - <-time.After(time.Duration(*duration) * time.Second) - close(done) - }() - ok := true - for ok { - select { - case ch <- 0: - case <-done: - ok = false - } - } - close(ch) - wg.Wait() - conn.Close() - grpclog.Println(s.String()) - -} - -func closeLoopStream() { - s, conn, tc := buildConnection() - ch := make(chan int, *maxConcurrentRPCs*4) - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(*maxConcurrentRPCs) - // Distribute RPCs over maxConcurrentCalls workers. - for i := 0; i < *maxConcurrentRPCs; i++ { - go func() { - stream, err := tc.StreamingCall(context.Background()) - if err != nil { - grpclog.Fatalf("%v.StreamingCall(_) = _, %v", tc, err) - } - // Do some warm up. - for i := 0; i < 100; i++ { - streamCaller(stream) - } - for range ch { - start := time.Now() - streamCaller(stream) - elapse := time.Since(start) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }() - } - // Stop the client when time is up. - done := make(chan struct{}) - go func() { - <-time.After(time.Duration(*duration) * time.Second) - close(done) - }() - ok := true - for ok { - select { - case ch <- 0: - case <-done: - ok = false - } - } - close(ch) - wg.Wait() - conn.Close() - grpclog.Println(s.String()) -} - -func main() { - flag.Parse() - grpc.EnableTracing = *trace - go func() { - lis, err := net.Listen("tcp", ":0") - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - grpclog.Println("Client profiling address: ", lis.Addr().String()) - if err := http.Serve(lis, nil); err != nil { - grpclog.Fatalf("Failed to serve: %v", err) - } - }() - switch *rpcType { - case 0: - closeLoopUnary() - case 1: - closeLoopStream() - } -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/control.pb.go b/vendor/google.golang.org/grpc/benchmark/grpc_testing/control.pb.go deleted file mode 100644 index b88832f75..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/control.pb.go +++ /dev/null @@ -1,1194 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: control.proto - -/* -Package grpc_testing is a generated protocol buffer package. - -It is generated from these files: - control.proto - messages.proto - payloads.proto - services.proto - stats.proto - -It has these top-level messages: - PoissonParams - UniformParams - DeterministicParams - ParetoParams - ClosedLoopParams - LoadParams - SecurityParams - ClientConfig - ClientStatus - Mark - ClientArgs - ServerConfig - ServerArgs - ServerStatus - CoreRequest - CoreResponse - Void - Scenario - Scenarios - Payload - EchoStatus - SimpleRequest - SimpleResponse - StreamingInputCallRequest - StreamingInputCallResponse - ResponseParameters - StreamingOutputCallRequest - StreamingOutputCallResponse - ReconnectParams - ReconnectInfo - ByteBufferParams - SimpleProtoParams - ComplexProtoParams - PayloadConfig - ServerStats - HistogramParams - HistogramData - ClientStats -*/ -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ClientType int32 - -const ( - ClientType_SYNC_CLIENT ClientType = 0 - ClientType_ASYNC_CLIENT ClientType = 1 -) - -var ClientType_name = map[int32]string{ - 0: "SYNC_CLIENT", - 1: "ASYNC_CLIENT", -} -var ClientType_value = map[string]int32{ - "SYNC_CLIENT": 0, - "ASYNC_CLIENT": 1, -} - -func (x ClientType) String() string { - return proto.EnumName(ClientType_name, int32(x)) -} -func (ClientType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -type ServerType int32 - -const ( - ServerType_SYNC_SERVER ServerType = 0 - ServerType_ASYNC_SERVER ServerType = 1 - ServerType_ASYNC_GENERIC_SERVER ServerType = 2 -) - -var ServerType_name = map[int32]string{ - 0: "SYNC_SERVER", - 1: "ASYNC_SERVER", - 2: "ASYNC_GENERIC_SERVER", -} -var ServerType_value = map[string]int32{ - "SYNC_SERVER": 0, - "ASYNC_SERVER": 1, - "ASYNC_GENERIC_SERVER": 2, -} - -func (x ServerType) String() string { - return proto.EnumName(ServerType_name, int32(x)) -} -func (ServerType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -type RpcType int32 - -const ( - RpcType_UNARY RpcType = 0 - RpcType_STREAMING RpcType = 1 -) - -var RpcType_name = map[int32]string{ - 0: "UNARY", - 1: "STREAMING", -} -var RpcType_value = map[string]int32{ - "UNARY": 0, - "STREAMING": 1, -} - -func (x RpcType) String() string { - return proto.EnumName(RpcType_name, int32(x)) -} -func (RpcType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -// Parameters of poisson process distribution, which is a good representation -// of activity coming in from independent identical stationary sources. -type PoissonParams struct { - // The rate of arrivals (a.k.a. lambda parameter of the exp distribution). - OfferedLoad float64 `protobuf:"fixed64,1,opt,name=offered_load,json=offeredLoad" json:"offered_load,omitempty"` -} - -func (m *PoissonParams) Reset() { *m = PoissonParams{} } -func (m *PoissonParams) String() string { return proto.CompactTextString(m) } -func (*PoissonParams) ProtoMessage() {} -func (*PoissonParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *PoissonParams) GetOfferedLoad() float64 { - if m != nil { - return m.OfferedLoad - } - return 0 -} - -type UniformParams struct { - InterarrivalLo float64 `protobuf:"fixed64,1,opt,name=interarrival_lo,json=interarrivalLo" json:"interarrival_lo,omitempty"` - InterarrivalHi float64 `protobuf:"fixed64,2,opt,name=interarrival_hi,json=interarrivalHi" json:"interarrival_hi,omitempty"` -} - -func (m *UniformParams) Reset() { *m = UniformParams{} } -func (m *UniformParams) String() string { return proto.CompactTextString(m) } -func (*UniformParams) ProtoMessage() {} -func (*UniformParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *UniformParams) GetInterarrivalLo() float64 { - if m != nil { - return m.InterarrivalLo - } - return 0 -} - -func (m *UniformParams) GetInterarrivalHi() float64 { - if m != nil { - return m.InterarrivalHi - } - return 0 -} - -type DeterministicParams struct { - OfferedLoad float64 `protobuf:"fixed64,1,opt,name=offered_load,json=offeredLoad" json:"offered_load,omitempty"` -} - -func (m *DeterministicParams) Reset() { *m = DeterministicParams{} } -func (m *DeterministicParams) String() string { return proto.CompactTextString(m) } -func (*DeterministicParams) ProtoMessage() {} -func (*DeterministicParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *DeterministicParams) GetOfferedLoad() float64 { - if m != nil { - return m.OfferedLoad - } - return 0 -} - -type ParetoParams struct { - InterarrivalBase float64 `protobuf:"fixed64,1,opt,name=interarrival_base,json=interarrivalBase" json:"interarrival_base,omitempty"` - Alpha float64 `protobuf:"fixed64,2,opt,name=alpha" json:"alpha,omitempty"` -} - -func (m *ParetoParams) Reset() { *m = ParetoParams{} } -func (m *ParetoParams) String() string { return proto.CompactTextString(m) } -func (*ParetoParams) ProtoMessage() {} -func (*ParetoParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *ParetoParams) GetInterarrivalBase() float64 { - if m != nil { - return m.InterarrivalBase - } - return 0 -} - -func (m *ParetoParams) GetAlpha() float64 { - if m != nil { - return m.Alpha - } - return 0 -} - -// Once an RPC finishes, immediately start a new one. -// No configuration parameters needed. -type ClosedLoopParams struct { -} - -func (m *ClosedLoopParams) Reset() { *m = ClosedLoopParams{} } -func (m *ClosedLoopParams) String() string { return proto.CompactTextString(m) } -func (*ClosedLoopParams) ProtoMessage() {} -func (*ClosedLoopParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -type LoadParams struct { - // Types that are valid to be assigned to Load: - // *LoadParams_ClosedLoop - // *LoadParams_Poisson - // *LoadParams_Uniform - // *LoadParams_Determ - // *LoadParams_Pareto - Load isLoadParams_Load `protobuf_oneof:"load"` -} - -func (m *LoadParams) Reset() { *m = LoadParams{} } -func (m *LoadParams) String() string { return proto.CompactTextString(m) } -func (*LoadParams) ProtoMessage() {} -func (*LoadParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } - -type isLoadParams_Load interface { - isLoadParams_Load() -} - -type LoadParams_ClosedLoop struct { - ClosedLoop *ClosedLoopParams `protobuf:"bytes,1,opt,name=closed_loop,json=closedLoop,oneof"` -} -type LoadParams_Poisson struct { - Poisson *PoissonParams `protobuf:"bytes,2,opt,name=poisson,oneof"` -} -type LoadParams_Uniform struct { - Uniform *UniformParams `protobuf:"bytes,3,opt,name=uniform,oneof"` -} -type LoadParams_Determ struct { - Determ *DeterministicParams `protobuf:"bytes,4,opt,name=determ,oneof"` -} -type LoadParams_Pareto struct { - Pareto *ParetoParams `protobuf:"bytes,5,opt,name=pareto,oneof"` -} - -func (*LoadParams_ClosedLoop) isLoadParams_Load() {} -func (*LoadParams_Poisson) isLoadParams_Load() {} -func (*LoadParams_Uniform) isLoadParams_Load() {} -func (*LoadParams_Determ) isLoadParams_Load() {} -func (*LoadParams_Pareto) isLoadParams_Load() {} - -func (m *LoadParams) GetLoad() isLoadParams_Load { - if m != nil { - return m.Load - } - return nil -} - -func (m *LoadParams) GetClosedLoop() *ClosedLoopParams { - if x, ok := m.GetLoad().(*LoadParams_ClosedLoop); ok { - return x.ClosedLoop - } - return nil -} - -func (m *LoadParams) GetPoisson() *PoissonParams { - if x, ok := m.GetLoad().(*LoadParams_Poisson); ok { - return x.Poisson - } - return nil -} - -func (m *LoadParams) GetUniform() *UniformParams { - if x, ok := m.GetLoad().(*LoadParams_Uniform); ok { - return x.Uniform - } - return nil -} - -func (m *LoadParams) GetDeterm() *DeterministicParams { - if x, ok := m.GetLoad().(*LoadParams_Determ); ok { - return x.Determ - } - return nil -} - -func (m *LoadParams) GetPareto() *ParetoParams { - if x, ok := m.GetLoad().(*LoadParams_Pareto); ok { - return x.Pareto - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadParams) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadParams_OneofMarshaler, _LoadParams_OneofUnmarshaler, _LoadParams_OneofSizer, []interface{}{ - (*LoadParams_ClosedLoop)(nil), - (*LoadParams_Poisson)(nil), - (*LoadParams_Uniform)(nil), - (*LoadParams_Determ)(nil), - (*LoadParams_Pareto)(nil), - } -} - -func _LoadParams_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadParams) - // load - switch x := m.Load.(type) { - case *LoadParams_ClosedLoop: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClosedLoop); err != nil { - return err - } - case *LoadParams_Poisson: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Poisson); err != nil { - return err - } - case *LoadParams_Uniform: - b.EncodeVarint(3<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Uniform); err != nil { - return err - } - case *LoadParams_Determ: - b.EncodeVarint(4<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Determ); err != nil { - return err - } - case *LoadParams_Pareto: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Pareto); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadParams.Load has unexpected type %T", x) - } - return nil -} - -func _LoadParams_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadParams) - switch tag { - case 1: // load.closed_loop - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClosedLoopParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_ClosedLoop{msg} - return true, err - case 2: // load.poisson - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(PoissonParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Poisson{msg} - return true, err - case 3: // load.uniform - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(UniformParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Uniform{msg} - return true, err - case 4: // load.determ - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(DeterministicParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Determ{msg} - return true, err - case 5: // load.pareto - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ParetoParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Pareto{msg} - return true, err - default: - return false, nil - } -} - -func _LoadParams_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadParams) - // load - switch x := m.Load.(type) { - case *LoadParams_ClosedLoop: - s := proto.Size(x.ClosedLoop) - n += proto.SizeVarint(1<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Poisson: - s := proto.Size(x.Poisson) - n += proto.SizeVarint(2<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Uniform: - s := proto.Size(x.Uniform) - n += proto.SizeVarint(3<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Determ: - s := proto.Size(x.Determ) - n += proto.SizeVarint(4<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Pareto: - s := proto.Size(x.Pareto) - n += proto.SizeVarint(5<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// presence of SecurityParams implies use of TLS -type SecurityParams struct { - UseTestCa bool `protobuf:"varint,1,opt,name=use_test_ca,json=useTestCa" json:"use_test_ca,omitempty"` - ServerHostOverride string `protobuf:"bytes,2,opt,name=server_host_override,json=serverHostOverride" json:"server_host_override,omitempty"` -} - -func (m *SecurityParams) Reset() { *m = SecurityParams{} } -func (m *SecurityParams) String() string { return proto.CompactTextString(m) } -func (*SecurityParams) ProtoMessage() {} -func (*SecurityParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } - -func (m *SecurityParams) GetUseTestCa() bool { - if m != nil { - return m.UseTestCa - } - return false -} - -func (m *SecurityParams) GetServerHostOverride() string { - if m != nil { - return m.ServerHostOverride - } - return "" -} - -type ClientConfig struct { - // List of targets to connect to. At least one target needs to be specified. - ServerTargets []string `protobuf:"bytes,1,rep,name=server_targets,json=serverTargets" json:"server_targets,omitempty"` - ClientType ClientType `protobuf:"varint,2,opt,name=client_type,json=clientType,enum=grpc.testing.ClientType" json:"client_type,omitempty"` - SecurityParams *SecurityParams `protobuf:"bytes,3,opt,name=security_params,json=securityParams" json:"security_params,omitempty"` - // How many concurrent RPCs to start for each channel. - // For synchronous client, use a separate thread for each outstanding RPC. - OutstandingRpcsPerChannel int32 `protobuf:"varint,4,opt,name=outstanding_rpcs_per_channel,json=outstandingRpcsPerChannel" json:"outstanding_rpcs_per_channel,omitempty"` - // Number of independent client channels to create. - // i-th channel will connect to server_target[i % server_targets.size()] - ClientChannels int32 `protobuf:"varint,5,opt,name=client_channels,json=clientChannels" json:"client_channels,omitempty"` - // Only for async client. Number of threads to use to start/manage RPCs. - AsyncClientThreads int32 `protobuf:"varint,7,opt,name=async_client_threads,json=asyncClientThreads" json:"async_client_threads,omitempty"` - RpcType RpcType `protobuf:"varint,8,opt,name=rpc_type,json=rpcType,enum=grpc.testing.RpcType" json:"rpc_type,omitempty"` - // The requested load for the entire client (aggregated over all the threads). - LoadParams *LoadParams `protobuf:"bytes,10,opt,name=load_params,json=loadParams" json:"load_params,omitempty"` - PayloadConfig *PayloadConfig `protobuf:"bytes,11,opt,name=payload_config,json=payloadConfig" json:"payload_config,omitempty"` - HistogramParams *HistogramParams `protobuf:"bytes,12,opt,name=histogram_params,json=histogramParams" json:"histogram_params,omitempty"` - // Specify the cores we should run the client on, if desired - CoreList []int32 `protobuf:"varint,13,rep,packed,name=core_list,json=coreList" json:"core_list,omitempty"` - CoreLimit int32 `protobuf:"varint,14,opt,name=core_limit,json=coreLimit" json:"core_limit,omitempty"` -} - -func (m *ClientConfig) Reset() { *m = ClientConfig{} } -func (m *ClientConfig) String() string { return proto.CompactTextString(m) } -func (*ClientConfig) ProtoMessage() {} -func (*ClientConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } - -func (m *ClientConfig) GetServerTargets() []string { - if m != nil { - return m.ServerTargets - } - return nil -} - -func (m *ClientConfig) GetClientType() ClientType { - if m != nil { - return m.ClientType - } - return ClientType_SYNC_CLIENT -} - -func (m *ClientConfig) GetSecurityParams() *SecurityParams { - if m != nil { - return m.SecurityParams - } - return nil -} - -func (m *ClientConfig) GetOutstandingRpcsPerChannel() int32 { - if m != nil { - return m.OutstandingRpcsPerChannel - } - return 0 -} - -func (m *ClientConfig) GetClientChannels() int32 { - if m != nil { - return m.ClientChannels - } - return 0 -} - -func (m *ClientConfig) GetAsyncClientThreads() int32 { - if m != nil { - return m.AsyncClientThreads - } - return 0 -} - -func (m *ClientConfig) GetRpcType() RpcType { - if m != nil { - return m.RpcType - } - return RpcType_UNARY -} - -func (m *ClientConfig) GetLoadParams() *LoadParams { - if m != nil { - return m.LoadParams - } - return nil -} - -func (m *ClientConfig) GetPayloadConfig() *PayloadConfig { - if m != nil { - return m.PayloadConfig - } - return nil -} - -func (m *ClientConfig) GetHistogramParams() *HistogramParams { - if m != nil { - return m.HistogramParams - } - return nil -} - -func (m *ClientConfig) GetCoreList() []int32 { - if m != nil { - return m.CoreList - } - return nil -} - -func (m *ClientConfig) GetCoreLimit() int32 { - if m != nil { - return m.CoreLimit - } - return 0 -} - -type ClientStatus struct { - Stats *ClientStats `protobuf:"bytes,1,opt,name=stats" json:"stats,omitempty"` -} - -func (m *ClientStatus) Reset() { *m = ClientStatus{} } -func (m *ClientStatus) String() string { return proto.CompactTextString(m) } -func (*ClientStatus) ProtoMessage() {} -func (*ClientStatus) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } - -func (m *ClientStatus) GetStats() *ClientStats { - if m != nil { - return m.Stats - } - return nil -} - -// Request current stats -type Mark struct { - // if true, the stats will be reset after taking their snapshot. - Reset_ bool `protobuf:"varint,1,opt,name=reset" json:"reset,omitempty"` -} - -func (m *Mark) Reset() { *m = Mark{} } -func (m *Mark) String() string { return proto.CompactTextString(m) } -func (*Mark) ProtoMessage() {} -func (*Mark) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } - -func (m *Mark) GetReset_() bool { - if m != nil { - return m.Reset_ - } - return false -} - -type ClientArgs struct { - // Types that are valid to be assigned to Argtype: - // *ClientArgs_Setup - // *ClientArgs_Mark - Argtype isClientArgs_Argtype `protobuf_oneof:"argtype"` -} - -func (m *ClientArgs) Reset() { *m = ClientArgs{} } -func (m *ClientArgs) String() string { return proto.CompactTextString(m) } -func (*ClientArgs) ProtoMessage() {} -func (*ClientArgs) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } - -type isClientArgs_Argtype interface { - isClientArgs_Argtype() -} - -type ClientArgs_Setup struct { - Setup *ClientConfig `protobuf:"bytes,1,opt,name=setup,oneof"` -} -type ClientArgs_Mark struct { - Mark *Mark `protobuf:"bytes,2,opt,name=mark,oneof"` -} - -func (*ClientArgs_Setup) isClientArgs_Argtype() {} -func (*ClientArgs_Mark) isClientArgs_Argtype() {} - -func (m *ClientArgs) GetArgtype() isClientArgs_Argtype { - if m != nil { - return m.Argtype - } - return nil -} - -func (m *ClientArgs) GetSetup() *ClientConfig { - if x, ok := m.GetArgtype().(*ClientArgs_Setup); ok { - return x.Setup - } - return nil -} - -func (m *ClientArgs) GetMark() *Mark { - if x, ok := m.GetArgtype().(*ClientArgs_Mark); ok { - return x.Mark - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ClientArgs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ClientArgs_OneofMarshaler, _ClientArgs_OneofUnmarshaler, _ClientArgs_OneofSizer, []interface{}{ - (*ClientArgs_Setup)(nil), - (*ClientArgs_Mark)(nil), - } -} - -func _ClientArgs_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ClientArgs) - // argtype - switch x := m.Argtype.(type) { - case *ClientArgs_Setup: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Setup); err != nil { - return err - } - case *ClientArgs_Mark: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Mark); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ClientArgs.Argtype has unexpected type %T", x) - } - return nil -} - -func _ClientArgs_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ClientArgs) - switch tag { - case 1: // argtype.setup - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClientConfig) - err := b.DecodeMessage(msg) - m.Argtype = &ClientArgs_Setup{msg} - return true, err - case 2: // argtype.mark - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Mark) - err := b.DecodeMessage(msg) - m.Argtype = &ClientArgs_Mark{msg} - return true, err - default: - return false, nil - } -} - -func _ClientArgs_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ClientArgs) - // argtype - switch x := m.Argtype.(type) { - case *ClientArgs_Setup: - s := proto.Size(x.Setup) - n += proto.SizeVarint(1<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *ClientArgs_Mark: - s := proto.Size(x.Mark) - n += proto.SizeVarint(2<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type ServerConfig struct { - ServerType ServerType `protobuf:"varint,1,opt,name=server_type,json=serverType,enum=grpc.testing.ServerType" json:"server_type,omitempty"` - SecurityParams *SecurityParams `protobuf:"bytes,2,opt,name=security_params,json=securityParams" json:"security_params,omitempty"` - // Port on which to listen. Zero means pick unused port. - Port int32 `protobuf:"varint,4,opt,name=port" json:"port,omitempty"` - // Only for async server. Number of threads used to serve the requests. - AsyncServerThreads int32 `protobuf:"varint,7,opt,name=async_server_threads,json=asyncServerThreads" json:"async_server_threads,omitempty"` - // Specify the number of cores to limit server to, if desired - CoreLimit int32 `protobuf:"varint,8,opt,name=core_limit,json=coreLimit" json:"core_limit,omitempty"` - // payload config, used in generic server - PayloadConfig *PayloadConfig `protobuf:"bytes,9,opt,name=payload_config,json=payloadConfig" json:"payload_config,omitempty"` - // Specify the cores we should run the server on, if desired - CoreList []int32 `protobuf:"varint,10,rep,packed,name=core_list,json=coreList" json:"core_list,omitempty"` -} - -func (m *ServerConfig) Reset() { *m = ServerConfig{} } -func (m *ServerConfig) String() string { return proto.CompactTextString(m) } -func (*ServerConfig) ProtoMessage() {} -func (*ServerConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } - -func (m *ServerConfig) GetServerType() ServerType { - if m != nil { - return m.ServerType - } - return ServerType_SYNC_SERVER -} - -func (m *ServerConfig) GetSecurityParams() *SecurityParams { - if m != nil { - return m.SecurityParams - } - return nil -} - -func (m *ServerConfig) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *ServerConfig) GetAsyncServerThreads() int32 { - if m != nil { - return m.AsyncServerThreads - } - return 0 -} - -func (m *ServerConfig) GetCoreLimit() int32 { - if m != nil { - return m.CoreLimit - } - return 0 -} - -func (m *ServerConfig) GetPayloadConfig() *PayloadConfig { - if m != nil { - return m.PayloadConfig - } - return nil -} - -func (m *ServerConfig) GetCoreList() []int32 { - if m != nil { - return m.CoreList - } - return nil -} - -type ServerArgs struct { - // Types that are valid to be assigned to Argtype: - // *ServerArgs_Setup - // *ServerArgs_Mark - Argtype isServerArgs_Argtype `protobuf_oneof:"argtype"` -} - -func (m *ServerArgs) Reset() { *m = ServerArgs{} } -func (m *ServerArgs) String() string { return proto.CompactTextString(m) } -func (*ServerArgs) ProtoMessage() {} -func (*ServerArgs) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } - -type isServerArgs_Argtype interface { - isServerArgs_Argtype() -} - -type ServerArgs_Setup struct { - Setup *ServerConfig `protobuf:"bytes,1,opt,name=setup,oneof"` -} -type ServerArgs_Mark struct { - Mark *Mark `protobuf:"bytes,2,opt,name=mark,oneof"` -} - -func (*ServerArgs_Setup) isServerArgs_Argtype() {} -func (*ServerArgs_Mark) isServerArgs_Argtype() {} - -func (m *ServerArgs) GetArgtype() isServerArgs_Argtype { - if m != nil { - return m.Argtype - } - return nil -} - -func (m *ServerArgs) GetSetup() *ServerConfig { - if x, ok := m.GetArgtype().(*ServerArgs_Setup); ok { - return x.Setup - } - return nil -} - -func (m *ServerArgs) GetMark() *Mark { - if x, ok := m.GetArgtype().(*ServerArgs_Mark); ok { - return x.Mark - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerArgs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerArgs_OneofMarshaler, _ServerArgs_OneofUnmarshaler, _ServerArgs_OneofSizer, []interface{}{ - (*ServerArgs_Setup)(nil), - (*ServerArgs_Mark)(nil), - } -} - -func _ServerArgs_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerArgs) - // argtype - switch x := m.Argtype.(type) { - case *ServerArgs_Setup: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Setup); err != nil { - return err - } - case *ServerArgs_Mark: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Mark); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ServerArgs.Argtype has unexpected type %T", x) - } - return nil -} - -func _ServerArgs_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerArgs) - switch tag { - case 1: // argtype.setup - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ServerConfig) - err := b.DecodeMessage(msg) - m.Argtype = &ServerArgs_Setup{msg} - return true, err - case 2: // argtype.mark - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Mark) - err := b.DecodeMessage(msg) - m.Argtype = &ServerArgs_Mark{msg} - return true, err - default: - return false, nil - } -} - -func _ServerArgs_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerArgs) - // argtype - switch x := m.Argtype.(type) { - case *ServerArgs_Setup: - s := proto.Size(x.Setup) - n += proto.SizeVarint(1<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerArgs_Mark: - s := proto.Size(x.Mark) - n += proto.SizeVarint(2<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type ServerStatus struct { - Stats *ServerStats `protobuf:"bytes,1,opt,name=stats" json:"stats,omitempty"` - // the port bound by the server - Port int32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"` - // Number of cores available to the server - Cores int32 `protobuf:"varint,3,opt,name=cores" json:"cores,omitempty"` -} - -func (m *ServerStatus) Reset() { *m = ServerStatus{} } -func (m *ServerStatus) String() string { return proto.CompactTextString(m) } -func (*ServerStatus) ProtoMessage() {} -func (*ServerStatus) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} } - -func (m *ServerStatus) GetStats() *ServerStats { - if m != nil { - return m.Stats - } - return nil -} - -func (m *ServerStatus) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *ServerStatus) GetCores() int32 { - if m != nil { - return m.Cores - } - return 0 -} - -type CoreRequest struct { -} - -func (m *CoreRequest) Reset() { *m = CoreRequest{} } -func (m *CoreRequest) String() string { return proto.CompactTextString(m) } -func (*CoreRequest) ProtoMessage() {} -func (*CoreRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} } - -type CoreResponse struct { - // Number of cores available on the server - Cores int32 `protobuf:"varint,1,opt,name=cores" json:"cores,omitempty"` -} - -func (m *CoreResponse) Reset() { *m = CoreResponse{} } -func (m *CoreResponse) String() string { return proto.CompactTextString(m) } -func (*CoreResponse) ProtoMessage() {} -func (*CoreResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } - -func (m *CoreResponse) GetCores() int32 { - if m != nil { - return m.Cores - } - return 0 -} - -type Void struct { -} - -func (m *Void) Reset() { *m = Void{} } -func (m *Void) String() string { return proto.CompactTextString(m) } -func (*Void) ProtoMessage() {} -func (*Void) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } - -// A single performance scenario: input to qps_json_driver -type Scenario struct { - // Human readable name for this scenario - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Client configuration - ClientConfig *ClientConfig `protobuf:"bytes,2,opt,name=client_config,json=clientConfig" json:"client_config,omitempty"` - // Number of clients to start for the test - NumClients int32 `protobuf:"varint,3,opt,name=num_clients,json=numClients" json:"num_clients,omitempty"` - // Server configuration - ServerConfig *ServerConfig `protobuf:"bytes,4,opt,name=server_config,json=serverConfig" json:"server_config,omitempty"` - // Number of servers to start for the test - NumServers int32 `protobuf:"varint,5,opt,name=num_servers,json=numServers" json:"num_servers,omitempty"` - // Warmup period, in seconds - WarmupSeconds int32 `protobuf:"varint,6,opt,name=warmup_seconds,json=warmupSeconds" json:"warmup_seconds,omitempty"` - // Benchmark time, in seconds - BenchmarkSeconds int32 `protobuf:"varint,7,opt,name=benchmark_seconds,json=benchmarkSeconds" json:"benchmark_seconds,omitempty"` - // Number of workers to spawn locally (usually zero) - SpawnLocalWorkerCount int32 `protobuf:"varint,8,opt,name=spawn_local_worker_count,json=spawnLocalWorkerCount" json:"spawn_local_worker_count,omitempty"` -} - -func (m *Scenario) Reset() { *m = Scenario{} } -func (m *Scenario) String() string { return proto.CompactTextString(m) } -func (*Scenario) ProtoMessage() {} -func (*Scenario) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } - -func (m *Scenario) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Scenario) GetClientConfig() *ClientConfig { - if m != nil { - return m.ClientConfig - } - return nil -} - -func (m *Scenario) GetNumClients() int32 { - if m != nil { - return m.NumClients - } - return 0 -} - -func (m *Scenario) GetServerConfig() *ServerConfig { - if m != nil { - return m.ServerConfig - } - return nil -} - -func (m *Scenario) GetNumServers() int32 { - if m != nil { - return m.NumServers - } - return 0 -} - -func (m *Scenario) GetWarmupSeconds() int32 { - if m != nil { - return m.WarmupSeconds - } - return 0 -} - -func (m *Scenario) GetBenchmarkSeconds() int32 { - if m != nil { - return m.BenchmarkSeconds - } - return 0 -} - -func (m *Scenario) GetSpawnLocalWorkerCount() int32 { - if m != nil { - return m.SpawnLocalWorkerCount - } - return 0 -} - -// A set of scenarios to be run with qps_json_driver -type Scenarios struct { - Scenarios []*Scenario `protobuf:"bytes,1,rep,name=scenarios" json:"scenarios,omitempty"` -} - -func (m *Scenarios) Reset() { *m = Scenarios{} } -func (m *Scenarios) String() string { return proto.CompactTextString(m) } -func (*Scenarios) ProtoMessage() {} -func (*Scenarios) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} } - -func (m *Scenarios) GetScenarios() []*Scenario { - if m != nil { - return m.Scenarios - } - return nil -} - -func init() { - proto.RegisterType((*PoissonParams)(nil), "grpc.testing.PoissonParams") - proto.RegisterType((*UniformParams)(nil), "grpc.testing.UniformParams") - proto.RegisterType((*DeterministicParams)(nil), "grpc.testing.DeterministicParams") - proto.RegisterType((*ParetoParams)(nil), "grpc.testing.ParetoParams") - proto.RegisterType((*ClosedLoopParams)(nil), "grpc.testing.ClosedLoopParams") - proto.RegisterType((*LoadParams)(nil), "grpc.testing.LoadParams") - proto.RegisterType((*SecurityParams)(nil), "grpc.testing.SecurityParams") - proto.RegisterType((*ClientConfig)(nil), "grpc.testing.ClientConfig") - proto.RegisterType((*ClientStatus)(nil), "grpc.testing.ClientStatus") - proto.RegisterType((*Mark)(nil), "grpc.testing.Mark") - proto.RegisterType((*ClientArgs)(nil), "grpc.testing.ClientArgs") - proto.RegisterType((*ServerConfig)(nil), "grpc.testing.ServerConfig") - proto.RegisterType((*ServerArgs)(nil), "grpc.testing.ServerArgs") - proto.RegisterType((*ServerStatus)(nil), "grpc.testing.ServerStatus") - proto.RegisterType((*CoreRequest)(nil), "grpc.testing.CoreRequest") - proto.RegisterType((*CoreResponse)(nil), "grpc.testing.CoreResponse") - proto.RegisterType((*Void)(nil), "grpc.testing.Void") - proto.RegisterType((*Scenario)(nil), "grpc.testing.Scenario") - proto.RegisterType((*Scenarios)(nil), "grpc.testing.Scenarios") - proto.RegisterEnum("grpc.testing.ClientType", ClientType_name, ClientType_value) - proto.RegisterEnum("grpc.testing.ServerType", ServerType_name, ServerType_value) - proto.RegisterEnum("grpc.testing.RpcType", RpcType_name, RpcType_value) -} - -func init() { proto.RegisterFile("control.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 1179 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0x6f, 0x6f, 0xdb, 0xb6, - 0x13, 0xb6, 0x1d, 0xdb, 0xb1, 0x4e, 0xb6, 0xe3, 0x1f, 0x7f, 0xe9, 0xa0, 0xa6, 0x69, 0x97, 0x6a, - 0x1b, 0x16, 0x64, 0x40, 0x5a, 0x78, 0x05, 0xba, 0x62, 0x2f, 0x02, 0xc7, 0x33, 0xea, 0x00, 0x69, - 0x96, 0xd1, 0x69, 0x87, 0xbe, 0x12, 0x18, 0x99, 0xb1, 0x85, 0xc8, 0xa2, 0x46, 0x52, 0x09, 0xf2, - 0x15, 0xf6, 0x99, 0xf6, 0x39, 0xf6, 0x35, 0xf6, 0x15, 0x06, 0xfe, 0x91, 0x23, 0xb9, 0x06, 0x9a, - 0x6d, 0xef, 0xc4, 0xbb, 0xe7, 0xe1, 0x91, 0xf7, 0xdc, 0x1d, 0x05, 0x9d, 0x90, 0x25, 0x92, 0xb3, - 0xf8, 0x30, 0xe5, 0x4c, 0x32, 0xd4, 0x9e, 0xf1, 0x34, 0x3c, 0x94, 0x54, 0xc8, 0x28, 0x99, 0xed, - 0x74, 0x53, 0x72, 0x17, 0x33, 0x32, 0x15, 0xc6, 0xbb, 0xe3, 0x0a, 0x49, 0xa4, 0x5d, 0xf8, 0x7d, - 0xe8, 0x9c, 0xb3, 0x48, 0x08, 0x96, 0x9c, 0x13, 0x4e, 0x16, 0x02, 0x3d, 0x87, 0x36, 0xbb, 0xba, - 0xa2, 0x9c, 0x4e, 0x03, 0x45, 0xf2, 0xaa, 0x7b, 0xd5, 0xfd, 0x2a, 0x76, 0xad, 0xed, 0x94, 0x91, - 0xa9, 0x4f, 0xa0, 0xf3, 0x3e, 0x89, 0xae, 0x18, 0x5f, 0x58, 0xce, 0xb7, 0xb0, 0x15, 0x25, 0x92, - 0x72, 0xc2, 0x79, 0x74, 0x43, 0xe2, 0x20, 0x66, 0x96, 0xd6, 0x2d, 0x9a, 0x4f, 0xd9, 0x27, 0xc0, - 0x79, 0xe4, 0xd5, 0x3e, 0x05, 0x8e, 0x23, 0xff, 0x07, 0xf8, 0xff, 0x4f, 0x54, 0x52, 0xbe, 0x88, - 0x92, 0x48, 0xc8, 0x28, 0x7c, 0xf8, 0xe1, 0x7e, 0x81, 0xf6, 0x39, 0xe1, 0x54, 0x32, 0x4b, 0xf9, - 0x0e, 0xfe, 0x57, 0x0a, 0x79, 0x49, 0x04, 0xb5, 0xbc, 0x5e, 0xd1, 0x71, 0x4c, 0x04, 0x45, 0xdb, - 0xd0, 0x20, 0x71, 0x3a, 0x27, 0xf6, 0x54, 0x66, 0xe1, 0x23, 0xe8, 0x0d, 0x63, 0x26, 0x54, 0x00, - 0x96, 0x9a, 0x6d, 0xfd, 0x3f, 0x6a, 0x00, 0x2a, 0x9e, 0x8d, 0x32, 0x00, 0x37, 0xd4, 0x90, 0x20, - 0x66, 0x2c, 0xd5, 0xfb, 0xbb, 0xfd, 0x67, 0x87, 0x45, 0x1d, 0x0e, 0x57, 0xf7, 0x18, 0x57, 0x30, - 0x84, 0x4b, 0x1b, 0x7a, 0x0d, 0x9b, 0xa9, 0x51, 0x42, 0x47, 0x77, 0xfb, 0x4f, 0xca, 0xf4, 0x92, - 0x4c, 0xe3, 0x0a, 0xce, 0xd1, 0x8a, 0x98, 0x19, 0x39, 0xbc, 0x8d, 0x75, 0xc4, 0x92, 0x56, 0x8a, - 0x68, 0xd1, 0xe8, 0x47, 0x68, 0x4e, 0x75, 0x92, 0xbd, 0xba, 0xe6, 0x3d, 0x2f, 0xf3, 0xd6, 0x08, - 0x30, 0xae, 0x60, 0x4b, 0x41, 0xaf, 0xa0, 0x99, 0xea, 0x3c, 0x7b, 0x0d, 0x4d, 0xde, 0x59, 0x39, - 0x6d, 0x41, 0x03, 0xc5, 0x32, 0xd8, 0xe3, 0x26, 0xd4, 0x95, 0x70, 0xfe, 0x25, 0x74, 0x27, 0x34, - 0xcc, 0x78, 0x24, 0xef, 0x6c, 0x06, 0x9f, 0x81, 0x9b, 0x09, 0x1a, 0x28, 0x7e, 0x10, 0x12, 0x9d, - 0xc1, 0x16, 0x76, 0x32, 0x41, 0x2f, 0xa8, 0x90, 0x43, 0x82, 0x5e, 0xc2, 0xb6, 0xa0, 0xfc, 0x86, - 0xf2, 0x60, 0xce, 0x84, 0x0c, 0xd8, 0x0d, 0xe5, 0x3c, 0x9a, 0x52, 0x9d, 0x2b, 0x07, 0x23, 0xe3, - 0x1b, 0x33, 0x21, 0x7f, 0xb6, 0x1e, 0xff, 0xf7, 0x06, 0xb4, 0x87, 0x71, 0x44, 0x13, 0x39, 0x64, - 0xc9, 0x55, 0x34, 0x43, 0xdf, 0x40, 0xd7, 0x6e, 0x21, 0x09, 0x9f, 0x51, 0x29, 0xbc, 0xea, 0xde, - 0xc6, 0xbe, 0x83, 0x3b, 0xc6, 0x7a, 0x61, 0x8c, 0xe8, 0x8d, 0xd2, 0x52, 0xd1, 0x02, 0x79, 0x97, - 0x9a, 0x00, 0xdd, 0xbe, 0xb7, 0xaa, 0xa5, 0x02, 0x5c, 0xdc, 0xa5, 0x54, 0x69, 0x98, 0x7f, 0xa3, - 0x11, 0x6c, 0x09, 0x7b, 0xad, 0x20, 0xd5, 0xf7, 0xb2, 0x92, 0xec, 0x96, 0xe9, 0xe5, 0xbb, 0xe3, - 0xae, 0x28, 0xe7, 0xe2, 0x08, 0x76, 0x59, 0x26, 0x85, 0x24, 0xc9, 0x34, 0x4a, 0x66, 0x01, 0x4f, - 0x43, 0x11, 0xa4, 0x94, 0x07, 0xe1, 0x9c, 0x24, 0x09, 0x8d, 0xb5, 0x5c, 0x0d, 0xfc, 0xb8, 0x80, - 0xc1, 0x69, 0x28, 0xce, 0x29, 0x1f, 0x1a, 0x80, 0xea, 0x33, 0x7b, 0x05, 0x4b, 0x11, 0x5a, 0xa5, - 0x06, 0xee, 0x1a, 0xb3, 0xc5, 0x09, 0x95, 0x55, 0x22, 0xee, 0x92, 0x30, 0xc8, 0x6f, 0x3c, 0xe7, - 0x94, 0x4c, 0x85, 0xb7, 0xa9, 0xd1, 0x48, 0xfb, 0xec, 0x5d, 0x8d, 0x07, 0xbd, 0x84, 0x16, 0x4f, - 0x43, 0x93, 0x9a, 0x96, 0x4e, 0xcd, 0xa3, 0xf2, 0xdd, 0x70, 0x1a, 0xea, 0xbc, 0x6c, 0x72, 0xf3, - 0xa1, 0xf2, 0xa9, 0x34, 0xcf, 0x13, 0x02, 0x3a, 0x21, 0x2b, 0xf9, 0xbc, 0x6f, 0x25, 0x0c, 0xf1, - 0x7d, 0x5b, 0x1d, 0x43, 0x3e, 0xbc, 0x82, 0x50, 0x6b, 0xe8, 0xb9, 0x6b, 0x5b, 0xc3, 0x60, 0x8c, - 0xcc, 0xb8, 0x93, 0x16, 0x97, 0x68, 0x0c, 0xbd, 0x79, 0x24, 0x24, 0x9b, 0x71, 0xb2, 0xc8, 0xcf, - 0xd0, 0xd6, 0xbb, 0x3c, 0x2d, 0xef, 0x32, 0xce, 0x51, 0xf6, 0x20, 0x5b, 0xf3, 0xb2, 0x01, 0x3d, - 0x01, 0x27, 0x64, 0x9c, 0x06, 0x71, 0x24, 0xa4, 0xd7, 0xd9, 0xdb, 0xd8, 0x6f, 0xe0, 0x96, 0x32, - 0x9c, 0x46, 0x42, 0xa2, 0xa7, 0x00, 0xd6, 0xb9, 0x88, 0xa4, 0xd7, 0xd5, 0xf9, 0x73, 0x8c, 0x77, - 0x11, 0x49, 0xff, 0x28, 0xaf, 0xc5, 0x89, 0x24, 0x32, 0x13, 0xe8, 0x05, 0x34, 0xf4, 0x18, 0xb6, - 0xa3, 0xe2, 0xf1, 0xba, 0xf2, 0x52, 0x50, 0x81, 0x0d, 0xce, 0xdf, 0x85, 0xfa, 0x3b, 0xc2, 0xaf, - 0xd5, 0x88, 0xe2, 0x54, 0x50, 0x69, 0x3b, 0xc4, 0x2c, 0xfc, 0x0c, 0xc0, 0x70, 0x06, 0x7c, 0x26, - 0x50, 0x1f, 0x1a, 0x82, 0xca, 0x2c, 0x9f, 0x43, 0x3b, 0xeb, 0x36, 0x37, 0xd9, 0x19, 0x57, 0xb0, - 0x81, 0xa2, 0x7d, 0xa8, 0x2f, 0x08, 0xbf, 0xb6, 0xb3, 0x07, 0x95, 0x29, 0x2a, 0xf2, 0xb8, 0x82, - 0x35, 0xe2, 0xd8, 0x81, 0x4d, 0xc2, 0x67, 0xaa, 0x00, 0xfc, 0x3f, 0x6b, 0xd0, 0x9e, 0xe8, 0xe6, - 0xb1, 0xc9, 0x7e, 0x03, 0x6e, 0xde, 0x62, 0xaa, 0x40, 0xaa, 0xeb, 0x7a, 0xc7, 0x10, 0x4c, 0xef, - 0x88, 0xe5, 0xf7, 0xba, 0xde, 0xa9, 0xfd, 0x8b, 0xde, 0x41, 0x50, 0x4f, 0x19, 0x97, 0xb6, 0x47, - 0xf4, 0xf7, 0x7d, 0x95, 0xe7, 0x67, 0x5b, 0x53, 0xe5, 0xf6, 0x54, 0xb6, 0xca, 0xcb, 0x6a, 0xb6, - 0x56, 0xd4, 0x5c, 0x53, 0x97, 0xce, 0x3f, 0xae, 0xcb, 0x52, 0x35, 0x41, 0xb9, 0x9a, 0x94, 0x9e, - 0xe6, 0x40, 0x0f, 0xd0, 0xb3, 0x28, 0xc0, 0x7f, 0xd4, 0x33, 0xca, 0xe5, 0x7c, 0x50, 0x95, 0xde, - 0x43, 0xf3, 0x2a, 0x5d, 0x66, 0xbf, 0x56, 0xc8, 0xfe, 0x36, 0x34, 0xd4, 0xbd, 0xcc, 0x28, 0x6c, - 0x60, 0xb3, 0xf0, 0x3b, 0xe0, 0x0e, 0x19, 0xa7, 0x98, 0xfe, 0x96, 0x51, 0x21, 0xfd, 0xaf, 0xa1, - 0x6d, 0x96, 0x22, 0x65, 0x89, 0x79, 0x89, 0x0d, 0xa9, 0x5a, 0x24, 0x35, 0xa1, 0xfe, 0x81, 0x45, - 0x53, 0xff, 0xaf, 0x1a, 0xb4, 0x26, 0x21, 0x4d, 0x08, 0x8f, 0x98, 0x8a, 0x99, 0x90, 0x85, 0x29, - 0x36, 0x07, 0xeb, 0x6f, 0x74, 0x04, 0x9d, 0x7c, 0x00, 0x1a, 0x7d, 0x6a, 0x9f, 0xeb, 0x04, 0xdc, - 0x0e, 0x8b, 0x6f, 0xc5, 0x97, 0xe0, 0x26, 0xd9, 0xc2, 0x8e, 0xc5, 0xfc, 0xe8, 0x90, 0x64, 0x0b, - 0xc3, 0x51, 0x33, 0xda, 0x3e, 0x1b, 0x79, 0x84, 0xfa, 0xe7, 0xb4, 0xc1, 0x6d, 0x51, 0x6c, 0x15, - 0x1b, 0xc1, 0xd8, 0xf2, 0xf9, 0xac, 0x22, 0x18, 0x8e, 0x50, 0xcf, 0xd5, 0x2d, 0xe1, 0x8b, 0x2c, - 0x0d, 0x04, 0x0d, 0x59, 0x32, 0x15, 0x5e, 0x53, 0x63, 0x3a, 0xc6, 0x3a, 0x31, 0x46, 0xf5, 0x83, - 0x73, 0x49, 0x93, 0x70, 0xae, 0xb4, 0x5c, 0x22, 0x4d, 0x65, 0xf7, 0x96, 0x8e, 0x1c, 0xfc, 0x1a, - 0x3c, 0x91, 0x92, 0xdb, 0x24, 0x88, 0x59, 0x48, 0xe2, 0xe0, 0x96, 0xf1, 0x6b, 0x7d, 0x83, 0x2c, - 0xc9, 0xab, 0xfc, 0x91, 0xf6, 0x9f, 0x2a, 0xf7, 0xaf, 0xda, 0x3b, 0x54, 0x4e, 0x7f, 0x00, 0x4e, - 0x9e, 0x70, 0x81, 0x5e, 0x81, 0x23, 0xf2, 0x85, 0x7e, 0x43, 0xdd, 0xfe, 0x17, 0x2b, 0xf7, 0xb6, - 0x6e, 0x7c, 0x0f, 0x3c, 0x78, 0x91, 0xcf, 0x28, 0xdd, 0xee, 0x5b, 0xe0, 0x4e, 0x3e, 0x9e, 0x0d, - 0x83, 0xe1, 0xe9, 0xc9, 0xe8, 0xec, 0xa2, 0x57, 0x41, 0x3d, 0x68, 0x0f, 0x8a, 0x96, 0xea, 0xc1, - 0x49, 0xde, 0x04, 0x25, 0xc2, 0x64, 0x84, 0x3f, 0x8c, 0x70, 0x91, 0x60, 0x2d, 0x55, 0xe4, 0xc1, - 0xb6, 0xb1, 0xbc, 0x1d, 0x9d, 0x8d, 0xf0, 0xc9, 0xd2, 0x53, 0x3b, 0xf8, 0x0a, 0x36, 0xed, 0xbb, - 0x84, 0x1c, 0x68, 0xbc, 0x3f, 0x1b, 0xe0, 0x8f, 0xbd, 0x0a, 0xea, 0x80, 0x33, 0xb9, 0xc0, 0xa3, - 0xc1, 0xbb, 0x93, 0xb3, 0xb7, 0xbd, 0xea, 0x65, 0x53, 0xff, 0x12, 0x7f, 0xff, 0x77, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x75, 0x59, 0xf4, 0x03, 0x4e, 0x0b, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/control.proto b/vendor/google.golang.org/grpc/benchmark/grpc_testing/control.proto deleted file mode 100644 index 9379ef49a..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/control.proto +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -import "payloads.proto"; -import "stats.proto"; - -package grpc.testing; - -enum ClientType { - SYNC_CLIENT = 0; - ASYNC_CLIENT = 1; -} - -enum ServerType { - SYNC_SERVER = 0; - ASYNC_SERVER = 1; - ASYNC_GENERIC_SERVER = 2; -} - -enum RpcType { - UNARY = 0; - STREAMING = 1; -} - -// Parameters of poisson process distribution, which is a good representation -// of activity coming in from independent identical stationary sources. -message PoissonParams { - // The rate of arrivals (a.k.a. lambda parameter of the exp distribution). - double offered_load = 1; -} - -message UniformParams { - double interarrival_lo = 1; - double interarrival_hi = 2; -} - -message DeterministicParams { - double offered_load = 1; -} - -message ParetoParams { - double interarrival_base = 1; - double alpha = 2; -} - -// Once an RPC finishes, immediately start a new one. -// No configuration parameters needed. -message ClosedLoopParams { -} - -message LoadParams { - oneof load { - ClosedLoopParams closed_loop = 1; - PoissonParams poisson = 2; - UniformParams uniform = 3; - DeterministicParams determ = 4; - ParetoParams pareto = 5; - }; -} - -// presence of SecurityParams implies use of TLS -message SecurityParams { - bool use_test_ca = 1; - string server_host_override = 2; -} - -message ClientConfig { - // List of targets to connect to. At least one target needs to be specified. - repeated string server_targets = 1; - ClientType client_type = 2; - SecurityParams security_params = 3; - // How many concurrent RPCs to start for each channel. - // For synchronous client, use a separate thread for each outstanding RPC. - int32 outstanding_rpcs_per_channel = 4; - // Number of independent client channels to create. - // i-th channel will connect to server_target[i % server_targets.size()] - int32 client_channels = 5; - // Only for async client. Number of threads to use to start/manage RPCs. - int32 async_client_threads = 7; - RpcType rpc_type = 8; - // The requested load for the entire client (aggregated over all the threads). - LoadParams load_params = 10; - PayloadConfig payload_config = 11; - HistogramParams histogram_params = 12; - - // Specify the cores we should run the client on, if desired - repeated int32 core_list = 13; - int32 core_limit = 14; -} - -message ClientStatus { - ClientStats stats = 1; -} - -// Request current stats -message Mark { - // if true, the stats will be reset after taking their snapshot. - bool reset = 1; -} - -message ClientArgs { - oneof argtype { - ClientConfig setup = 1; - Mark mark = 2; - } -} - -message ServerConfig { - ServerType server_type = 1; - SecurityParams security_params = 2; - // Port on which to listen. Zero means pick unused port. - int32 port = 4; - // Only for async server. Number of threads used to serve the requests. - int32 async_server_threads = 7; - // Specify the number of cores to limit server to, if desired - int32 core_limit = 8; - // payload config, used in generic server - PayloadConfig payload_config = 9; - - // Specify the cores we should run the server on, if desired - repeated int32 core_list = 10; -} - -message ServerArgs { - oneof argtype { - ServerConfig setup = 1; - Mark mark = 2; - } -} - -message ServerStatus { - ServerStats stats = 1; - // the port bound by the server - int32 port = 2; - // Number of cores available to the server - int32 cores = 3; -} - -message CoreRequest { -} - -message CoreResponse { - // Number of cores available on the server - int32 cores = 1; -} - -message Void { -} - -// A single performance scenario: input to qps_json_driver -message Scenario { - // Human readable name for this scenario - string name = 1; - // Client configuration - ClientConfig client_config = 2; - // Number of clients to start for the test - int32 num_clients = 3; - // Server configuration - ServerConfig server_config = 4; - // Number of servers to start for the test - int32 num_servers = 5; - // Warmup period, in seconds - int32 warmup_seconds = 6; - // Benchmark time, in seconds - int32 benchmark_seconds = 7; - // Number of workers to spawn locally (usually zero) - int32 spawn_local_worker_count = 8; -} - -// A set of scenarios to be run with qps_json_driver -message Scenarios { - repeated Scenario scenarios = 1; -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/messages.pb.go b/vendor/google.golang.org/grpc/benchmark/grpc_testing/messages.pb.go deleted file mode 100644 index b34c5d59a..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/messages.pb.go +++ /dev/null @@ -1,479 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: messages.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// The type of payload that should be returned. -type PayloadType int32 - -const ( - // Compressable text format. - PayloadType_COMPRESSABLE PayloadType = 0 - // Uncompressable binary format. - PayloadType_UNCOMPRESSABLE PayloadType = 1 - // Randomly chosen from all other formats defined in this enum. - PayloadType_RANDOM PayloadType = 2 -) - -var PayloadType_name = map[int32]string{ - 0: "COMPRESSABLE", - 1: "UNCOMPRESSABLE", - 2: "RANDOM", -} -var PayloadType_value = map[string]int32{ - "COMPRESSABLE": 0, - "UNCOMPRESSABLE": 1, - "RANDOM": 2, -} - -func (x PayloadType) String() string { - return proto.EnumName(PayloadType_name, int32(x)) -} -func (PayloadType) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{0} } - -// Compression algorithms -type CompressionType int32 - -const ( - // No compression - CompressionType_NONE CompressionType = 0 - CompressionType_GZIP CompressionType = 1 - CompressionType_DEFLATE CompressionType = 2 -) - -var CompressionType_name = map[int32]string{ - 0: "NONE", - 1: "GZIP", - 2: "DEFLATE", -} -var CompressionType_value = map[string]int32{ - "NONE": 0, - "GZIP": 1, - "DEFLATE": 2, -} - -func (x CompressionType) String() string { - return proto.EnumName(CompressionType_name, int32(x)) -} -func (CompressionType) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{1} } - -// A block of data, to simply increase gRPC message size. -type Payload struct { - // The type of data in body. - Type PayloadType `protobuf:"varint,1,opt,name=type,enum=grpc.testing.PayloadType" json:"type,omitempty"` - // Primary contents of payload. - Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"` -} - -func (m *Payload) Reset() { *m = Payload{} } -func (m *Payload) String() string { return proto.CompactTextString(m) } -func (*Payload) ProtoMessage() {} -func (*Payload) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} } - -func (m *Payload) GetType() PayloadType { - if m != nil { - return m.Type - } - return PayloadType_COMPRESSABLE -} - -func (m *Payload) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -type EchoStatus struct { - Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` - Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` -} - -func (m *EchoStatus) Reset() { *m = EchoStatus{} } -func (m *EchoStatus) String() string { return proto.CompactTextString(m) } -func (*EchoStatus) ProtoMessage() {} -func (*EchoStatus) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} } - -func (m *EchoStatus) GetCode() int32 { - if m != nil { - return m.Code - } - return 0 -} - -func (m *EchoStatus) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -// Unary request. -type SimpleRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - ResponseSize int32 `protobuf:"varint,2,opt,name=response_size,json=responseSize" json:"response_size,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"` - // Whether SimpleResponse should include username. - FillUsername bool `protobuf:"varint,4,opt,name=fill_username,json=fillUsername" json:"fill_username,omitempty"` - // Whether SimpleResponse should include OAuth scope. - FillOauthScope bool `protobuf:"varint,5,opt,name=fill_oauth_scope,json=fillOauthScope" json:"fill_oauth_scope,omitempty"` - // Compression algorithm to be used by the server for the response (stream) - ResponseCompression CompressionType `protobuf:"varint,6,opt,name=response_compression,json=responseCompression,enum=grpc.testing.CompressionType" json:"response_compression,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus" json:"response_status,omitempty"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} } - -func (m *SimpleRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *SimpleRequest) GetResponseSize() int32 { - if m != nil { - return m.ResponseSize - } - return 0 -} - -func (m *SimpleRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleRequest) GetFillUsername() bool { - if m != nil { - return m.FillUsername - } - return false -} - -func (m *SimpleRequest) GetFillOauthScope() bool { - if m != nil { - return m.FillOauthScope - } - return false -} - -func (m *SimpleRequest) GetResponseCompression() CompressionType { - if m != nil { - return m.ResponseCompression - } - return CompressionType_NONE -} - -func (m *SimpleRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Unary response, as configured by the request. -type SimpleResponse struct { - // Payload to increase message size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` - // The user the request came from, for verifying authentication was - // successful when the client expected it. - Username string `protobuf:"bytes,2,opt,name=username" json:"username,omitempty"` - // OAuth scope. - OauthScope string `protobuf:"bytes,3,opt,name=oauth_scope,json=oauthScope" json:"oauth_scope,omitempty"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} } - -func (m *SimpleResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleResponse) GetUsername() string { - if m != nil { - return m.Username - } - return "" -} - -func (m *SimpleResponse) GetOauthScope() string { - if m != nil { - return m.OauthScope - } - return "" -} - -// Client-streaming request. -type StreamingInputCallRequest struct { - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` -} - -func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} } -func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallRequest) ProtoMessage() {} -func (*StreamingInputCallRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} } - -func (m *StreamingInputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Client-streaming response. -type StreamingInputCallResponse struct { - // Aggregated size of payloads received from the client. - AggregatedPayloadSize int32 `protobuf:"varint,1,opt,name=aggregated_payload_size,json=aggregatedPayloadSize" json:"aggregated_payload_size,omitempty"` -} - -func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} } -func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallResponse) ProtoMessage() {} -func (*StreamingInputCallResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} } - -func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 { - if m != nil { - return m.AggregatedPayloadSize - } - return 0 -} - -// Configuration for a particular response. -type ResponseParameters struct { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - Size int32 `protobuf:"varint,1,opt,name=size" json:"size,omitempty"` - // Desired interval between consecutive responses in the response stream in - // microseconds. - IntervalUs int32 `protobuf:"varint,2,opt,name=interval_us,json=intervalUs" json:"interval_us,omitempty"` -} - -func (m *ResponseParameters) Reset() { *m = ResponseParameters{} } -func (m *ResponseParameters) String() string { return proto.CompactTextString(m) } -func (*ResponseParameters) ProtoMessage() {} -func (*ResponseParameters) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} } - -func (m *ResponseParameters) GetSize() int32 { - if m != nil { - return m.Size - } - return 0 -} - -func (m *ResponseParameters) GetIntervalUs() int32 { - if m != nil { - return m.IntervalUs - } - return 0 -} - -// Server-streaming request. -type StreamingOutputCallRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Configuration for each expected response message. - ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters,json=responseParameters" json:"response_parameters,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"` - // Compression algorithm to be used by the server for the response (stream) - ResponseCompression CompressionType `protobuf:"varint,6,opt,name=response_compression,json=responseCompression,enum=grpc.testing.CompressionType" json:"response_compression,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus" json:"response_status,omitempty"` -} - -func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} } -func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallRequest) ProtoMessage() {} -func (*StreamingOutputCallRequest) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} } - -func (m *StreamingOutputCallRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters { - if m != nil { - return m.ResponseParameters - } - return nil -} - -func (m *StreamingOutputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *StreamingOutputCallRequest) GetResponseCompression() CompressionType { - if m != nil { - return m.ResponseCompression - } - return CompressionType_NONE -} - -func (m *StreamingOutputCallRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Server-streaming response, as configured by the request and parameters. -type StreamingOutputCallResponse struct { - // Payload to increase response size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` -} - -func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} } -func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallResponse) ProtoMessage() {} -func (*StreamingOutputCallResponse) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} } - -func (m *StreamingOutputCallResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// For reconnect interop test only. -// Client tells server what reconnection parameters it used. -type ReconnectParams struct { - MaxReconnectBackoffMs int32 `protobuf:"varint,1,opt,name=max_reconnect_backoff_ms,json=maxReconnectBackoffMs" json:"max_reconnect_backoff_ms,omitempty"` -} - -func (m *ReconnectParams) Reset() { *m = ReconnectParams{} } -func (m *ReconnectParams) String() string { return proto.CompactTextString(m) } -func (*ReconnectParams) ProtoMessage() {} -func (*ReconnectParams) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{9} } - -func (m *ReconnectParams) GetMaxReconnectBackoffMs() int32 { - if m != nil { - return m.MaxReconnectBackoffMs - } - return 0 -} - -// For reconnect interop test only. -// Server tells client whether its reconnects are following the spec and the -// reconnect backoffs it saw. -type ReconnectInfo struct { - Passed bool `protobuf:"varint,1,opt,name=passed" json:"passed,omitempty"` - BackoffMs []int32 `protobuf:"varint,2,rep,packed,name=backoff_ms,json=backoffMs" json:"backoff_ms,omitempty"` -} - -func (m *ReconnectInfo) Reset() { *m = ReconnectInfo{} } -func (m *ReconnectInfo) String() string { return proto.CompactTextString(m) } -func (*ReconnectInfo) ProtoMessage() {} -func (*ReconnectInfo) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{10} } - -func (m *ReconnectInfo) GetPassed() bool { - if m != nil { - return m.Passed - } - return false -} - -func (m *ReconnectInfo) GetBackoffMs() []int32 { - if m != nil { - return m.BackoffMs - } - return nil -} - -func init() { - proto.RegisterType((*Payload)(nil), "grpc.testing.Payload") - proto.RegisterType((*EchoStatus)(nil), "grpc.testing.EchoStatus") - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") - proto.RegisterType((*StreamingInputCallRequest)(nil), "grpc.testing.StreamingInputCallRequest") - proto.RegisterType((*StreamingInputCallResponse)(nil), "grpc.testing.StreamingInputCallResponse") - proto.RegisterType((*ResponseParameters)(nil), "grpc.testing.ResponseParameters") - proto.RegisterType((*StreamingOutputCallRequest)(nil), "grpc.testing.StreamingOutputCallRequest") - proto.RegisterType((*StreamingOutputCallResponse)(nil), "grpc.testing.StreamingOutputCallResponse") - proto.RegisterType((*ReconnectParams)(nil), "grpc.testing.ReconnectParams") - proto.RegisterType((*ReconnectInfo)(nil), "grpc.testing.ReconnectInfo") - proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value) - proto.RegisterEnum("grpc.testing.CompressionType", CompressionType_name, CompressionType_value) -} - -func init() { proto.RegisterFile("messages.proto", fileDescriptor1) } - -var fileDescriptor1 = []byte{ - // 652 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0x4d, 0x6f, 0xd3, 0x40, - 0x10, 0xc5, 0xf9, 0xee, 0x24, 0x4d, 0xa3, 0x85, 0x82, 0x5b, 0x54, 0x11, 0x99, 0x4b, 0x54, 0x89, - 0x20, 0x05, 0x09, 0x24, 0x0e, 0xa0, 0xb4, 0x4d, 0x51, 0x50, 0x9a, 0x84, 0x75, 0x7b, 0xe1, 0x62, - 0x6d, 0x9c, 0x8d, 0x6b, 0x11, 0x7b, 0x8d, 0x77, 0x8d, 0x9a, 0x1e, 0xb8, 0xf3, 0x83, 0xb9, 0xa3, - 0x5d, 0x7f, 0xc4, 0x69, 0x7b, 0x68, 0xe1, 0xc2, 0x6d, 0xf7, 0xed, 0x9b, 0x97, 0x79, 0x33, 0xcf, - 0x0a, 0x34, 0x3d, 0xca, 0x39, 0x71, 0x28, 0xef, 0x06, 0x21, 0x13, 0x0c, 0x35, 0x9c, 0x30, 0xb0, - 0xbb, 0x82, 0x72, 0xe1, 0xfa, 0x8e, 0x31, 0x82, 0xea, 0x94, 0xac, 0x96, 0x8c, 0xcc, 0xd1, 0x2b, - 0x28, 0x89, 0x55, 0x40, 0x75, 0xad, 0xad, 0x75, 0x9a, 0xbd, 0xbd, 0x6e, 0x9e, 0xd7, 0x4d, 0x48, - 0xe7, 0xab, 0x80, 0x62, 0x45, 0x43, 0x08, 0x4a, 0x33, 0x36, 0x5f, 0xe9, 0x85, 0xb6, 0xd6, 0x69, - 0x60, 0x75, 0x36, 0xde, 0x03, 0x0c, 0xec, 0x4b, 0x66, 0x0a, 0x22, 0x22, 0x2e, 0x19, 0x36, 0x9b, - 0xc7, 0x82, 0x65, 0xac, 0xce, 0x48, 0x87, 0x6a, 0xd2, 0x8f, 0x2a, 0xdc, 0xc2, 0xe9, 0xd5, 0xf8, - 0x55, 0x84, 0x6d, 0xd3, 0xf5, 0x82, 0x25, 0xc5, 0xf4, 0x7b, 0x44, 0xb9, 0x40, 0x1f, 0x60, 0x3b, - 0xa4, 0x3c, 0x60, 0x3e, 0xa7, 0xd6, 0xfd, 0x3a, 0x6b, 0xa4, 0x7c, 0x79, 0x43, 0x2f, 0x73, 0xf5, - 0xdc, 0xbd, 0x8e, 0x7f, 0xb1, 0xbc, 0x26, 0x99, 0xee, 0x35, 0x45, 0xaf, 0xa1, 0x1a, 0xc4, 0x0a, - 0x7a, 0xb1, 0xad, 0x75, 0xea, 0xbd, 0xdd, 0x3b, 0xe5, 0x71, 0xca, 0x92, 0xaa, 0x0b, 0x77, 0xb9, - 0xb4, 0x22, 0x4e, 0x43, 0x9f, 0x78, 0x54, 0x2f, 0xb5, 0xb5, 0x4e, 0x0d, 0x37, 0x24, 0x78, 0x91, - 0x60, 0xa8, 0x03, 0x2d, 0x45, 0x62, 0x24, 0x12, 0x97, 0x16, 0xb7, 0x59, 0x40, 0xf5, 0xb2, 0xe2, - 0x35, 0x25, 0x3e, 0x91, 0xb0, 0x29, 0x51, 0x34, 0x85, 0x27, 0x59, 0x93, 0x36, 0xf3, 0x82, 0x90, - 0x72, 0xee, 0x32, 0x5f, 0xaf, 0x28, 0xaf, 0x07, 0x9b, 0xcd, 0x1c, 0xaf, 0x09, 0xca, 0xef, 0xe3, - 0xb4, 0x34, 0xf7, 0x80, 0xfa, 0xb0, 0xb3, 0xb6, 0xad, 0x36, 0xa1, 0x57, 0x95, 0x33, 0x7d, 0x53, - 0x6c, 0xbd, 0x29, 0xdc, 0xcc, 0x46, 0xa2, 0xee, 0xc6, 0x4f, 0x68, 0xa6, 0xab, 0x88, 0xf1, 0xfc, - 0x98, 0xb4, 0x7b, 0x8d, 0x69, 0x1f, 0x6a, 0xd9, 0x84, 0xe2, 0x4d, 0x67, 0x77, 0xf4, 0x02, 0xea, - 0xf9, 0xc1, 0x14, 0xd5, 0x33, 0xb0, 0x6c, 0x28, 0xc6, 0x08, 0xf6, 0x4c, 0x11, 0x52, 0xe2, 0xb9, - 0xbe, 0x33, 0xf4, 0x83, 0x48, 0x1c, 0x93, 0xe5, 0x32, 0x8d, 0xc5, 0x43, 0x5b, 0x31, 0xce, 0x61, - 0xff, 0x2e, 0xb5, 0xc4, 0xd9, 0x5b, 0x78, 0x46, 0x1c, 0x27, 0xa4, 0x0e, 0x11, 0x74, 0x6e, 0x25, - 0x35, 0x71, 0x5e, 0xe2, 0xe0, 0xee, 0xae, 0x9f, 0x13, 0x69, 0x19, 0x1c, 0x63, 0x08, 0x28, 0xd5, - 0x98, 0x92, 0x90, 0x78, 0x54, 0xd0, 0x50, 0x65, 0x3e, 0x57, 0xaa, 0xce, 0xd2, 0xae, 0xeb, 0x0b, - 0x1a, 0xfe, 0x20, 0x32, 0x35, 0x49, 0x0a, 0x21, 0x85, 0x2e, 0xb8, 0xf1, 0xbb, 0x90, 0xeb, 0x70, - 0x12, 0x89, 0x1b, 0x86, 0xff, 0xf5, 0x3b, 0xf8, 0x02, 0x59, 0x4e, 0xac, 0x20, 0x6b, 0x55, 0x2f, - 0xb4, 0x8b, 0x9d, 0x7a, 0xaf, 0xbd, 0xa9, 0x72, 0xdb, 0x12, 0x46, 0xe1, 0x6d, 0x9b, 0x0f, 0xfe, - 0x6a, 0xfe, 0xcb, 0x98, 0x8f, 0xe1, 0xf9, 0x9d, 0x63, 0xff, 0xcb, 0xcc, 0x1b, 0x9f, 0x61, 0x07, - 0x53, 0x9b, 0xf9, 0x3e, 0xb5, 0x85, 0x1a, 0x16, 0x47, 0xef, 0x40, 0xf7, 0xc8, 0x95, 0x15, 0xa6, - 0xb0, 0x35, 0x23, 0xf6, 0x37, 0xb6, 0x58, 0x58, 0x1e, 0x4f, 0xe3, 0xe5, 0x91, 0xab, 0xac, 0xea, - 0x28, 0x7e, 0x3d, 0xe3, 0xc6, 0x29, 0x6c, 0x67, 0xe8, 0xd0, 0x5f, 0x30, 0xf4, 0x14, 0x2a, 0x01, - 0xe1, 0x9c, 0xc6, 0xcd, 0xd4, 0x70, 0x72, 0x43, 0x07, 0x00, 0x39, 0x4d, 0xb9, 0xd4, 0x32, 0xde, - 0x9a, 0xa5, 0x3a, 0x87, 0x1f, 0xa1, 0x9e, 0x4b, 0x06, 0x6a, 0x41, 0xe3, 0x78, 0x72, 0x36, 0xc5, - 0x03, 0xd3, 0xec, 0x1f, 0x8d, 0x06, 0xad, 0x47, 0x08, 0x41, 0xf3, 0x62, 0xbc, 0x81, 0x69, 0x08, - 0xa0, 0x82, 0xfb, 0xe3, 0x93, 0xc9, 0x59, 0xab, 0x70, 0xd8, 0x83, 0x9d, 0x1b, 0xfb, 0x40, 0x35, - 0x28, 0x8d, 0x27, 0x63, 0x59, 0x5c, 0x83, 0xd2, 0xa7, 0xaf, 0xc3, 0x69, 0x4b, 0x43, 0x75, 0xa8, - 0x9e, 0x0c, 0x4e, 0x47, 0xfd, 0xf3, 0x41, 0xab, 0x30, 0xab, 0xa8, 0xbf, 0x9a, 0x37, 0x7f, 0x02, - 0x00, 0x00, 0xff, 0xff, 0xc2, 0x6a, 0xce, 0x1e, 0x7c, 0x06, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/messages.proto b/vendor/google.golang.org/grpc/benchmark/grpc_testing/messages.proto deleted file mode 100644 index bd83f095f..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/messages.proto +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Message definitions to be used by integration test service definitions. - -syntax = "proto3"; - -package grpc.testing; - -// The type of payload that should be returned. -enum PayloadType { - // Compressable text format. - COMPRESSABLE = 0; - - // Uncompressable binary format. - UNCOMPRESSABLE = 1; - - // Randomly chosen from all other formats defined in this enum. - RANDOM = 2; -} - -// Compression algorithms -enum CompressionType { - // No compression - NONE = 0; - GZIP = 1; - DEFLATE = 2; -} - -// A block of data, to simply increase gRPC message size. -message Payload { - // The type of data in body. - PayloadType type = 1; - // Primary contents of payload. - bytes body = 2; -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -message EchoStatus { - int32 code = 1; - string message = 2; -} - -// Unary request. -message SimpleRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - PayloadType response_type = 1; - - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 response_size = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; - - // Whether SimpleResponse should include username. - bool fill_username = 4; - - // Whether SimpleResponse should include OAuth scope. - bool fill_oauth_scope = 5; - - // Compression algorithm to be used by the server for the response (stream) - CompressionType response_compression = 6; - - // Whether server should return a given status - EchoStatus response_status = 7; -} - -// Unary response, as configured by the request. -message SimpleResponse { - // Payload to increase message size. - Payload payload = 1; - // The user the request came from, for verifying authentication was - // successful when the client expected it. - string username = 2; - // OAuth scope. - string oauth_scope = 3; -} - -// Client-streaming request. -message StreamingInputCallRequest { - // Optional input payload sent along with the request. - Payload payload = 1; - - // Not expecting any payload from the response. -} - -// Client-streaming response. -message StreamingInputCallResponse { - // Aggregated size of payloads received from the client. - int32 aggregated_payload_size = 1; -} - -// Configuration for a particular response. -message ResponseParameters { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 size = 1; - - // Desired interval between consecutive responses in the response stream in - // microseconds. - int32 interval_us = 2; -} - -// Server-streaming request. -message StreamingOutputCallRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - PayloadType response_type = 1; - - // Configuration for each expected response message. - repeated ResponseParameters response_parameters = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; - - // Compression algorithm to be used by the server for the response (stream) - CompressionType response_compression = 6; - - // Whether server should return a given status - EchoStatus response_status = 7; -} - -// Server-streaming response, as configured by the request and parameters. -message StreamingOutputCallResponse { - // Payload to increase response size. - Payload payload = 1; -} - -// For reconnect interop test only. -// Client tells server what reconnection parameters it used. -message ReconnectParams { - int32 max_reconnect_backoff_ms = 1; -} - -// For reconnect interop test only. -// Server tells client whether its reconnects are following the spec and the -// reconnect backoffs it saw. -message ReconnectInfo { - bool passed = 1; - repeated int32 backoff_ms = 2; -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/payloads.pb.go b/vendor/google.golang.org/grpc/benchmark/grpc_testing/payloads.pb.go deleted file mode 100644 index d70d1f745..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/payloads.pb.go +++ /dev/null @@ -1,250 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: payloads.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -type ByteBufferParams struct { - ReqSize int32 `protobuf:"varint,1,opt,name=req_size,json=reqSize" json:"req_size,omitempty"` - RespSize int32 `protobuf:"varint,2,opt,name=resp_size,json=respSize" json:"resp_size,omitempty"` -} - -func (m *ByteBufferParams) Reset() { *m = ByteBufferParams{} } -func (m *ByteBufferParams) String() string { return proto.CompactTextString(m) } -func (*ByteBufferParams) ProtoMessage() {} -func (*ByteBufferParams) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{0} } - -func (m *ByteBufferParams) GetReqSize() int32 { - if m != nil { - return m.ReqSize - } - return 0 -} - -func (m *ByteBufferParams) GetRespSize() int32 { - if m != nil { - return m.RespSize - } - return 0 -} - -type SimpleProtoParams struct { - ReqSize int32 `protobuf:"varint,1,opt,name=req_size,json=reqSize" json:"req_size,omitempty"` - RespSize int32 `protobuf:"varint,2,opt,name=resp_size,json=respSize" json:"resp_size,omitempty"` -} - -func (m *SimpleProtoParams) Reset() { *m = SimpleProtoParams{} } -func (m *SimpleProtoParams) String() string { return proto.CompactTextString(m) } -func (*SimpleProtoParams) ProtoMessage() {} -func (*SimpleProtoParams) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{1} } - -func (m *SimpleProtoParams) GetReqSize() int32 { - if m != nil { - return m.ReqSize - } - return 0 -} - -func (m *SimpleProtoParams) GetRespSize() int32 { - if m != nil { - return m.RespSize - } - return 0 -} - -type ComplexProtoParams struct { -} - -func (m *ComplexProtoParams) Reset() { *m = ComplexProtoParams{} } -func (m *ComplexProtoParams) String() string { return proto.CompactTextString(m) } -func (*ComplexProtoParams) ProtoMessage() {} -func (*ComplexProtoParams) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{2} } - -type PayloadConfig struct { - // Types that are valid to be assigned to Payload: - // *PayloadConfig_BytebufParams - // *PayloadConfig_SimpleParams - // *PayloadConfig_ComplexParams - Payload isPayloadConfig_Payload `protobuf_oneof:"payload"` -} - -func (m *PayloadConfig) Reset() { *m = PayloadConfig{} } -func (m *PayloadConfig) String() string { return proto.CompactTextString(m) } -func (*PayloadConfig) ProtoMessage() {} -func (*PayloadConfig) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{3} } - -type isPayloadConfig_Payload interface { - isPayloadConfig_Payload() -} - -type PayloadConfig_BytebufParams struct { - BytebufParams *ByteBufferParams `protobuf:"bytes,1,opt,name=bytebuf_params,json=bytebufParams,oneof"` -} -type PayloadConfig_SimpleParams struct { - SimpleParams *SimpleProtoParams `protobuf:"bytes,2,opt,name=simple_params,json=simpleParams,oneof"` -} -type PayloadConfig_ComplexParams struct { - ComplexParams *ComplexProtoParams `protobuf:"bytes,3,opt,name=complex_params,json=complexParams,oneof"` -} - -func (*PayloadConfig_BytebufParams) isPayloadConfig_Payload() {} -func (*PayloadConfig_SimpleParams) isPayloadConfig_Payload() {} -func (*PayloadConfig_ComplexParams) isPayloadConfig_Payload() {} - -func (m *PayloadConfig) GetPayload() isPayloadConfig_Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *PayloadConfig) GetBytebufParams() *ByteBufferParams { - if x, ok := m.GetPayload().(*PayloadConfig_BytebufParams); ok { - return x.BytebufParams - } - return nil -} - -func (m *PayloadConfig) GetSimpleParams() *SimpleProtoParams { - if x, ok := m.GetPayload().(*PayloadConfig_SimpleParams); ok { - return x.SimpleParams - } - return nil -} - -func (m *PayloadConfig) GetComplexParams() *ComplexProtoParams { - if x, ok := m.GetPayload().(*PayloadConfig_ComplexParams); ok { - return x.ComplexParams - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*PayloadConfig) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _PayloadConfig_OneofMarshaler, _PayloadConfig_OneofUnmarshaler, _PayloadConfig_OneofSizer, []interface{}{ - (*PayloadConfig_BytebufParams)(nil), - (*PayloadConfig_SimpleParams)(nil), - (*PayloadConfig_ComplexParams)(nil), - } -} - -func _PayloadConfig_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*PayloadConfig) - // payload - switch x := m.Payload.(type) { - case *PayloadConfig_BytebufParams: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.BytebufParams); err != nil { - return err - } - case *PayloadConfig_SimpleParams: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.SimpleParams); err != nil { - return err - } - case *PayloadConfig_ComplexParams: - b.EncodeVarint(3<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ComplexParams); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("PayloadConfig.Payload has unexpected type %T", x) - } - return nil -} - -func _PayloadConfig_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*PayloadConfig) - switch tag { - case 1: // payload.bytebuf_params - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ByteBufferParams) - err := b.DecodeMessage(msg) - m.Payload = &PayloadConfig_BytebufParams{msg} - return true, err - case 2: // payload.simple_params - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(SimpleProtoParams) - err := b.DecodeMessage(msg) - m.Payload = &PayloadConfig_SimpleParams{msg} - return true, err - case 3: // payload.complex_params - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ComplexProtoParams) - err := b.DecodeMessage(msg) - m.Payload = &PayloadConfig_ComplexParams{msg} - return true, err - default: - return false, nil - } -} - -func _PayloadConfig_OneofSizer(msg proto.Message) (n int) { - m := msg.(*PayloadConfig) - // payload - switch x := m.Payload.(type) { - case *PayloadConfig_BytebufParams: - s := proto.Size(x.BytebufParams) - n += proto.SizeVarint(1<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *PayloadConfig_SimpleParams: - s := proto.Size(x.SimpleParams) - n += proto.SizeVarint(2<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *PayloadConfig_ComplexParams: - s := proto.Size(x.ComplexParams) - n += proto.SizeVarint(3<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -func init() { - proto.RegisterType((*ByteBufferParams)(nil), "grpc.testing.ByteBufferParams") - proto.RegisterType((*SimpleProtoParams)(nil), "grpc.testing.SimpleProtoParams") - proto.RegisterType((*ComplexProtoParams)(nil), "grpc.testing.ComplexProtoParams") - proto.RegisterType((*PayloadConfig)(nil), "grpc.testing.PayloadConfig") -} - -func init() { proto.RegisterFile("payloads.proto", fileDescriptor2) } - -var fileDescriptor2 = []byte{ - // 254 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2b, 0x48, 0xac, 0xcc, - 0xc9, 0x4f, 0x4c, 0x29, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x49, 0x2f, 0x2a, 0x48, - 0xd6, 0x2b, 0x49, 0x2d, 0x2e, 0xc9, 0xcc, 0x4b, 0x57, 0xf2, 0xe2, 0x12, 0x70, 0xaa, 0x2c, 0x49, - 0x75, 0x2a, 0x4d, 0x4b, 0x4b, 0x2d, 0x0a, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0x16, 0x92, 0xe4, 0xe2, - 0x28, 0x4a, 0x2d, 0x8c, 0x2f, 0xce, 0xac, 0x4a, 0x95, 0x60, 0x54, 0x60, 0xd4, 0x60, 0x0d, 0x62, - 0x2f, 0x4a, 0x2d, 0x0c, 0xce, 0xac, 0x4a, 0x15, 0x92, 0xe6, 0xe2, 0x2c, 0x4a, 0x2d, 0x2e, 0x80, - 0xc8, 0x31, 0x81, 0xe5, 0x38, 0x40, 0x02, 0x20, 0x49, 0x25, 0x6f, 0x2e, 0xc1, 0xe0, 0xcc, 0xdc, - 0x82, 0x9c, 0xd4, 0x00, 0x90, 0x45, 0x14, 0x1a, 0x26, 0xc2, 0x25, 0xe4, 0x9c, 0x0f, 0x32, 0xac, - 0x02, 0xc9, 0x34, 0xa5, 0x6f, 0x8c, 0x5c, 0xbc, 0x01, 0x10, 0xff, 0x38, 0xe7, 0xe7, 0xa5, 0x65, - 0xa6, 0x0b, 0xb9, 0x73, 0xf1, 0x25, 0x55, 0x96, 0xa4, 0x26, 0x95, 0xa6, 0xc5, 0x17, 0x80, 0xd5, - 0x80, 0x6d, 0xe1, 0x36, 0x92, 0xd3, 0x43, 0xf6, 0xa7, 0x1e, 0xba, 0x27, 0x3d, 0x18, 0x82, 0x78, - 0xa1, 0xfa, 0xa0, 0x0e, 0x75, 0xe3, 0xe2, 0x2d, 0x06, 0xbb, 0x1e, 0x66, 0x0e, 0x13, 0xd8, 0x1c, - 0x79, 0x54, 0x73, 0x30, 0x3c, 0xe8, 0xc1, 0x10, 0xc4, 0x03, 0xd1, 0x07, 0x35, 0xc7, 0x93, 0x8b, - 0x2f, 0x19, 0xe2, 0x70, 0x98, 0x41, 0xcc, 0x60, 0x83, 0x14, 0x50, 0x0d, 0xc2, 0xf4, 0x1c, 0xc8, - 0x49, 0x50, 0x9d, 0x10, 0x01, 0x27, 0x4e, 0x2e, 0x76, 0x68, 0xe4, 0x25, 0xb1, 0x81, 0x23, 0xcf, - 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xb0, 0x8c, 0x18, 0x4e, 0xce, 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/payloads.proto b/vendor/google.golang.org/grpc/benchmark/grpc_testing/payloads.proto deleted file mode 100644 index 5d4871f5f..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/payloads.proto +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - -message ByteBufferParams { - int32 req_size = 1; - int32 resp_size = 2; -} - -message SimpleProtoParams { - int32 req_size = 1; - int32 resp_size = 2; -} - -message ComplexProtoParams { - // TODO (vpai): Fill this in once the details of complex, representative - // protos are decided -} - -message PayloadConfig { - oneof payload { - ByteBufferParams bytebuf_params = 1; - SimpleProtoParams simple_params = 2; - ComplexProtoParams complex_params = 3; - } -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/services.pb.go b/vendor/google.golang.org/grpc/benchmark/grpc_testing/services.pb.go deleted file mode 100644 index 50e350595..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/services.pb.go +++ /dev/null @@ -1,442 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: services.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for BenchmarkService service - -type BenchmarkServiceClient interface { - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // One request followed by one response. - // The server returns the client payload as-is. - StreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_StreamingCallClient, error) -} - -type benchmarkServiceClient struct { - cc *grpc.ClientConn -} - -func NewBenchmarkServiceClient(cc *grpc.ClientConn) BenchmarkServiceClient { - return &benchmarkServiceClient{cc} -} - -func (c *benchmarkServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := grpc.Invoke(ctx, "/grpc.testing.BenchmarkService/UnaryCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *benchmarkServiceClient) StreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_StreamingCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_BenchmarkService_serviceDesc.Streams[0], c.cc, "/grpc.testing.BenchmarkService/StreamingCall", opts...) - if err != nil { - return nil, err - } - x := &benchmarkServiceStreamingCallClient{stream} - return x, nil -} - -type BenchmarkService_StreamingCallClient interface { - Send(*SimpleRequest) error - Recv() (*SimpleResponse, error) - grpc.ClientStream -} - -type benchmarkServiceStreamingCallClient struct { - grpc.ClientStream -} - -func (x *benchmarkServiceStreamingCallClient) Send(m *SimpleRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *benchmarkServiceStreamingCallClient) Recv() (*SimpleResponse, error) { - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for BenchmarkService service - -type BenchmarkServiceServer interface { - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // One request followed by one response. - // The server returns the client payload as-is. - StreamingCall(BenchmarkService_StreamingCallServer) error -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BenchmarkServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.BenchmarkService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BenchmarkServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _BenchmarkService_StreamingCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(BenchmarkServiceServer).StreamingCall(&benchmarkServiceStreamingCallServer{stream}) -} - -type BenchmarkService_StreamingCallServer interface { - Send(*SimpleResponse) error - Recv() (*SimpleRequest, error) - grpc.ServerStream -} - -type benchmarkServiceStreamingCallServer struct { - grpc.ServerStream -} - -func (x *benchmarkServiceStreamingCallServer) Send(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *benchmarkServiceStreamingCallServer) Recv() (*SimpleRequest, error) { - m := new(SimpleRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _BenchmarkService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.BenchmarkService", - HandlerType: (*BenchmarkServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryCall", - Handler: _BenchmarkService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingCall", - Handler: _BenchmarkService_StreamingCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "services.proto", -} - -// Client API for WorkerService service - -type WorkerServiceClient interface { - // Start server with specified workload. - // First request sent specifies the ServerConfig followed by ServerStatus - // response. After that, a "Mark" can be sent anytime to request the latest - // stats. Closing the stream will initiate shutdown of the test server - // and once the shutdown has finished, the OK status is sent to terminate - // this RPC. - RunServer(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunServerClient, error) - // Start client with specified workload. - // First request sent specifies the ClientConfig followed by ClientStatus - // response. After that, a "Mark" can be sent anytime to request the latest - // stats. Closing the stream will initiate shutdown of the test client - // and once the shutdown has finished, the OK status is sent to terminate - // this RPC. - RunClient(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunClientClient, error) - // Just return the core count - unary call - CoreCount(ctx context.Context, in *CoreRequest, opts ...grpc.CallOption) (*CoreResponse, error) - // Quit this worker - QuitWorker(ctx context.Context, in *Void, opts ...grpc.CallOption) (*Void, error) -} - -type workerServiceClient struct { - cc *grpc.ClientConn -} - -func NewWorkerServiceClient(cc *grpc.ClientConn) WorkerServiceClient { - return &workerServiceClient{cc} -} - -func (c *workerServiceClient) RunServer(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunServerClient, error) { - stream, err := grpc.NewClientStream(ctx, &_WorkerService_serviceDesc.Streams[0], c.cc, "/grpc.testing.WorkerService/RunServer", opts...) - if err != nil { - return nil, err - } - x := &workerServiceRunServerClient{stream} - return x, nil -} - -type WorkerService_RunServerClient interface { - Send(*ServerArgs) error - Recv() (*ServerStatus, error) - grpc.ClientStream -} - -type workerServiceRunServerClient struct { - grpc.ClientStream -} - -func (x *workerServiceRunServerClient) Send(m *ServerArgs) error { - return x.ClientStream.SendMsg(m) -} - -func (x *workerServiceRunServerClient) Recv() (*ServerStatus, error) { - m := new(ServerStatus) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *workerServiceClient) RunClient(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunClientClient, error) { - stream, err := grpc.NewClientStream(ctx, &_WorkerService_serviceDesc.Streams[1], c.cc, "/grpc.testing.WorkerService/RunClient", opts...) - if err != nil { - return nil, err - } - x := &workerServiceRunClientClient{stream} - return x, nil -} - -type WorkerService_RunClientClient interface { - Send(*ClientArgs) error - Recv() (*ClientStatus, error) - grpc.ClientStream -} - -type workerServiceRunClientClient struct { - grpc.ClientStream -} - -func (x *workerServiceRunClientClient) Send(m *ClientArgs) error { - return x.ClientStream.SendMsg(m) -} - -func (x *workerServiceRunClientClient) Recv() (*ClientStatus, error) { - m := new(ClientStatus) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *workerServiceClient) CoreCount(ctx context.Context, in *CoreRequest, opts ...grpc.CallOption) (*CoreResponse, error) { - out := new(CoreResponse) - err := grpc.Invoke(ctx, "/grpc.testing.WorkerService/CoreCount", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *workerServiceClient) QuitWorker(ctx context.Context, in *Void, opts ...grpc.CallOption) (*Void, error) { - out := new(Void) - err := grpc.Invoke(ctx, "/grpc.testing.WorkerService/QuitWorker", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for WorkerService service - -type WorkerServiceServer interface { - // Start server with specified workload. - // First request sent specifies the ServerConfig followed by ServerStatus - // response. After that, a "Mark" can be sent anytime to request the latest - // stats. Closing the stream will initiate shutdown of the test server - // and once the shutdown has finished, the OK status is sent to terminate - // this RPC. - RunServer(WorkerService_RunServerServer) error - // Start client with specified workload. - // First request sent specifies the ClientConfig followed by ClientStatus - // response. After that, a "Mark" can be sent anytime to request the latest - // stats. Closing the stream will initiate shutdown of the test client - // and once the shutdown has finished, the OK status is sent to terminate - // this RPC. - RunClient(WorkerService_RunClientServer) error - // Just return the core count - unary call - CoreCount(context.Context, *CoreRequest) (*CoreResponse, error) - // Quit this worker - QuitWorker(context.Context, *Void) (*Void, error) -} - -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 { - Send(*ServerStatus) error - Recv() (*ServerArgs, error) - grpc.ServerStream -} - -type workerServiceRunServerServer struct { - grpc.ServerStream -} - -func (x *workerServiceRunServerServer) Send(m *ServerStatus) error { - return x.ServerStream.SendMsg(m) -} - -func (x *workerServiceRunServerServer) Recv() (*ServerArgs, error) { - m := new(ServerArgs) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _WorkerService_RunClient_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(WorkerServiceServer).RunClient(&workerServiceRunClientServer{stream}) -} - -type WorkerService_RunClientServer interface { - Send(*ClientStatus) error - Recv() (*ClientArgs, error) - grpc.ServerStream -} - -type workerServiceRunClientServer struct { - grpc.ServerStream -} - -func (x *workerServiceRunClientServer) Send(m *ClientStatus) error { - return x.ServerStream.SendMsg(m) -} - -func (x *workerServiceRunClientServer) Recv() (*ClientArgs, error) { - m := new(ClientArgs) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _WorkerService_CoreCount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CoreRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(WorkerServiceServer).CoreCount(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.WorkerService/CoreCount", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(WorkerServiceServer).CoreCount(ctx, req.(*CoreRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _WorkerService_QuitWorker_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Void) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(WorkerServiceServer).QuitWorker(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.WorkerService/QuitWorker", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(WorkerServiceServer).QuitWorker(ctx, req.(*Void)) - } - return interceptor(ctx, in, info, handler) -} - -var _WorkerService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.WorkerService", - HandlerType: (*WorkerServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CoreCount", - Handler: _WorkerService_CoreCount_Handler, - }, - { - 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: "services.proto", -} - -func init() { proto.RegisterFile("services.proto", fileDescriptor3) } - -var fileDescriptor3 = []byte{ - // 255 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x91, 0xc1, 0x4a, 0xc4, 0x30, - 0x10, 0x86, 0xa9, 0x07, 0xa1, 0xc1, 0x2e, 0x92, 0x93, 0x46, 0x1f, 0xc0, 0x53, 0x91, 0xd5, 0x17, - 0x70, 0x8b, 0x1e, 0x05, 0xb7, 0xa8, 0xe7, 0x58, 0x87, 0x1a, 0x36, 0xcd, 0xd4, 0x99, 0x89, 0xe0, - 0x93, 0xf8, 0x0e, 0x3e, 0xa5, 0xec, 0x66, 0x57, 0xd6, 0x92, 0x9b, 0xc7, 0xf9, 0xbf, 0xe1, 0x23, - 0x7f, 0x46, 0xcd, 0x18, 0xe8, 0xc3, 0x75, 0xc0, 0xf5, 0x48, 0x28, 0xa8, 0x8f, 0x7a, 0x1a, 0xbb, - 0x5a, 0x80, 0xc5, 0x85, 0xde, 0xcc, 0x06, 0x60, 0xb6, 0xfd, 0x8e, 0x9a, 0xaa, 0xc3, 0x20, 0x84, - 0x3e, 0x8d, 0xf3, 0xef, 0x42, 0x1d, 0x2f, 0x20, 0x74, 0x6f, 0x83, 0xa5, 0x55, 0x9b, 0x44, 0xfa, - 0x4e, 0x95, 0x8f, 0xc1, 0xd2, 0x67, 0x63, 0xbd, 0xd7, 0x67, 0xf5, 0xbe, 0xaf, 0x6e, 0xdd, 0x30, - 0x7a, 0x58, 0xc2, 0x7b, 0x04, 0x16, 0x73, 0x9e, 0x87, 0x3c, 0x62, 0x60, 0xd0, 0xf7, 0xaa, 0x6a, - 0x85, 0xc0, 0x0e, 0x2e, 0xf4, 0xff, 0x74, 0x5d, 0x14, 0x97, 0xc5, 0xfc, 0xeb, 0x40, 0x55, 0xcf, - 0x48, 0x2b, 0xa0, 0xdd, 0x4b, 0x6f, 0x55, 0xb9, 0x8c, 0x61, 0x3d, 0x01, 0xe9, 0x93, 0x89, 0x60, - 0x93, 0xde, 0x50, 0xcf, 0xc6, 0xe4, 0x48, 0x2b, 0x56, 0x22, 0xaf, 0xc5, 0x5b, 0x4d, 0xe3, 0x1d, - 0x04, 0x99, 0x6a, 0x52, 0x9a, 0xd3, 0x24, 0xb2, 0xa7, 0x59, 0xa8, 0xb2, 0x41, 0x82, 0x06, 0x63, - 0x10, 0x7d, 0x3a, 0x59, 0x46, 0xfa, 0x6d, 0x6a, 0x72, 0x68, 0xfb, 0x67, 0xd7, 0x4a, 0x3d, 0x44, - 0x27, 0xa9, 0xa6, 0xd6, 0x7f, 0x37, 0x9f, 0xd0, 0xbd, 0x9a, 0x4c, 0xf6, 0x72, 0xb8, 0xb9, 0xe6, - 0xd5, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3b, 0x84, 0x02, 0xe3, 0x0c, 0x02, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/services.proto b/vendor/google.golang.org/grpc/benchmark/grpc_testing/services.proto deleted file mode 100644 index f4e790782..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/services.proto +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An integration test service that covers all the method signature permutations -// of unary/streaming requests/responses. -syntax = "proto3"; - -import "messages.proto"; -import "control.proto"; - -package grpc.testing; - -service BenchmarkService { - // One request followed by one response. - // The server returns the client payload as-is. - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // One request followed by one response. - // The server returns the client payload as-is. - rpc StreamingCall(stream SimpleRequest) returns (stream SimpleResponse); -} - -service WorkerService { - // Start server with specified workload. - // First request sent specifies the ServerConfig followed by ServerStatus - // response. After that, a "Mark" can be sent anytime to request the latest - // stats. Closing the stream will initiate shutdown of the test server - // and once the shutdown has finished, the OK status is sent to terminate - // this RPC. - rpc RunServer(stream ServerArgs) returns (stream ServerStatus); - - // Start client with specified workload. - // First request sent specifies the ClientConfig followed by ClientStatus - // response. After that, a "Mark" can be sent anytime to request the latest - // stats. Closing the stream will initiate shutdown of the test client - // and once the shutdown has finished, the OK status is sent to terminate - // this RPC. - rpc RunClient(stream ClientArgs) returns (stream ClientStatus); - - // Just return the core count - unary call - rpc CoreCount(CoreRequest) returns (CoreResponse); - - // Quit this worker - rpc QuitWorker(Void) returns (Void); -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/stats.pb.go b/vendor/google.golang.org/grpc/benchmark/grpc_testing/stats.pb.go deleted file mode 100644 index d69cb7410..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/stats.pb.go +++ /dev/null @@ -1,208 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: stats.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -type ServerStats struct { - // wall clock time change in seconds since last reset - TimeElapsed float64 `protobuf:"fixed64,1,opt,name=time_elapsed,json=timeElapsed" json:"time_elapsed,omitempty"` - // change in user time (in seconds) used by the server since last reset - TimeUser float64 `protobuf:"fixed64,2,opt,name=time_user,json=timeUser" json:"time_user,omitempty"` - // change in server time (in seconds) used by the server process and all - // threads since last reset - TimeSystem float64 `protobuf:"fixed64,3,opt,name=time_system,json=timeSystem" json:"time_system,omitempty"` -} - -func (m *ServerStats) Reset() { *m = ServerStats{} } -func (m *ServerStats) String() string { return proto.CompactTextString(m) } -func (*ServerStats) ProtoMessage() {} -func (*ServerStats) Descriptor() ([]byte, []int) { return fileDescriptor4, []int{0} } - -func (m *ServerStats) GetTimeElapsed() float64 { - if m != nil { - return m.TimeElapsed - } - return 0 -} - -func (m *ServerStats) GetTimeUser() float64 { - if m != nil { - return m.TimeUser - } - return 0 -} - -func (m *ServerStats) GetTimeSystem() float64 { - if m != nil { - return m.TimeSystem - } - return 0 -} - -// Histogram params based on grpc/support/histogram.c -type HistogramParams struct { - Resolution float64 `protobuf:"fixed64,1,opt,name=resolution" json:"resolution,omitempty"` - MaxPossible float64 `protobuf:"fixed64,2,opt,name=max_possible,json=maxPossible" json:"max_possible,omitempty"` -} - -func (m *HistogramParams) Reset() { *m = HistogramParams{} } -func (m *HistogramParams) String() string { return proto.CompactTextString(m) } -func (*HistogramParams) ProtoMessage() {} -func (*HistogramParams) Descriptor() ([]byte, []int) { return fileDescriptor4, []int{1} } - -func (m *HistogramParams) GetResolution() float64 { - if m != nil { - return m.Resolution - } - return 0 -} - -func (m *HistogramParams) GetMaxPossible() float64 { - if m != nil { - return m.MaxPossible - } - return 0 -} - -// Histogram data based on grpc/support/histogram.c -type HistogramData struct { - Bucket []uint32 `protobuf:"varint,1,rep,packed,name=bucket" json:"bucket,omitempty"` - MinSeen float64 `protobuf:"fixed64,2,opt,name=min_seen,json=minSeen" json:"min_seen,omitempty"` - MaxSeen float64 `protobuf:"fixed64,3,opt,name=max_seen,json=maxSeen" json:"max_seen,omitempty"` - Sum float64 `protobuf:"fixed64,4,opt,name=sum" json:"sum,omitempty"` - SumOfSquares float64 `protobuf:"fixed64,5,opt,name=sum_of_squares,json=sumOfSquares" json:"sum_of_squares,omitempty"` - Count float64 `protobuf:"fixed64,6,opt,name=count" json:"count,omitempty"` -} - -func (m *HistogramData) Reset() { *m = HistogramData{} } -func (m *HistogramData) String() string { return proto.CompactTextString(m) } -func (*HistogramData) ProtoMessage() {} -func (*HistogramData) Descriptor() ([]byte, []int) { return fileDescriptor4, []int{2} } - -func (m *HistogramData) GetBucket() []uint32 { - if m != nil { - return m.Bucket - } - return nil -} - -func (m *HistogramData) GetMinSeen() float64 { - if m != nil { - return m.MinSeen - } - return 0 -} - -func (m *HistogramData) GetMaxSeen() float64 { - if m != nil { - return m.MaxSeen - } - return 0 -} - -func (m *HistogramData) GetSum() float64 { - if m != nil { - return m.Sum - } - return 0 -} - -func (m *HistogramData) GetSumOfSquares() float64 { - if m != nil { - return m.SumOfSquares - } - return 0 -} - -func (m *HistogramData) GetCount() float64 { - if m != nil { - return m.Count - } - return 0 -} - -type ClientStats struct { - // Latency histogram. Data points are in nanoseconds. - Latencies *HistogramData `protobuf:"bytes,1,opt,name=latencies" json:"latencies,omitempty"` - // See ServerStats for details. - TimeElapsed float64 `protobuf:"fixed64,2,opt,name=time_elapsed,json=timeElapsed" json:"time_elapsed,omitempty"` - TimeUser float64 `protobuf:"fixed64,3,opt,name=time_user,json=timeUser" json:"time_user,omitempty"` - TimeSystem float64 `protobuf:"fixed64,4,opt,name=time_system,json=timeSystem" json:"time_system,omitempty"` -} - -func (m *ClientStats) Reset() { *m = ClientStats{} } -func (m *ClientStats) String() string { return proto.CompactTextString(m) } -func (*ClientStats) ProtoMessage() {} -func (*ClientStats) Descriptor() ([]byte, []int) { return fileDescriptor4, []int{3} } - -func (m *ClientStats) GetLatencies() *HistogramData { - if m != nil { - return m.Latencies - } - return nil -} - -func (m *ClientStats) GetTimeElapsed() float64 { - if m != nil { - return m.TimeElapsed - } - return 0 -} - -func (m *ClientStats) GetTimeUser() float64 { - if m != nil { - return m.TimeUser - } - return 0 -} - -func (m *ClientStats) GetTimeSystem() float64 { - if m != nil { - return m.TimeSystem - } - return 0 -} - -func init() { - proto.RegisterType((*ServerStats)(nil), "grpc.testing.ServerStats") - proto.RegisterType((*HistogramParams)(nil), "grpc.testing.HistogramParams") - proto.RegisterType((*HistogramData)(nil), "grpc.testing.HistogramData") - proto.RegisterType((*ClientStats)(nil), "grpc.testing.ClientStats") -} - -func init() { proto.RegisterFile("stats.proto", fileDescriptor4) } - -var fileDescriptor4 = []byte{ - // 341 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x92, 0xc1, 0x4a, 0xeb, 0x40, - 0x14, 0x86, 0x49, 0xd3, 0xf6, 0xb6, 0x27, 0xed, 0xbd, 0x97, 0x41, 0x24, 0x52, 0xd0, 0x1a, 0x5c, - 0x74, 0x95, 0x85, 0xae, 0x5c, 0xab, 0xe0, 0xce, 0xd2, 0xe8, 0x3a, 0x4c, 0xe3, 0x69, 0x19, 0xcc, - 0xcc, 0xc4, 0x39, 0x33, 0x12, 0x1f, 0x49, 0x7c, 0x49, 0xc9, 0x24, 0x68, 0x55, 0xd0, 0x5d, 0xe6, - 0xfb, 0x7e, 0xe6, 0xe4, 0xe4, 0x0f, 0x44, 0x64, 0xb9, 0xa5, 0xb4, 0x32, 0xda, 0x6a, 0x36, 0xd9, - 0x9a, 0xaa, 0x48, 0x2d, 0x92, 0x15, 0x6a, 0x9b, 0x28, 0x88, 0x32, 0x34, 0x4f, 0x68, 0xb2, 0x26, - 0xc2, 0x8e, 0x61, 0x62, 0x85, 0xc4, 0x1c, 0x4b, 0x5e, 0x11, 0xde, 0xc7, 0xc1, 0x3c, 0x58, 0x04, - 0xab, 0xa8, 0x61, 0x57, 0x2d, 0x62, 0x33, 0x18, 0xfb, 0x88, 0x23, 0x34, 0x71, 0xcf, 0xfb, 0x51, - 0x03, 0xee, 0x08, 0x0d, 0x3b, 0x02, 0x9f, 0xcd, 0xe9, 0x99, 0x2c, 0xca, 0x38, 0xf4, 0x1a, 0x1a, - 0x94, 0x79, 0x92, 0xdc, 0xc2, 0xbf, 0x6b, 0x41, 0x56, 0x6f, 0x0d, 0x97, 0x4b, 0x6e, 0xb8, 0x24, - 0x76, 0x08, 0x60, 0x90, 0x74, 0xe9, 0xac, 0xd0, 0xaa, 0x9b, 0xb8, 0x43, 0x9a, 0x77, 0x92, 0xbc, - 0xce, 0x2b, 0x4d, 0x24, 0xd6, 0x25, 0x76, 0x33, 0x23, 0xc9, 0xeb, 0x65, 0x87, 0x92, 0xd7, 0x00, - 0xa6, 0xef, 0xd7, 0x5e, 0x72, 0xcb, 0xd9, 0x3e, 0x0c, 0xd7, 0xae, 0x78, 0x40, 0x1b, 0x07, 0xf3, - 0x70, 0x31, 0x5d, 0x75, 0x27, 0x76, 0x00, 0x23, 0x29, 0x54, 0x4e, 0x88, 0xaa, 0xbb, 0xe8, 0x8f, - 0x14, 0x2a, 0x43, 0x54, 0x5e, 0xf1, 0xba, 0x55, 0x61, 0xa7, 0x78, 0xed, 0xd5, 0x7f, 0x08, 0xc9, - 0xc9, 0xb8, 0xef, 0x69, 0xf3, 0xc8, 0x4e, 0xe0, 0x2f, 0x39, 0x99, 0xeb, 0x4d, 0x4e, 0x8f, 0x8e, - 0x1b, 0xa4, 0x78, 0xe0, 0xe5, 0x84, 0x9c, 0xbc, 0xd9, 0x64, 0x2d, 0x63, 0x7b, 0x30, 0x28, 0xb4, - 0x53, 0x36, 0x1e, 0x7a, 0xd9, 0x1e, 0x92, 0x97, 0x00, 0xa2, 0x8b, 0x52, 0xa0, 0xb2, 0xed, 0x47, - 0x3f, 0x87, 0x71, 0xc9, 0x2d, 0xaa, 0x42, 0x20, 0xf9, 0xfd, 0xa3, 0xd3, 0x59, 0xba, 0xdb, 0x52, - 0xfa, 0x69, 0xb7, 0xd5, 0x47, 0xfa, 0x5b, 0x5f, 0xbd, 0x5f, 0xfa, 0x0a, 0x7f, 0xee, 0xab, 0xff, - 0xb5, 0xaf, 0xf5, 0xd0, 0xff, 0x34, 0x67, 0x6f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xea, 0x75, 0x34, - 0x90, 0x43, 0x02, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/benchmark/grpc_testing/stats.proto b/vendor/google.golang.org/grpc/benchmark/grpc_testing/stats.proto deleted file mode 100644 index baf3610f3..000000000 --- a/vendor/google.golang.org/grpc/benchmark/grpc_testing/stats.proto +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - -message ServerStats { - // wall clock time change in seconds since last reset - double time_elapsed = 1; - - // change in user time (in seconds) used by the server since last reset - double time_user = 2; - - // change in server time (in seconds) used by the server process and all - // threads since last reset - double time_system = 3; -} - -// Histogram params based on grpc/support/histogram.c -message HistogramParams { - double resolution = 1; // first bucket is [0, 1 + resolution) - double max_possible = 2; // use enough buckets to allow this value -} - -// Histogram data based on grpc/support/histogram.c -message HistogramData { - repeated uint32 bucket = 1; - double min_seen = 2; - double max_seen = 3; - double sum = 4; - double sum_of_squares = 5; - double count = 6; -} - -message ClientStats { - // Latency histogram. Data points are in nanoseconds. - HistogramData latencies = 1; - - // See ServerStats for details. - double time_elapsed = 2; - double time_user = 3; - double time_system = 4; -} diff --git a/vendor/google.golang.org/grpc/benchmark/latency/latency.go b/vendor/google.golang.org/grpc/benchmark/latency/latency.go deleted file mode 100644 index 5839a5c44..000000000 --- a/vendor/google.golang.org/grpc/benchmark/latency/latency.go +++ /dev/null @@ -1,316 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package latency provides wrappers for net.Conn, net.Listener, and -// net.Dialers, designed to interoperate to inject real-world latency into -// network connections. -package latency - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" - "net" - "time" - - "golang.org/x/net/context" -) - -// Dialer is a function matching the signature of net.Dial. -type Dialer func(network, address string) (net.Conn, error) - -// TimeoutDialer is a function matching the signature of net.DialTimeout. -type TimeoutDialer func(network, address string, timeout time.Duration) (net.Conn, error) - -// ContextDialer is a function matching the signature of -// net.Dialer.DialContext. -type ContextDialer func(ctx context.Context, network, address string) (net.Conn, error) - -// Network represents a network with the given bandwidth, latency, and MTU -// (Maximum Transmission Unit) configuration, and can produce wrappers of -// net.Listeners, net.Conn, and various forms of dialing functions. The -// Listeners and Dialers/Conns on both sides of connections must come from this -// package, but need not be created from the same Network. Latency is computed -// when sending (in Write), and is injected when receiving (in Read). This -// allows senders' Write calls to be non-blocking, as in real-world -// applications. -// -// Note: Latency is injected by the sender specifying the absolute time data -// should be available, and the reader delaying until that time arrives to -// provide the data. This package attempts to counter-act the effects of clock -// drift and existing network latency by measuring the delay between the -// sender's transmission time and the receiver's reception time during startup. -// No attempt is made to measure the existing bandwidth of the connection. -type Network struct { - Kbps int // Kilobits per second; if non-positive, infinite - Latency time.Duration // One-way latency (sending); if non-positive, no delay - MTU int // Bytes per packet; if non-positive, infinite -} - -var ( - //Local simulates local network. - Local = Network{0, 0, 0} - //LAN simulates local area network network. - LAN = Network{100 * 1024, 2 * time.Millisecond, 1500} - //WAN simulates wide area network. - WAN = Network{20 * 1024, 30 * time.Millisecond, 1500} - //Longhaul simulates bad network. - Longhaul = Network{1000 * 1024, 200 * time.Millisecond, 9000} -) - -// Conn returns a net.Conn that wraps c and injects n's latency into that -// connection. This function also imposes latency for connection creation. -// If n's Latency is lower than the measured latency in c, an error is -// returned. -func (n *Network) Conn(c net.Conn) (net.Conn, error) { - start := now() - nc := &conn{Conn: c, network: n, readBuf: new(bytes.Buffer)} - if err := nc.sync(); err != nil { - return nil, err - } - sleep(start.Add(nc.delay).Sub(now())) - return nc, nil -} - -type conn struct { - net.Conn - network *Network - - readBuf *bytes.Buffer // one packet worth of data received - lastSendEnd time.Time // time the previous Write should be fully on the wire - delay time.Duration // desired latency - measured latency -} - -// header is sent before all data transmitted by the application. -type header struct { - ReadTime int64 // Time the reader is allowed to read this packet (UnixNano) - Sz int32 // Size of the data in the packet -} - -func (c *conn) Write(p []byte) (n int, err error) { - tNow := now() - if c.lastSendEnd.Before(tNow) { - c.lastSendEnd = tNow - } - for len(p) > 0 { - pkt := p - if c.network.MTU > 0 && len(pkt) > c.network.MTU { - pkt = pkt[:c.network.MTU] - p = p[c.network.MTU:] - } else { - p = nil - } - if c.network.Kbps > 0 { - if congestion := c.lastSendEnd.Sub(tNow) - c.delay; congestion > 0 { - // The network is full; sleep until this packet can be sent. - sleep(congestion) - tNow = tNow.Add(congestion) - } - } - c.lastSendEnd = c.lastSendEnd.Add(c.network.pktTime(len(pkt))) - hdr := header{ReadTime: c.lastSendEnd.Add(c.delay).UnixNano(), Sz: int32(len(pkt))} - if err := binary.Write(c.Conn, binary.BigEndian, hdr); err != nil { - return n, err - } - x, err := c.Conn.Write(pkt) - n += x - if err != nil { - return n, err - } - } - return n, nil -} - -func (c *conn) Read(p []byte) (n int, err error) { - if c.readBuf.Len() == 0 { - var hdr header - if err := binary.Read(c.Conn, binary.BigEndian, &hdr); err != nil { - return 0, err - } - defer func() { sleep(time.Unix(0, hdr.ReadTime).Sub(now())) }() - - if _, err := io.CopyN(c.readBuf, c.Conn, int64(hdr.Sz)); err != nil { - return 0, err - } - } - // Read from readBuf. - return c.readBuf.Read(p) -} - -// sync does a handshake and then measures the latency on the network in -// coordination with the other side. -func (c *conn) sync() error { - const ( - pingMsg = "syncPing" - warmup = 10 // minimum number of iterations to measure latency - giveUp = 50 // maximum number of iterations to measure latency - accuracy = time.Millisecond // req'd accuracy to stop early - goodRun = 3 // stop early if latency within accuracy this many times - ) - - type syncMsg struct { - SendT int64 // Time sent. If zero, stop. - RecvT int64 // Time received. If zero, fill in and respond. - } - - // A trivial handshake - if err := binary.Write(c.Conn, binary.BigEndian, []byte(pingMsg)); err != nil { - return err - } - var ping [8]byte - if err := binary.Read(c.Conn, binary.BigEndian, &ping); err != nil { - return err - } else if string(ping[:]) != pingMsg { - return fmt.Errorf("malformed handshake message: %v (want %q)", ping, pingMsg) - } - - // Both sides are alive and syncing. Calculate network delay / clock skew. - att := 0 - good := 0 - var latency time.Duration - localDone, remoteDone := false, false - send := true - for !localDone || !remoteDone { - if send { - if err := binary.Write(c.Conn, binary.BigEndian, syncMsg{SendT: now().UnixNano()}); err != nil { - return err - } - att++ - send = false - } - - // Block until we get a syncMsg - m := syncMsg{} - if err := binary.Read(c.Conn, binary.BigEndian, &m); err != nil { - return err - } - - if m.RecvT == 0 { - // Message initiated from other side. - if m.SendT == 0 { - remoteDone = true - continue - } - // Send response. - m.RecvT = now().UnixNano() - if err := binary.Write(c.Conn, binary.BigEndian, m); err != nil { - return err - } - continue - } - - lag := time.Duration(m.RecvT - m.SendT) - latency += lag - avgLatency := latency / time.Duration(att) - if e := lag - avgLatency; e > -accuracy && e < accuracy { - good++ - } else { - good = 0 - } - if att < giveUp && (att < warmup || good < goodRun) { - send = true - continue - } - localDone = true - latency = avgLatency - // Tell the other side we're done. - if err := binary.Write(c.Conn, binary.BigEndian, syncMsg{}); err != nil { - return err - } - } - if c.network.Latency <= 0 { - return nil - } - c.delay = c.network.Latency - latency - if c.delay < 0 { - return fmt.Errorf("measured network latency (%v) higher than desired latency (%v)", latency, c.network.Latency) - } - return nil -} - -// Listener returns a net.Listener that wraps l and injects n's latency in its -// connections. -func (n *Network) Listener(l net.Listener) net.Listener { - return &listener{Listener: l, network: n} -} - -type listener struct { - net.Listener - network *Network -} - -func (l *listener) Accept() (net.Conn, error) { - c, err := l.Listener.Accept() - if err != nil { - return nil, err - } - return l.network.Conn(c) -} - -// Dialer returns a Dialer that wraps d and injects n's latency in its -// connections. n's Latency is also injected to the connection's creation. -func (n *Network) Dialer(d Dialer) Dialer { - return func(network, address string) (net.Conn, error) { - conn, err := d(network, address) - if err != nil { - return nil, err - } - return n.Conn(conn) - } -} - -// TimeoutDialer returns a TimeoutDialer that wraps d and injects n's latency -// in its connections. n's Latency is also injected to the connection's -// creation. -func (n *Network) TimeoutDialer(d TimeoutDialer) TimeoutDialer { - return func(network, address string, timeout time.Duration) (net.Conn, error) { - conn, err := d(network, address, timeout) - if err != nil { - return nil, err - } - return n.Conn(conn) - } -} - -// ContextDialer returns a ContextDialer that wraps d and injects n's latency -// in its connections. n's Latency is also injected to the connection's -// creation. -func (n *Network) ContextDialer(d ContextDialer) ContextDialer { - return func(ctx context.Context, network, address string) (net.Conn, error) { - conn, err := d(ctx, network, address) - if err != nil { - return nil, err - } - return n.Conn(conn) - } -} - -// pktTime returns the time it takes to transmit one packet of data of size b -// in bytes. -func (n *Network) pktTime(b int) time.Duration { - if n.Kbps <= 0 { - return time.Duration(0) - } - return time.Duration(b) * time.Second / time.Duration(n.Kbps*(1024/8)) -} - -// Wrappers for testing - -var now = time.Now -var sleep = time.Sleep diff --git a/vendor/google.golang.org/grpc/benchmark/latency/latency_test.go b/vendor/google.golang.org/grpc/benchmark/latency/latency_test.go deleted file mode 100644 index 2298b1360..000000000 --- a/vendor/google.golang.org/grpc/benchmark/latency/latency_test.go +++ /dev/null @@ -1,353 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package latency - -import ( - "bytes" - "fmt" - "net" - "reflect" - "sync" - "testing" - "time" -) - -// bufConn is a net.Conn implemented by a bytes.Buffer (which is a ReadWriter). -type bufConn struct { - *bytes.Buffer -} - -func (bufConn) Close() error { panic("unimplemented") } -func (bufConn) LocalAddr() net.Addr { panic("unimplemented") } -func (bufConn) RemoteAddr() net.Addr { panic("unimplemented") } -func (bufConn) SetDeadline(t time.Time) error { panic("unimplemneted") } -func (bufConn) SetReadDeadline(t time.Time) error { panic("unimplemneted") } -func (bufConn) SetWriteDeadline(t time.Time) error { panic("unimplemneted") } - -func restoreHooks() func() { - s := sleep - n := now - return func() { - sleep = s - now = n - } -} - -func TestConn(t *testing.T) { - defer restoreHooks()() - - // Constant time. - now = func() time.Time { return time.Unix(123, 456) } - - // Capture sleep times for checking later. - var sleepTimes []time.Duration - sleep = func(t time.Duration) { sleepTimes = append(sleepTimes, t) } - - wantSleeps := func(want ...time.Duration) { - if !reflect.DeepEqual(want, sleepTimes) { - t.Fatalf("sleepTimes = %v; want %v", sleepTimes, want) - } - sleepTimes = nil - } - - // Use a fairly high latency to cause a large BDP and avoid sleeps while - // writing due to simulation of full buffers. - latency := 1 * time.Second - c, err := (&Network{Kbps: 1, Latency: latency, MTU: 5}).Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - wantSleeps(latency) // Connection creation delay. - - // 1 kbps = 128 Bps. Divides evenly by 1 second using nanos. - byteLatency := time.Duration(time.Second / 128) - - write := func(b []byte) { - n, err := c.Write(b) - if n != len(b) || err != nil { - t.Fatalf("c.Write(%v) = %v, %v; want %v, nil", b, n, err, len(b)) - } - } - - write([]byte{1, 2, 3, 4, 5}) // One full packet - pkt1Time := latency + byteLatency*5 - write([]byte{6}) // One partial packet - pkt2Time := pkt1Time + byteLatency - write([]byte{7, 8, 9, 10, 11, 12, 13}) // Two packets - pkt3Time := pkt2Time + byteLatency*5 - pkt4Time := pkt3Time + byteLatency*2 - - // No reads, so no sleeps yet. - wantSleeps() - - read := func(n int, want []byte) { - b := make([]byte, n) - if rd, err := c.Read(b); err != nil || rd != len(want) { - t.Fatalf("c.Read(<%v bytes>) = %v, %v; want %v, nil", n, rd, err, len(want)) - } - if !reflect.DeepEqual(b[:len(want)], want) { - t.Fatalf("read %v; want %v", b, want) - } - } - - read(1, []byte{1}) - wantSleeps(pkt1Time) - read(1, []byte{2}) - wantSleeps() - read(3, []byte{3, 4, 5}) - wantSleeps() - read(2, []byte{6}) - wantSleeps(pkt2Time) - read(2, []byte{7, 8}) - wantSleeps(pkt3Time) - read(10, []byte{9, 10, 11}) - wantSleeps() - read(10, []byte{12, 13}) - wantSleeps(pkt4Time) -} - -func TestSync(t *testing.T) { - defer restoreHooks()() - - // Infinitely fast CPU: time doesn't pass unless sleep is called. - tn := time.Unix(123, 0) - now = func() time.Time { return tn } - sleep = func(d time.Duration) { tn = tn.Add(d) } - - // Simulate a 20ms latency network, then run sync across that and expect to - // measure 20ms latency, or 10ms additional delay for a 30ms network. - slowConn, err := (&Network{Kbps: 0, Latency: 20 * time.Millisecond, MTU: 5}).Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - c, err := (&Network{Latency: 30 * time.Millisecond}).Conn(slowConn) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - if c.(*conn).delay != 10*time.Millisecond { - t.Fatalf("c.delay = %v; want 10ms", c.(*conn).delay) - } -} - -func TestSyncTooSlow(t *testing.T) { - defer restoreHooks()() - - // Infinitely fast CPU: time doesn't pass unless sleep is called. - tn := time.Unix(123, 0) - now = func() time.Time { return tn } - sleep = func(d time.Duration) { tn = tn.Add(d) } - - // Simulate a 10ms latency network, then attempt to simulate a 5ms latency - // network and expect an error. - slowConn, err := (&Network{Kbps: 0, Latency: 10 * time.Millisecond, MTU: 5}).Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - - errWant := "measured network latency (10ms) higher than desired latency (5ms)" - if _, err := (&Network{Latency: 5 * time.Millisecond}).Conn(slowConn); err == nil || err.Error() != errWant { - t.Fatalf("Conn() = _, %q; want _, %q", err, errWant) - } -} - -func TestListenerAndDialer(t *testing.T) { - defer restoreHooks()() - - tn := time.Unix(123, 0) - startTime := tn - mu := &sync.Mutex{} - now = func() time.Time { - mu.Lock() - defer mu.Unlock() - return tn - } - - // Use a fairly high latency to cause a large BDP and avoid sleeps while - // writing due to simulation of full buffers. - n := &Network{Kbps: 2, Latency: 1 * time.Second, MTU: 10} - // 2 kbps = .25 kBps = 256 Bps - byteLatency := func(n int) time.Duration { - return time.Duration(n) * time.Second / 256 - } - - // Create a real listener and wrap it. - l, err := net.Listen("tcp", ":0") - if err != nil { - t.Fatalf("Unexpected error creating listener: %v", err) - } - defer l.Close() - l = n.Listener(l) - - var serverConn net.Conn - var scErr error - scDone := make(chan struct{}) - go func() { - serverConn, scErr = l.Accept() - close(scDone) - }() - - // Create a dialer and use it. - clientConn, err := n.TimeoutDialer(net.DialTimeout)("tcp", l.Addr().String(), 2*time.Second) - if err != nil { - t.Fatalf("Unexpected error dialing: %v", err) - } - defer clientConn.Close() - - // Block until server's Conn is available. - <-scDone - if scErr != nil { - t.Fatalf("Unexpected error listening: %v", scErr) - } - defer serverConn.Close() - - // sleep (only) advances tn. Done after connections established so sync detects zero delay. - sleep = func(d time.Duration) { - mu.Lock() - defer mu.Unlock() - if d > 0 { - tn = tn.Add(d) - } - } - - seq := func(a, b int) []byte { - buf := make([]byte, b-a) - for i := 0; i < b-a; i++ { - buf[i] = byte(i + a) - } - return buf - } - - pkt1 := seq(0, 10) - pkt2 := seq(10, 30) - pkt3 := seq(30, 35) - - write := func(c net.Conn, b []byte) { - n, err := c.Write(b) - if n != len(b) || err != nil { - t.Fatalf("c.Write(%v) = %v, %v; want %v, nil", b, n, err, len(b)) - } - } - - write(serverConn, pkt1) - write(serverConn, pkt2) - write(serverConn, pkt3) - write(clientConn, pkt3) - write(clientConn, pkt1) - write(clientConn, pkt2) - - if tn != startTime { - t.Fatalf("unexpected sleep in write; tn = %v; want %v", tn, startTime) - } - - read := func(c net.Conn, n int, want []byte, timeWant time.Time) { - b := make([]byte, n) - if rd, err := c.Read(b); err != nil || rd != len(want) { - t.Fatalf("c.Read(<%v bytes>) = %v, %v; want %v, nil (read: %v)", n, rd, err, len(want), b[:rd]) - } - if !reflect.DeepEqual(b[:len(want)], want) { - t.Fatalf("read %v; want %v", b, want) - } - if !tn.Equal(timeWant) { - t.Errorf("tn after read(%v) = %v; want %v", want, tn, timeWant) - } - } - - read(clientConn, len(pkt1)+1, pkt1, startTime.Add(n.Latency+byteLatency(len(pkt1)))) - read(serverConn, len(pkt3)+1, pkt3, tn) // tn was advanced by the above read; pkt3 is shorter than pkt1 - - read(clientConn, len(pkt2), pkt2[:10], startTime.Add(n.Latency+byteLatency(len(pkt1)+10))) - read(clientConn, len(pkt2), pkt2[10:], startTime.Add(n.Latency+byteLatency(len(pkt1)+len(pkt2)))) - read(clientConn, len(pkt3), pkt3, startTime.Add(n.Latency+byteLatency(len(pkt1)+len(pkt2)+len(pkt3)))) - - read(serverConn, len(pkt1), pkt1, tn) // tn already past the arrival time due to prior reads - read(serverConn, len(pkt2), pkt2[:10], tn) - read(serverConn, len(pkt2), pkt2[10:], tn) - - // Sleep awhile and make sure the read happens disregarding previous writes - // (lastSendEnd handling). - sleep(10 * time.Second) - write(clientConn, pkt1) - read(serverConn, len(pkt1), pkt1, tn.Add(n.Latency+byteLatency(len(pkt1)))) - - // Send, sleep longer than the network delay, then make sure the read happens - // instantly. - write(serverConn, pkt1) - sleep(10 * time.Second) - read(clientConn, len(pkt1), pkt1, tn) -} - -func TestBufferBloat(t *testing.T) { - defer restoreHooks()() - - // Infinitely fast CPU: time doesn't pass unless sleep is called. - tn := time.Unix(123, 0) - now = func() time.Time { return tn } - // Capture sleep times for checking later. - var sleepTimes []time.Duration - sleep = func(d time.Duration) { - sleepTimes = append(sleepTimes, d) - tn = tn.Add(d) - } - - wantSleeps := func(want ...time.Duration) error { - if !reflect.DeepEqual(want, sleepTimes) { - return fmt.Errorf("sleepTimes = %v; want %v", sleepTimes, want) - } - sleepTimes = nil - return nil - } - - n := &Network{Kbps: 8 /* 1KBps */, Latency: time.Second, MTU: 8} - bdpBytes := (n.Kbps * 1024 / 8) * int(n.Latency/time.Second) // 1024 - c, err := n.Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - wantSleeps(n.Latency) // Connection creation delay. - - write := func(n int, sleeps ...time.Duration) { - if wt, err := c.Write(make([]byte, n)); err != nil || wt != n { - t.Fatalf("c.Write(<%v bytes>) = %v, %v; want %v, nil", n, wt, err, n) - } - if err := wantSleeps(sleeps...); err != nil { - t.Fatalf("After writing %v bytes: %v", n, err) - } - } - - read := func(n int, sleeps ...time.Duration) { - if rd, err := c.Read(make([]byte, n)); err != nil || rd != n { - t.Fatalf("c.Read(_) = %v, %v; want %v, nil", rd, err, n) - } - if err := wantSleeps(sleeps...); err != nil { - t.Fatalf("After reading %v bytes: %v", n, err) - } - } - - write(8) // No reads and buffer not full, so no sleeps yet. - read(8, time.Second+n.pktTime(8)) - - write(bdpBytes) // Fill the buffer. - write(1) // We can send one extra packet even when the buffer is full. - write(n.MTU, n.pktTime(1)) // Make sure we sleep to clear the previous write. - write(1, n.pktTime(n.MTU)) - write(n.MTU+1, n.pktTime(1), n.pktTime(n.MTU)) - - tn = tn.Add(10 * time.Second) // Wait long enough for the buffer to clear. - write(bdpBytes) // No sleeps required. -} diff --git a/vendor/google.golang.org/grpc/benchmark/primitives/primitives_test.go b/vendor/google.golang.org/grpc/benchmark/primitives/primitives_test.go deleted file mode 100644 index 59355590d..000000000 --- a/vendor/google.golang.org/grpc/benchmark/primitives/primitives_test.go +++ /dev/null @@ -1,235 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package primitives_test contains benchmarks for various synchronization primitives -// available in Go. -package primitives_test - -import ( - "sync" - "sync/atomic" - "testing" -) - -func BenchmarkSelectClosed(b *testing.B) { - c := make(chan struct{}) - close(c) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - select { - case <-c: - x++ - default: - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkSelectOpen(b *testing.B) { - c := make(chan struct{}) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - select { - case <-c: - default: - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkAtomicBool(b *testing.B) { - c := int32(0) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if atomic.LoadInt32(&c) == 0 { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkAtomicValue(b *testing.B) { - c := atomic.Value{} - c.Store(0) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if c.Load().(int) == 0 { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkMutex(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Lock() - x++ - c.Unlock() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkRWMutex(b *testing.B) { - c := sync.RWMutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.RLock() - x++ - c.RUnlock() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkRWMutexW(b *testing.B) { - c := sync.RWMutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Lock() - x++ - c.Unlock() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkMutexWithDefer(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - func() { - c.Lock() - defer c.Unlock() - x++ - }() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkMutexWithClosureDefer(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - func() { - c.Lock() - defer func() { c.Unlock() }() - x++ - }() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkMutexWithoutDefer(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - func() { - c.Lock() - x++ - c.Unlock() - }() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -type myFooer struct{} - -func (myFooer) Foo() {} - -type fooer interface { - Foo() -} - -func BenchmarkInterfaceTypeAssertion(b *testing.B) { - // Call a separate function to avoid compiler optimizations. - runInterfaceTypeAssertion(b, myFooer{}) -} - -func runInterfaceTypeAssertion(b *testing.B, fer interface{}) { - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, ok := fer.(fooer); ok { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkStructTypeAssertion(b *testing.B) { - // Call a separate function to avoid compiler optimizations. - runStructTypeAssertion(b, myFooer{}) -} - -func runStructTypeAssertion(b *testing.B, fer interface{}) { - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, ok := fer.(myFooer); ok { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} diff --git a/vendor/google.golang.org/grpc/benchmark/server/main.go b/vendor/google.golang.org/grpc/benchmark/server/main.go deleted file mode 100644 index dcce130e4..000000000 --- a/vendor/google.golang.org/grpc/benchmark/server/main.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "math" - "net" - "net/http" - _ "net/http/pprof" - "time" - - "google.golang.org/grpc/benchmark" - "google.golang.org/grpc/grpclog" -) - -var ( - duration = flag.Int("duration", math.MaxInt32, "The duration in seconds to run the benchmark server") -) - -func main() { - flag.Parse() - go func() { - lis, err := net.Listen("tcp", ":0") - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - grpclog.Println("Server profiling address: ", lis.Addr().String()) - if err := http.Serve(lis, nil); err != nil { - grpclog.Fatalf("Failed to serve: %v", err) - } - }() - addr, stopper := benchmark.StartServer(benchmark.ServerInfo{Addr: ":0", Type: "protobuf"}) // listen on all interfaces - grpclog.Println("Server Address: ", addr) - <-time.After(time.Duration(*duration) * time.Second) - stopper() -} diff --git a/vendor/google.golang.org/grpc/benchmark/stats/histogram.go b/vendor/google.golang.org/grpc/benchmark/stats/histogram.go deleted file mode 100644 index f038d26ed..000000000 --- a/vendor/google.golang.org/grpc/benchmark/stats/histogram.go +++ /dev/null @@ -1,222 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package stats - -import ( - "bytes" - "fmt" - "io" - "log" - "math" - "strconv" - "strings" -) - -// Histogram accumulates values in the form of a histogram with -// exponentially increased bucket sizes. -type Histogram struct { - // Count is the total number of values added to the histogram. - Count int64 - // Sum is the sum of all the values added to the histogram. - Sum int64 - // SumOfSquares is the sum of squares of all values. - SumOfSquares int64 - // Min is the minimum of all the values added to the histogram. - Min int64 - // Max is the maximum of all the values added to the histogram. - Max int64 - // Buckets contains all the buckets of the histogram. - Buckets []HistogramBucket - - opts HistogramOptions - logBaseBucketSize float64 - oneOverLogOnePlusGrowthFactor float64 -} - -// HistogramOptions contains the parameters that define the histogram's buckets. -// The first bucket of the created histogram (with index 0) contains [min, min+n) -// where n = BaseBucketSize, min = MinValue. -// Bucket i (i>=1) contains [min + n * m^(i-1), min + n * m^i), where m = 1+GrowthFactor. -// The type of the values is int64. -type HistogramOptions struct { - // NumBuckets is the number of buckets. - NumBuckets int - // GrowthFactor is the growth factor of the buckets. A value of 0.1 - // indicates that bucket N+1 will be 10% larger than bucket N. - GrowthFactor float64 - // BaseBucketSize is the size of the first bucket. - BaseBucketSize float64 - // MinValue is the lower bound of the first bucket. - MinValue int64 -} - -// HistogramBucket represents one histogram bucket. -type HistogramBucket struct { - // LowBound is the lower bound of the bucket. - LowBound float64 - // Count is the number of values in the bucket. - Count int64 -} - -// NewHistogram returns a pointer to a new Histogram object that was created -// with the provided options. -func NewHistogram(opts HistogramOptions) *Histogram { - if opts.NumBuckets == 0 { - opts.NumBuckets = 32 - } - if opts.BaseBucketSize == 0.0 { - opts.BaseBucketSize = 1.0 - } - h := Histogram{ - Buckets: make([]HistogramBucket, opts.NumBuckets), - Min: math.MaxInt64, - Max: math.MinInt64, - - opts: opts, - logBaseBucketSize: math.Log(opts.BaseBucketSize), - oneOverLogOnePlusGrowthFactor: 1 / math.Log(1+opts.GrowthFactor), - } - m := 1.0 + opts.GrowthFactor - delta := opts.BaseBucketSize - h.Buckets[0].LowBound = float64(opts.MinValue) - for i := 1; i < opts.NumBuckets; i++ { - h.Buckets[i].LowBound = float64(opts.MinValue) + delta - delta = delta * m - } - return &h -} - -// Print writes textual output of the histogram values. -func (h *Histogram) Print(w io.Writer) { - h.PrintWithUnit(w, 1) -} - -// PrintWithUnit writes textual output of the histogram values . -// Data in histogram is divided by a Unit before print. -func (h *Histogram) PrintWithUnit(w io.Writer, unit float64) { - avg := float64(h.Sum) / float64(h.Count) - fmt.Fprintf(w, "Count: %d Min: %5.1f Max: %5.1f Avg: %.2f\n", h.Count, float64(h.Min)/unit, float64(h.Max)/unit, avg/unit) - fmt.Fprintf(w, "%s\n", strings.Repeat("-", 60)) - if h.Count <= 0 { - return - } - - maxBucketDigitLen := len(strconv.FormatFloat(h.Buckets[len(h.Buckets)-1].LowBound, 'f', 6, 64)) - if maxBucketDigitLen < 3 { - // For "inf". - maxBucketDigitLen = 3 - } - maxCountDigitLen := len(strconv.FormatInt(h.Count, 10)) - percentMulti := 100 / float64(h.Count) - - accCount := int64(0) - for i, b := range h.Buckets { - fmt.Fprintf(w, "[%*f, ", maxBucketDigitLen, b.LowBound/unit) - if i+1 < len(h.Buckets) { - fmt.Fprintf(w, "%*f)", maxBucketDigitLen, h.Buckets[i+1].LowBound/unit) - } else { - fmt.Fprintf(w, "%*s)", maxBucketDigitLen, "inf") - } - - accCount += b.Count - fmt.Fprintf(w, " %*d %5.1f%% %5.1f%%", maxCountDigitLen, b.Count, float64(b.Count)*percentMulti, float64(accCount)*percentMulti) - - const barScale = 0.1 - barLength := int(float64(b.Count)*percentMulti*barScale + 0.5) - fmt.Fprintf(w, " %s\n", strings.Repeat("#", barLength)) - } -} - -// String returns the textual output of the histogram values as string. -func (h *Histogram) String() string { - var b bytes.Buffer - h.Print(&b) - return b.String() -} - -// Clear resets all the content of histogram. -func (h *Histogram) Clear() { - h.Count = 0 - h.Sum = 0 - h.SumOfSquares = 0 - h.Min = math.MaxInt64 - h.Max = math.MinInt64 - for i := range h.Buckets { - h.Buckets[i].Count = 0 - } -} - -// Opts returns a copy of the options used to create the Histogram. -func (h *Histogram) Opts() HistogramOptions { - return h.opts -} - -// Add adds a value to the histogram. -func (h *Histogram) Add(value int64) error { - bucket, err := h.findBucket(value) - if err != nil { - return err - } - h.Buckets[bucket].Count++ - h.Count++ - h.Sum += value - h.SumOfSquares += value * value - if value < h.Min { - h.Min = value - } - if value > h.Max { - h.Max = value - } - return nil -} - -func (h *Histogram) findBucket(value int64) (int, error) { - delta := float64(value - h.opts.MinValue) - var b int - if delta >= h.opts.BaseBucketSize { - // b = log_{1+growthFactor} (delta / baseBucketSize) + 1 - // = log(delta / baseBucketSize) / log(1+growthFactor) + 1 - // = (log(delta) - log(baseBucketSize)) * (1 / log(1+growthFactor)) + 1 - b = int((math.Log(delta)-h.logBaseBucketSize)*h.oneOverLogOnePlusGrowthFactor + 1) - } - if b >= len(h.Buckets) { - return 0, fmt.Errorf("no bucket for value: %d", value) - } - return b, nil -} - -// Merge takes another histogram h2, and merges its content into h. -// The two histograms must be created by equivalent HistogramOptions. -func (h *Histogram) Merge(h2 *Histogram) { - if h.opts != h2.opts { - log.Fatalf("failed to merge histograms, created by inequivalent options") - } - h.Count += h2.Count - h.Sum += h2.Sum - h.SumOfSquares += h2.SumOfSquares - if h2.Min < h.Min { - h.Min = h2.Min - } - if h2.Max > h.Max { - h.Max = h2.Max - } - for i, b := range h2.Buckets { - h.Buckets[i].Count += b.Count - } -} diff --git a/vendor/google.golang.org/grpc/benchmark/stats/stats.go b/vendor/google.golang.org/grpc/benchmark/stats/stats.go deleted file mode 100644 index 412daead0..000000000 --- a/vendor/google.golang.org/grpc/benchmark/stats/stats.go +++ /dev/null @@ -1,291 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package stats - -import ( - "bytes" - "fmt" - "io" - "math" - "sort" - "strconv" - "time" -) - -// Features contains most fields for a benchmark -type Features struct { - NetworkMode string - EnableTrace bool - Latency time.Duration - Kbps int - Mtu int - MaxConcurrentCalls int - ReqSizeBytes int - RespSizeBytes int - EnableCompressor bool -} - -// String returns the textual output of the Features as string. -func (f Features) String() string { - return fmt.Sprintf("traceMode_%t-latency_%s-kbps_%#v-MTU_%#v-maxConcurrentCalls_"+ - "%#v-reqSize_%#vB-respSize_%#vB-Compressor_%t", f.EnableTrace, - f.Latency.String(), f.Kbps, f.Mtu, f.MaxConcurrentCalls, f.ReqSizeBytes, f.RespSizeBytes, f.EnableCompressor) -} - -// PartialPrintString can print certain features with different format. -func PartialPrintString(noneEmptyPos []bool, f Features, shared bool) string { - s := "" - var ( - prefix, suffix, linker string - isNetwork bool - ) - if shared { - suffix = "\n" - linker = ": " - } else { - prefix = "-" - linker = "_" - } - if noneEmptyPos[0] { - s += fmt.Sprintf("%sTrace%s%t%s", prefix, linker, f.EnableCompressor, suffix) - } - if shared && f.NetworkMode != "" { - s += fmt.Sprintf("Network: %s \n", f.NetworkMode) - isNetwork = true - } - if !isNetwork { - if noneEmptyPos[1] { - s += fmt.Sprintf("%slatency%s%s%s", prefix, linker, f.Latency.String(), suffix) - } - if noneEmptyPos[2] { - s += fmt.Sprintf("%skbps%s%#v%s", prefix, linker, f.Kbps, suffix) - } - if noneEmptyPos[3] { - s += fmt.Sprintf("%sMTU%s%#v%s", prefix, linker, f.Mtu, suffix) - } - } - if noneEmptyPos[4] { - s += fmt.Sprintf("%sCallers%s%#v%s", prefix, linker, f.MaxConcurrentCalls, suffix) - } - if noneEmptyPos[5] { - s += fmt.Sprintf("%sreqSize%s%#vB%s", prefix, linker, f.ReqSizeBytes, suffix) - } - if noneEmptyPos[6] { - s += fmt.Sprintf("%srespSize%s%#vB%s", prefix, linker, f.RespSizeBytes, suffix) - } - if noneEmptyPos[7] { - s += fmt.Sprintf("%sCompressor%s%t%s", prefix, linker, f.EnableCompressor, suffix) - } - return s -} - -type percentLatency struct { - Percent int - Value time.Duration -} - -// BenchResults records features and result of a benchmark. -type BenchResults struct { - RunMode string - Features Features - Latency []percentLatency - Operations int - NsPerOp int64 - AllocedBytesPerOp int64 - AllocsPerOp int64 - SharedPosion []bool -} - -// SetBenchmarkResult sets features of benchmark and basic results. -func (stats *Stats) SetBenchmarkResult(mode string, features Features, o int, allocdBytes, allocs int64, sharedPos []bool) { - stats.result.RunMode = mode - stats.result.Features = features - stats.result.Operations = o - stats.result.AllocedBytesPerOp = allocdBytes - stats.result.AllocsPerOp = allocs - stats.result.SharedPosion = sharedPos -} - -// GetBenchmarkResults returns the result of the benchmark including features and result. -func (stats *Stats) GetBenchmarkResults() BenchResults { - return stats.result -} - -// BenchString output latency stats as the format as time + unit. -func (stats *Stats) BenchString() string { - stats.maybeUpdate() - s := stats.result - res := s.RunMode + "-" + s.Features.String() + ": \n" - if len(s.Latency) != 0 { - var statsUnit = s.Latency[0].Value - var timeUnit = fmt.Sprintf("%v", statsUnit)[1:] - for i := 1; i < len(s.Latency)-1; i++ { - res += fmt.Sprintf("%d_Latency: %s %s \t", s.Latency[i].Percent, - strconv.FormatFloat(float64(s.Latency[i].Value)/float64(statsUnit), 'f', 4, 64), timeUnit) - } - res += fmt.Sprintf("Avg latency: %s %s \t", - strconv.FormatFloat(float64(s.Latency[len(s.Latency)-1].Value)/float64(statsUnit), 'f', 4, 64), timeUnit) - } - res += fmt.Sprintf("Count: %v \t", s.Operations) - res += fmt.Sprintf("%v Bytes/op\t", s.AllocedBytesPerOp) - res += fmt.Sprintf("%v Allocs/op\t", s.AllocsPerOp) - - return res -} - -// Stats is a simple helper for gathering additional statistics like histogram -// during benchmarks. This is not thread safe. -type Stats struct { - numBuckets int - unit time.Duration - min, max int64 - histogram *Histogram - - durations durationSlice - dirty bool - - sortLatency bool - result BenchResults -} - -type durationSlice []time.Duration - -// NewStats creates a new Stats instance. If numBuckets is not positive, -// the default value (16) will be used. -func NewStats(numBuckets int) *Stats { - if numBuckets <= 0 { - numBuckets = 16 - } - return &Stats{ - // Use one more bucket for the last unbounded bucket. - numBuckets: numBuckets + 1, - durations: make(durationSlice, 0, 100000), - } -} - -// Add adds an elapsed time per operation to the stats. -func (stats *Stats) Add(d time.Duration) { - stats.durations = append(stats.durations, d) - stats.dirty = true -} - -// Clear resets the stats, removing all values. -func (stats *Stats) Clear() { - stats.durations = stats.durations[:0] - stats.histogram = nil - stats.dirty = false - stats.result = BenchResults{} -} - -//Sort method for durations -func (a durationSlice) Len() int { return len(a) } -func (a durationSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a durationSlice) Less(i, j int) bool { return a[i] < a[j] } -func max(a, b int64) int64 { - if a > b { - return a - } - return b -} - -// maybeUpdate updates internal stat data if there was any newly added -// stats since this was updated. -func (stats *Stats) maybeUpdate() { - if !stats.dirty { - return - } - - if stats.sortLatency { - sort.Sort(stats.durations) - stats.min = int64(stats.durations[0]) - stats.max = int64(stats.durations[len(stats.durations)-1]) - } - - stats.min = math.MaxInt64 - stats.max = 0 - for _, d := range stats.durations { - if stats.min > int64(d) { - stats.min = int64(d) - } - if stats.max < int64(d) { - stats.max = int64(d) - } - } - - // Use the largest unit that can represent the minimum time duration. - stats.unit = time.Nanosecond - for _, u := range []time.Duration{time.Microsecond, time.Millisecond, time.Second} { - if stats.min <= int64(u) { - break - } - stats.unit = u - } - - numBuckets := stats.numBuckets - if n := int(stats.max - stats.min + 1); n < numBuckets { - numBuckets = n - } - stats.histogram = NewHistogram(HistogramOptions{ - NumBuckets: numBuckets, - // max-min(lower bound of last bucket) = (1 + growthFactor)^(numBuckets-2) * baseBucketSize. - GrowthFactor: math.Pow(float64(stats.max-stats.min), 1/float64(numBuckets-2)) - 1, - BaseBucketSize: 1.0, - MinValue: stats.min}) - - for _, d := range stats.durations { - stats.histogram.Add(int64(d)) - } - - stats.dirty = false - - if stats.durations.Len() != 0 { - var percentToObserve = []int{50, 90} - // First data record min unit from the latency result. - stats.result.Latency = append(stats.result.Latency, percentLatency{Percent: -1, Value: stats.unit}) - for _, position := range percentToObserve { - stats.result.Latency = append(stats.result.Latency, percentLatency{Percent: position, Value: stats.durations[max(stats.histogram.Count*int64(position)/100-1, 0)]}) - } - // Last data record the average latency. - avg := float64(stats.histogram.Sum) / float64(stats.histogram.Count) - stats.result.Latency = append(stats.result.Latency, percentLatency{Percent: -1, Value: time.Duration(avg)}) - } -} - -// SortLatency blocks the output -func (stats *Stats) SortLatency() { - stats.sortLatency = true -} - -// Print writes textual output of the Stats. -func (stats *Stats) Print(w io.Writer) { - stats.maybeUpdate() - if stats.histogram == nil { - fmt.Fprint(w, "Histogram (empty)\n") - } else { - fmt.Fprintf(w, "Histogram (unit: %s)\n", fmt.Sprintf("%v", stats.unit)[1:]) - stats.histogram.PrintWithUnit(w, float64(stats.unit)) - } -} - -// String returns the textual output of the Stats as string. -func (stats *Stats) String() string { - var b bytes.Buffer - stats.Print(&b) - return b.String() -} diff --git a/vendor/google.golang.org/grpc/benchmark/stats/util.go b/vendor/google.golang.org/grpc/benchmark/stats/util.go deleted file mode 100644 index f3bb3a364..000000000 --- a/vendor/google.golang.org/grpc/benchmark/stats/util.go +++ /dev/null @@ -1,208 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package stats - -import ( - "bufio" - "bytes" - "fmt" - "os" - "runtime" - "sort" - "strings" - "sync" - "testing" -) - -var ( - curB *testing.B - curBenchName string - curStats map[string]*Stats - - orgStdout *os.File - nextOutPos int - - injectCond *sync.Cond - injectDone chan struct{} -) - -// AddStats adds a new unnamed Stats instance to the current benchmark. You need -// to run benchmarks by calling RunTestMain() to inject the stats to the -// benchmark results. If numBuckets is not positive, the default value (16) will -// be used. Please note that this calls b.ResetTimer() since it may be blocked -// until the previous benchmark stats is printed out. So AddStats() should -// typically be called at the very beginning of each benchmark function. -func AddStats(b *testing.B, numBuckets int) *Stats { - return AddStatsWithName(b, "", numBuckets) -} - -// AddStatsWithName adds a new named Stats instance to the current benchmark. -// With this, you can add multiple stats in a single benchmark. You need -// to run benchmarks by calling RunTestMain() to inject the stats to the -// benchmark results. If numBuckets is not positive, the default value (16) will -// be used. Please note that this calls b.ResetTimer() since it may be blocked -// until the previous benchmark stats is printed out. So AddStatsWithName() -// should typically be called at the very beginning of each benchmark function. -func AddStatsWithName(b *testing.B, name string, numBuckets int) *Stats { - var benchName string - for i := 1; ; i++ { - pc, _, _, ok := runtime.Caller(i) - if !ok { - panic("benchmark function not found") - } - p := strings.Split(runtime.FuncForPC(pc).Name(), ".") - benchName = p[len(p)-1] - if strings.HasPrefix(benchName, "run") { - break - } - } - procs := runtime.GOMAXPROCS(-1) - if procs != 1 { - benchName = fmt.Sprintf("%s-%d", benchName, procs) - } - - stats := NewStats(numBuckets) - - if injectCond != nil { - // We need to wait until the previous benchmark stats is printed out. - injectCond.L.Lock() - for curB != nil && curBenchName != benchName { - injectCond.Wait() - } - - curB = b - curBenchName = benchName - curStats[name] = stats - - injectCond.L.Unlock() - } - - b.ResetTimer() - return stats -} - -// RunTestMain runs the tests with enabling injection of benchmark stats. It -// returns an exit code to pass to os.Exit. -func RunTestMain(m *testing.M) int { - startStatsInjector() - defer stopStatsInjector() - return m.Run() -} - -// startStatsInjector starts stats injection to benchmark results. -func startStatsInjector() { - orgStdout = os.Stdout - r, w, _ := os.Pipe() - os.Stdout = w - nextOutPos = 0 - - resetCurBenchStats() - - injectCond = sync.NewCond(&sync.Mutex{}) - injectDone = make(chan struct{}) - go func() { - defer close(injectDone) - - scanner := bufio.NewScanner(r) - scanner.Split(splitLines) - for scanner.Scan() { - injectStatsIfFinished(scanner.Text()) - } - if err := scanner.Err(); err != nil { - panic(err) - } - }() -} - -// stopStatsInjector stops stats injection and restores os.Stdout. -func stopStatsInjector() { - os.Stdout.Close() - <-injectDone - injectCond = nil - os.Stdout = orgStdout -} - -// splitLines is a split function for a bufio.Scanner that returns each line -// of text, teeing texts to the original stdout even before each line ends. -func splitLines(data []byte, eof bool) (advance int, token []byte, err error) { - if eof && len(data) == 0 { - return 0, nil, nil - } - - if i := bytes.IndexByte(data, '\n'); i >= 0 { - orgStdout.Write(data[nextOutPos : i+1]) - nextOutPos = 0 - return i + 1, data[0:i], nil - } - - orgStdout.Write(data[nextOutPos:]) - nextOutPos = len(data) - - if eof { - // This is a final, non-terminated line. Return it. - return len(data), data, nil - } - - return 0, nil, nil -} - -// injectStatsIfFinished prints out the stats if the current benchmark finishes. -func injectStatsIfFinished(line string) { - injectCond.L.Lock() - defer injectCond.L.Unlock() - // We assume that the benchmark results start with "Benchmark". - if curB == nil || !strings.HasPrefix(line, "Benchmark") { - return - } - - if !curB.Failed() { - // Output all stats in alphabetical order. - names := make([]string, 0, len(curStats)) - for name := range curStats { - names = append(names, name) - } - sort.Strings(names) - for _, name := range names { - stats := curStats[name] - // The output of stats starts with a header like "Histogram (unit: ms)" - // followed by statistical properties and the buckets. Add the stats name - // if it is a named stats and indent them as Go testing outputs. - lines := strings.Split(stats.String(), "\n") - if n := len(lines); n > 0 { - if name != "" { - name = ": " + name - } - fmt.Fprintf(orgStdout, "--- %s%s\n", lines[0], name) - for _, line := range lines[1 : n-1] { - fmt.Fprintf(orgStdout, "\t%s\n", line) - } - } - } - } - - resetCurBenchStats() - injectCond.Signal() -} - -// resetCurBenchStats resets the current benchmark stats. -func resetCurBenchStats() { - curB = nil - curBenchName = "" - curStats = make(map[string]*Stats) -} diff --git a/vendor/google.golang.org/grpc/benchmark/worker/benchmark_client.go b/vendor/google.golang.org/grpc/benchmark/worker/benchmark_client.go deleted file mode 100644 index 9db1d8504..000000000 --- a/vendor/google.golang.org/grpc/benchmark/worker/benchmark_client.go +++ /dev/null @@ -1,392 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "math" - "runtime" - "sync" - "syscall" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/testdata" -) - -var ( - caFile = flag.String("ca_file", "", "The file containing the CA root cert file") -) - -type lockingHistogram struct { - mu sync.Mutex - histogram *stats.Histogram -} - -func (h *lockingHistogram) add(value int64) { - h.mu.Lock() - defer h.mu.Unlock() - h.histogram.Add(value) -} - -// swap sets h.histogram to new, and returns its old value. -func (h *lockingHistogram) swap(new *stats.Histogram) *stats.Histogram { - h.mu.Lock() - defer h.mu.Unlock() - old := h.histogram - h.histogram = new - return old -} - -func (h *lockingHistogram) mergeInto(merged *stats.Histogram) { - h.mu.Lock() - defer h.mu.Unlock() - merged.Merge(h.histogram) -} - -type benchmarkClient struct { - closeConns func() - stop chan bool - lastResetTime time.Time - histogramOptions stats.HistogramOptions - lockingHistograms []lockingHistogram - rusageLastReset *syscall.Rusage -} - -func printClientConfig(config *testpb.ClientConfig) { - // Some config options are ignored: - // - client type: - // will always create sync client - // - async client threads. - // - core list - grpclog.Printf(" * client type: %v (ignored, always creates sync client)", config.ClientType) - grpclog.Printf(" * async client threads: %v (ignored)", config.AsyncClientThreads) - // TODO: use cores specified by CoreList when setting list of cores is supported in go. - grpclog.Printf(" * core list: %v (ignored)", config.CoreList) - - grpclog.Printf(" - security params: %v", config.SecurityParams) - grpclog.Printf(" - core limit: %v", config.CoreLimit) - grpclog.Printf(" - payload config: %v", config.PayloadConfig) - grpclog.Printf(" - rpcs per chann: %v", config.OutstandingRpcsPerChannel) - grpclog.Printf(" - channel number: %v", config.ClientChannels) - grpclog.Printf(" - load params: %v", config.LoadParams) - grpclog.Printf(" - rpc type: %v", config.RpcType) - grpclog.Printf(" - histogram params: %v", config.HistogramParams) - grpclog.Printf(" - server targets: %v", config.ServerTargets) -} - -func setupClientEnv(config *testpb.ClientConfig) { - // Use all cpu cores available on machine by default. - // TODO: Revisit this for the optimal default setup. - if config.CoreLimit > 0 { - runtime.GOMAXPROCS(int(config.CoreLimit)) - } else { - runtime.GOMAXPROCS(runtime.NumCPU()) - } -} - -// createConns creates connections according to given config. -// It returns the connections and corresponding function to close them. -// It returns non-nil error if there is anything wrong. -func createConns(config *testpb.ClientConfig) ([]*grpc.ClientConn, func(), error) { - var opts []grpc.DialOption - - // Sanity check for client type. - switch config.ClientType { - case testpb.ClientType_SYNC_CLIENT: - case testpb.ClientType_ASYNC_CLIENT: - default: - return nil, nil, grpc.Errorf(codes.InvalidArgument, "unknow client type: %v", config.ClientType) - } - - // Check and set security options. - if config.SecurityParams != nil { - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err := credentials.NewClientTLSFromFile(*caFile, config.SecurityParams.ServerHostOverride) - if err != nil { - return nil, nil, grpc.Errorf(codes.InvalidArgument, "failed to create TLS credentials %v", err) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - } else { - opts = append(opts, grpc.WithInsecure()) - } - - // Use byteBufCodec if it is required. - if config.PayloadConfig != nil { - switch config.PayloadConfig.Payload.(type) { - case *testpb.PayloadConfig_BytebufParams: - opts = append(opts, grpc.WithCodec(byteBufCodec{})) - case *testpb.PayloadConfig_SimpleParams: - default: - return nil, nil, grpc.Errorf(codes.InvalidArgument, "unknow payload config: %v", config.PayloadConfig) - } - } - - // Create connections. - connCount := int(config.ClientChannels) - conns := make([]*grpc.ClientConn, connCount, connCount) - for connIndex := 0; connIndex < connCount; connIndex++ { - conns[connIndex] = benchmark.NewClientConn(config.ServerTargets[connIndex%len(config.ServerTargets)], opts...) - } - - return conns, func() { - for _, conn := range conns { - conn.Close() - } - }, nil -} - -func performRPCs(config *testpb.ClientConfig, conns []*grpc.ClientConn, bc *benchmarkClient) error { - // Read payload size and type from config. - var ( - payloadReqSize, payloadRespSize int - payloadType string - ) - if config.PayloadConfig != nil { - switch c := config.PayloadConfig.Payload.(type) { - case *testpb.PayloadConfig_BytebufParams: - payloadReqSize = int(c.BytebufParams.ReqSize) - payloadRespSize = int(c.BytebufParams.RespSize) - payloadType = "bytebuf" - case *testpb.PayloadConfig_SimpleParams: - payloadReqSize = int(c.SimpleParams.ReqSize) - payloadRespSize = int(c.SimpleParams.RespSize) - payloadType = "protobuf" - default: - return grpc.Errorf(codes.InvalidArgument, "unknow payload config: %v", config.PayloadConfig) - } - } - - // TODO add open loop distribution. - switch config.LoadParams.Load.(type) { - case *testpb.LoadParams_ClosedLoop: - case *testpb.LoadParams_Poisson: - return grpc.Errorf(codes.Unimplemented, "unsupported load params: %v", config.LoadParams) - default: - return grpc.Errorf(codes.InvalidArgument, "unknown load params: %v", config.LoadParams) - } - - rpcCountPerConn := int(config.OutstandingRpcsPerChannel) - - switch config.RpcType { - case testpb.RpcType_UNARY: - bc.doCloseLoopUnary(conns, rpcCountPerConn, payloadReqSize, payloadRespSize) - // TODO open loop. - case testpb.RpcType_STREAMING: - bc.doCloseLoopStreaming(conns, rpcCountPerConn, payloadReqSize, payloadRespSize, payloadType) - // TODO open loop. - default: - return grpc.Errorf(codes.InvalidArgument, "unknown rpc type: %v", config.RpcType) - } - - return nil -} - -func startBenchmarkClient(config *testpb.ClientConfig) (*benchmarkClient, error) { - printClientConfig(config) - - // Set running environment like how many cores to use. - setupClientEnv(config) - - conns, closeConns, err := createConns(config) - if err != nil { - return nil, err - } - - rusage := new(syscall.Rusage) - syscall.Getrusage(syscall.RUSAGE_SELF, rusage) - - rpcCountPerConn := int(config.OutstandingRpcsPerChannel) - bc := &benchmarkClient{ - histogramOptions: stats.HistogramOptions{ - NumBuckets: int(math.Log(config.HistogramParams.MaxPossible)/math.Log(1+config.HistogramParams.Resolution)) + 1, - GrowthFactor: config.HistogramParams.Resolution, - BaseBucketSize: (1 + config.HistogramParams.Resolution), - MinValue: 0, - }, - lockingHistograms: make([]lockingHistogram, rpcCountPerConn*len(conns), rpcCountPerConn*len(conns)), - - stop: make(chan bool), - lastResetTime: time.Now(), - closeConns: closeConns, - rusageLastReset: rusage, - } - - if err = performRPCs(config, conns, bc); err != nil { - // Close all connections if performRPCs failed. - closeConns() - return nil, err - } - - return bc, nil -} - -func (bc *benchmarkClient) doCloseLoopUnary(conns []*grpc.ClientConn, rpcCountPerConn int, reqSize int, respSize int) { - for ic, conn := range conns { - client := testpb.NewBenchmarkServiceClient(conn) - // For each connection, create rpcCountPerConn goroutines to do rpc. - for j := 0; j < rpcCountPerConn; j++ { - // Create histogram for each goroutine. - idx := ic*rpcCountPerConn + j - bc.lockingHistograms[idx].histogram = stats.NewHistogram(bc.histogramOptions) - // Start goroutine on the created mutex and histogram. - go func(idx int) { - // TODO: do warm up if necessary. - // Now relying on worker client to reserve time to do warm up. - // The worker client needs to wait for some time after client is created, - // before starting benchmark. - done := make(chan bool) - for { - go func() { - start := time.Now() - if err := benchmark.DoUnaryCall(client, reqSize, respSize); err != nil { - select { - case <-bc.stop: - case done <- false: - } - return - } - elapse := time.Since(start) - bc.lockingHistograms[idx].add(int64(elapse)) - select { - case <-bc.stop: - case done <- true: - } - }() - select { - case <-bc.stop: - return - case <-done: - } - } - }(idx) - } - } -} - -func (bc *benchmarkClient) doCloseLoopStreaming(conns []*grpc.ClientConn, rpcCountPerConn int, reqSize int, respSize int, payloadType string) { - var doRPC func(testpb.BenchmarkService_StreamingCallClient, int, int) error - if payloadType == "bytebuf" { - doRPC = benchmark.DoByteBufStreamingRoundTrip - } else { - doRPC = benchmark.DoStreamingRoundTrip - } - for ic, conn := range conns { - // For each connection, create rpcCountPerConn goroutines to do rpc. - for j := 0; j < rpcCountPerConn; j++ { - c := testpb.NewBenchmarkServiceClient(conn) - stream, err := c.StreamingCall(context.Background()) - if err != nil { - grpclog.Fatalf("%v.StreamingCall(_) = _, %v", c, err) - } - // Create histogram for each goroutine. - idx := ic*rpcCountPerConn + j - bc.lockingHistograms[idx].histogram = stats.NewHistogram(bc.histogramOptions) - // Start goroutine on the created mutex and histogram. - go func(idx int) { - // TODO: do warm up if necessary. - // Now relying on worker client to reserve time to do warm up. - // The worker client needs to wait for some time after client is created, - // before starting benchmark. - for { - start := time.Now() - if err := doRPC(stream, reqSize, respSize); err != nil { - return - } - elapse := time.Since(start) - bc.lockingHistograms[idx].add(int64(elapse)) - select { - case <-bc.stop: - return - default: - } - } - }(idx) - } - } -} - -// getStats returns the stats for benchmark client. -// It resets lastResetTime and all histograms if argument reset is true. -func (bc *benchmarkClient) getStats(reset bool) *testpb.ClientStats { - var wallTimeElapsed, uTimeElapsed, sTimeElapsed float64 - mergedHistogram := stats.NewHistogram(bc.histogramOptions) - latestRusage := new(syscall.Rusage) - - if reset { - // Merging histogram may take some time. - // Put all histograms aside and merge later. - toMerge := make([]*stats.Histogram, len(bc.lockingHistograms), len(bc.lockingHistograms)) - for i := range bc.lockingHistograms { - toMerge[i] = bc.lockingHistograms[i].swap(stats.NewHistogram(bc.histogramOptions)) - } - - for i := 0; i < len(toMerge); i++ { - mergedHistogram.Merge(toMerge[i]) - } - - wallTimeElapsed = time.Since(bc.lastResetTime).Seconds() - syscall.Getrusage(syscall.RUSAGE_SELF, latestRusage) - uTimeElapsed, sTimeElapsed = cpuTimeDiff(bc.rusageLastReset, latestRusage) - - bc.rusageLastReset = latestRusage - bc.lastResetTime = time.Now() - } else { - // Merge only, not reset. - for i := range bc.lockingHistograms { - bc.lockingHistograms[i].mergeInto(mergedHistogram) - } - - wallTimeElapsed = time.Since(bc.lastResetTime).Seconds() - syscall.Getrusage(syscall.RUSAGE_SELF, latestRusage) - uTimeElapsed, sTimeElapsed = cpuTimeDiff(bc.rusageLastReset, latestRusage) - } - - b := make([]uint32, len(mergedHistogram.Buckets), len(mergedHistogram.Buckets)) - for i, v := range mergedHistogram.Buckets { - b[i] = uint32(v.Count) - } - return &testpb.ClientStats{ - Latencies: &testpb.HistogramData{ - Bucket: b, - MinSeen: float64(mergedHistogram.Min), - MaxSeen: float64(mergedHistogram.Max), - Sum: float64(mergedHistogram.Sum), - SumOfSquares: float64(mergedHistogram.SumOfSquares), - Count: float64(mergedHistogram.Count), - }, - TimeElapsed: wallTimeElapsed, - TimeUser: uTimeElapsed, - TimeSystem: sTimeElapsed, - } -} - -func (bc *benchmarkClient) shutdown() { - close(bc.stop) - bc.closeConns() -} diff --git a/vendor/google.golang.org/grpc/benchmark/worker/benchmark_server.go b/vendor/google.golang.org/grpc/benchmark/worker/benchmark_server.go deleted file mode 100644 index 238dfdebc..000000000 --- a/vendor/google.golang.org/grpc/benchmark/worker/benchmark_server.go +++ /dev/null @@ -1,184 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "runtime" - "strconv" - "strings" - "sync" - "syscall" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/testdata" -) - -var ( - certFile = flag.String("tls_cert_file", "", "The TLS cert file") - keyFile = flag.String("tls_key_file", "", "The TLS key file") -) - -type benchmarkServer struct { - port int - cores int - closeFunc func() - mu sync.RWMutex - lastResetTime time.Time - rusageLastReset *syscall.Rusage -} - -func printServerConfig(config *testpb.ServerConfig) { - // Some config options are ignored: - // - server type: - // will always start sync server - // - async server threads - // - core list - grpclog.Printf(" * server type: %v (ignored, always starts sync server)", config.ServerType) - grpclog.Printf(" * async server threads: %v (ignored)", config.AsyncServerThreads) - // TODO: use cores specified by CoreList when setting list of cores is supported in go. - grpclog.Printf(" * core list: %v (ignored)", config.CoreList) - - grpclog.Printf(" - security params: %v", config.SecurityParams) - grpclog.Printf(" - core limit: %v", config.CoreLimit) - grpclog.Printf(" - port: %v", config.Port) - grpclog.Printf(" - payload config: %v", config.PayloadConfig) -} - -func startBenchmarkServer(config *testpb.ServerConfig, serverPort int) (*benchmarkServer, error) { - printServerConfig(config) - - // Use all cpu cores available on machine by default. - // TODO: Revisit this for the optimal default setup. - numOfCores := runtime.NumCPU() - if config.CoreLimit > 0 { - numOfCores = int(config.CoreLimit) - } - runtime.GOMAXPROCS(numOfCores) - - var opts []grpc.ServerOption - - // Sanity check for server type. - switch config.ServerType { - case testpb.ServerType_SYNC_SERVER: - case testpb.ServerType_ASYNC_SERVER: - case testpb.ServerType_ASYNC_GENERIC_SERVER: - default: - return nil, grpc.Errorf(codes.InvalidArgument, "unknow server type: %v", config.ServerType) - } - - // Set security options. - if config.SecurityParams != nil { - if *certFile == "" { - *certFile = testdata.Path("server1.pem") - } - if *keyFile == "" { - *keyFile = testdata.Path("server1.key") - } - creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) - if err != nil { - grpclog.Fatalf("failed to generate credentials %v", err) - } - opts = append(opts, grpc.Creds(creds)) - } - - // Priority: config.Port > serverPort > default (0). - port := int(config.Port) - if port == 0 { - port = serverPort - } - - // Create different benchmark server according to config. - var ( - addr string - closeFunc func() - err error - ) - if config.PayloadConfig != nil { - switch payload := config.PayloadConfig.Payload.(type) { - case *testpb.PayloadConfig_BytebufParams: - opts = append(opts, grpc.CustomCodec(byteBufCodec{})) - addr, closeFunc = benchmark.StartServer(benchmark.ServerInfo{ - Addr: ":" + strconv.Itoa(port), - Type: "bytebuf", - Metadata: payload.BytebufParams.RespSize, - }, opts...) - case *testpb.PayloadConfig_SimpleParams: - addr, closeFunc = benchmark.StartServer(benchmark.ServerInfo{ - Addr: ":" + strconv.Itoa(port), - Type: "protobuf", - }, opts...) - case *testpb.PayloadConfig_ComplexParams: - return nil, grpc.Errorf(codes.Unimplemented, "unsupported payload config: %v", config.PayloadConfig) - default: - return nil, grpc.Errorf(codes.InvalidArgument, "unknow payload config: %v", config.PayloadConfig) - } - } else { - // Start protobuf server if payload config is nil. - addr, closeFunc = benchmark.StartServer(benchmark.ServerInfo{ - Addr: ":" + strconv.Itoa(port), - Type: "protobuf", - }, opts...) - } - - grpclog.Printf("benchmark server listening at %v", addr) - addrSplitted := strings.Split(addr, ":") - p, err := strconv.Atoi(addrSplitted[len(addrSplitted)-1]) - if err != nil { - grpclog.Fatalf("failed to get port number from server address: %v", err) - } - - rusage := new(syscall.Rusage) - syscall.Getrusage(syscall.RUSAGE_SELF, rusage) - - return &benchmarkServer{ - port: p, - cores: numOfCores, - closeFunc: closeFunc, - lastResetTime: time.Now(), - rusageLastReset: rusage, - }, nil -} - -// getStats returns the stats for benchmark server. -// It resets lastResetTime if argument reset is true. -func (bs *benchmarkServer) getStats(reset bool) *testpb.ServerStats { - bs.mu.RLock() - defer bs.mu.RUnlock() - wallTimeElapsed := time.Since(bs.lastResetTime).Seconds() - rusageLatest := new(syscall.Rusage) - syscall.Getrusage(syscall.RUSAGE_SELF, rusageLatest) - uTimeElapsed, sTimeElapsed := cpuTimeDiff(bs.rusageLastReset, rusageLatest) - - if reset { - bs.lastResetTime = time.Now() - bs.rusageLastReset = rusageLatest - } - return &testpb.ServerStats{ - TimeElapsed: wallTimeElapsed, - TimeUser: uTimeElapsed, - TimeSystem: sTimeElapsed, - } -} diff --git a/vendor/google.golang.org/grpc/benchmark/worker/main.go b/vendor/google.golang.org/grpc/benchmark/worker/main.go deleted file mode 100644 index 2b1ba985b..000000000 --- a/vendor/google.golang.org/grpc/benchmark/worker/main.go +++ /dev/null @@ -1,229 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "fmt" - "io" - "net" - "net/http" - _ "net/http/pprof" - "runtime" - "strconv" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" -) - -var ( - driverPort = flag.Int("driver_port", 10000, "port for communication with driver") - serverPort = flag.Int("server_port", 0, "port for benchmark server if not specified by server config message") - pprofPort = flag.Int("pprof_port", -1, "Port for pprof debug server to listen on. Pprof server doesn't start if unset") - blockProfRate = flag.Int("block_prof_rate", 0, "fraction of goroutine blocking events to report in blocking profile") -) - -type byteBufCodec struct { -} - -func (byteBufCodec) Marshal(v interface{}) ([]byte, error) { - b, ok := v.(*[]byte) - if !ok { - return nil, fmt.Errorf("failed to marshal: %v is not type of *[]byte", v) - } - return *b, nil -} - -func (byteBufCodec) Unmarshal(data []byte, v interface{}) error { - b, ok := v.(*[]byte) - if !ok { - return fmt.Errorf("failed to marshal: %v is not type of *[]byte", v) - } - *b = data - return nil -} - -func (byteBufCodec) String() string { - return "bytebuffer" -} - -// workerServer implements WorkerService rpc handlers. -// It can create benchmarkServer or benchmarkClient on demand. -type workerServer struct { - stop chan<- bool - serverPort int -} - -func (s *workerServer) RunServer(stream testpb.WorkerService_RunServerServer) error { - var bs *benchmarkServer - defer func() { - // Close benchmark server when stream ends. - grpclog.Printf("closing benchmark server") - if bs != nil { - bs.closeFunc() - } - }() - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - var out *testpb.ServerStatus - switch argtype := in.Argtype.(type) { - case *testpb.ServerArgs_Setup: - grpclog.Printf("server setup received:") - if bs != nil { - grpclog.Printf("server setup received when server already exists, closing the existing server") - bs.closeFunc() - } - bs, err = startBenchmarkServer(argtype.Setup, s.serverPort) - if err != nil { - return err - } - out = &testpb.ServerStatus{ - Stats: bs.getStats(false), - Port: int32(bs.port), - Cores: int32(bs.cores), - } - - case *testpb.ServerArgs_Mark: - grpclog.Printf("server mark received:") - grpclog.Printf(" - %v", argtype) - if bs == nil { - return grpc.Errorf(codes.InvalidArgument, "server does not exist when mark received") - } - out = &testpb.ServerStatus{ - Stats: bs.getStats(argtype.Mark.Reset_), - Port: int32(bs.port), - Cores: int32(bs.cores), - } - } - - if err := stream.Send(out); err != nil { - return err - } - } -} - -func (s *workerServer) RunClient(stream testpb.WorkerService_RunClientServer) error { - var bc *benchmarkClient - defer func() { - // Shut down benchmark client when stream ends. - grpclog.Printf("shuting down benchmark client") - if bc != nil { - bc.shutdown() - } - }() - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - var out *testpb.ClientStatus - switch t := in.Argtype.(type) { - case *testpb.ClientArgs_Setup: - grpclog.Printf("client setup received:") - if bc != nil { - grpclog.Printf("client setup received when client already exists, shuting down the existing client") - bc.shutdown() - } - bc, err = startBenchmarkClient(t.Setup) - if err != nil { - return err - } - out = &testpb.ClientStatus{ - Stats: bc.getStats(false), - } - - case *testpb.ClientArgs_Mark: - grpclog.Printf("client mark received:") - grpclog.Printf(" - %v", t) - if bc == nil { - return grpc.Errorf(codes.InvalidArgument, "client does not exist when mark received") - } - out = &testpb.ClientStatus{ - Stats: bc.getStats(t.Mark.Reset_), - } - } - - if err := stream.Send(out); err != nil { - return err - } - } -} - -func (s *workerServer) CoreCount(ctx context.Context, in *testpb.CoreRequest) (*testpb.CoreResponse, error) { - grpclog.Printf("core count: %v", runtime.NumCPU()) - return &testpb.CoreResponse{Cores: int32(runtime.NumCPU())}, nil -} - -func (s *workerServer) QuitWorker(ctx context.Context, in *testpb.Void) (*testpb.Void, error) { - grpclog.Printf("quiting worker") - s.stop <- true - return &testpb.Void{}, nil -} - -func main() { - grpc.EnableTracing = false - - flag.Parse() - lis, err := net.Listen("tcp", ":"+strconv.Itoa(*driverPort)) - if err != nil { - grpclog.Fatalf("failed to listen: %v", err) - } - grpclog.Printf("worker listening at port %v", *driverPort) - - s := grpc.NewServer() - stop := make(chan bool) - testpb.RegisterWorkerServiceServer(s, &workerServer{ - stop: stop, - serverPort: *serverPort, - }) - - go func() { - <-stop - // Wait for 1 second before stopping the server to make sure the return value of QuitWorker is sent to client. - // TODO revise this once server graceful stop is supported in gRPC. - time.Sleep(time.Second) - s.Stop() - }() - - runtime.SetBlockProfileRate(*blockProfRate) - - if *pprofPort >= 0 { - go func() { - grpclog.Println("Starting pprof server on port " + strconv.Itoa(*pprofPort)) - grpclog.Println(http.ListenAndServe("localhost:"+strconv.Itoa(*pprofPort), nil)) - }() - } - - s.Serve(lis) -} diff --git a/vendor/google.golang.org/grpc/benchmark/worker/util.go b/vendor/google.golang.org/grpc/benchmark/worker/util.go deleted file mode 100644 index f26993e65..000000000 --- a/vendor/google.golang.org/grpc/benchmark/worker/util.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import "syscall" - -func cpuTimeDiff(first *syscall.Rusage, latest *syscall.Rusage) (float64, float64) { - var ( - utimeDiffs = latest.Utime.Sec - first.Utime.Sec - utimeDiffus = latest.Utime.Usec - first.Utime.Usec - stimeDiffs = latest.Stime.Sec - first.Stime.Sec - stimeDiffus = latest.Stime.Usec - first.Stime.Usec - ) - - uTimeElapsed := float64(utimeDiffs) + float64(utimeDiffus)*1.0e-6 - sTimeElapsed := float64(stimeDiffs) + float64(stimeDiffus)*1.0e-6 - - return uTimeElapsed, sTimeElapsed -} diff --git a/vendor/google.golang.org/grpc/call.go b/vendor/google.golang.org/grpc/call.go index 1ef2507c3..0854f84b9 100644 --- a/vendor/google.golang.org/grpc/call.go +++ b/vendor/google.golang.org/grpc/call.go @@ -19,7 +19,6 @@ package grpc import ( - "bytes" "io" "time" @@ -27,9 +26,9 @@ import ( "golang.org/x/net/trace" "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" + "google.golang.org/grpc/encoding" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" "google.golang.org/grpc/transport" ) @@ -62,7 +61,17 @@ func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTran if c.maxReceiveMessageSize == nil { return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)") } - if err = recv(p, dopts.codec, stream, dopts.dc, reply, *c.maxReceiveMessageSize, inPayload); err != nil { + + // Set dc if it exists and matches the message compression type used, + // otherwise set comp if a registered compressor exists for it. + var comp encoding.Compressor + var dc Decompressor + if rc := stream.RecvCompress(); dopts.dc != nil && dopts.dc.Type() == rc { + dc = dopts.dc + } else if rc != "" && rc != encoding.Identity { + comp = encoding.GetCompressor(rc) + } + if err = recv(p, dopts.codec, stream, dc, reply, *c.maxReceiveMessageSize, inPayload, comp); err != nil { if err == io.EOF { break } @@ -89,18 +98,25 @@ func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, } }() var ( - cbuf *bytes.Buffer outPayload *stats.OutPayload ) - if compressor != nil { - cbuf = new(bytes.Buffer) - } if dopts.copts.StatsHandler != nil { outPayload = &stats.OutPayload{ Client: true, } } - hdr, data, err := encode(dopts.codec, args, compressor, cbuf, outPayload) + // Set comp and clear compressor if a registered compressor matches the type + // specified via UseCompressor. (And error if a matching compressor is not + // registered.) + var comp encoding.Compressor + if ct := c.compressorType; ct != "" && ct != encoding.Identity { + compressor = nil // Disable the legacy compressor. + comp = encoding.GetCompressor(ct) + if comp == nil { + return Errorf(codes.Internal, "grpc: Compressor is not installed for grpc-encoding %q", ct) + } + } + hdr, data, err := encode(dopts.codec, args, compressor, outPayload, comp) if err != nil { return err } @@ -125,16 +141,23 @@ func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, return nil } -// Invoke sends the RPC request on the wire and returns after response is received. -// Invoke is called by generated code. Also users can call Invoke directly when it -// is really needed in their use cases. -func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error { +// Invoke sends the RPC request on the wire and returns after response is +// received. This is typically called by generated code. +func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error { if cc.dopts.unaryInt != nil { return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...) } return invoke(ctx, method, args, reply, cc, opts...) } +// Invoke sends the RPC request on the wire and returns after response is +// received. This is typically called by generated code. +// +// DEPRECATED: Use ClientConn.Invoke instead. +func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error { + return cc.Invoke(ctx, method, args, reply, opts...) +} + func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) { c := defaultCallInfo() mc := cc.GetMethodConfig(method) @@ -202,57 +225,45 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli Last: true, Delay: false, } + callHdr := &transport.CallHdr{ + Host: cc.authority, + Method: method, + } + if c.creds != nil { + callHdr.Creds = c.creds + } + if c.compressorType != "" { + callHdr.SendCompress = c.compressorType + } else if cc.dopts.cp != nil { + callHdr.SendCompress = cc.dopts.cp.Type() + } + firstAttempt := true + for { - var ( - err error - t transport.ClientTransport - stream *transport.Stream - // Record the done handler from Balancer.Get(...). It is called once the - // RPC has completed or failed. - done func(balancer.DoneInfo) - ) - // TODO(zhaoq): Need a formal spec of fail-fast. - callHdr := &transport.CallHdr{ - Host: cc.authority, - Method: method, - } - if cc.dopts.cp != nil { - callHdr.SendCompress = cc.dopts.cp.Type() - } - if c.creds != nil { - callHdr.Creds = c.creds + // Check to make sure the context has expired. This will prevent us from + // looping forever if an error occurs for wait-for-ready RPCs where no data + // is sent on the wire. + select { + case <-ctx.Done(): + return toRPCErr(ctx.Err()) + default: } - t, done, err = cc.getTransport(ctx, c.failFast) + // Record the done handler from Balancer.Get(...). It is called once the + // RPC has completed or failed. + t, done, err := cc.getTransport(ctx, c.failFast) if err != nil { - // TODO(zhaoq): Probably revisit the error handling. - if _, ok := status.FromError(err); ok { - return err - } - if err == errConnClosing || err == errConnUnavailable { - if c.failFast { - return Errorf(codes.Unavailable, "%v", err) - } - continue - } - // All the other errors are treated as Internal errors. - return Errorf(codes.Internal, "%v", err) + return err } - if c.traceInfo.tr != nil { - c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true) - } - stream, err = t.NewStream(ctx, callHdr) + stream, err := t.NewStream(ctx, callHdr) if err != nil { if done != nil { - if _, ok := err.(transport.ConnectionError); ok { - // If error is connection error, transport was sending data on wire, - // and we are not sure if anything has been sent on wire. - // If error is not connection error, we are sure nothing has been sent. - updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false}) - } done(balancer.DoneInfo{Err: err}) } - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { + // In the event of any error from NewStream, we never attempted to write + // anything to the wire, so we can retry indefinitely for non-fail-fast + // RPCs. + if !c.failFast { continue } return toRPCErr(err) @@ -260,20 +271,30 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli if peer, ok := peer.FromContext(stream.Context()); ok { c.peer = peer } + if c.traceInfo.tr != nil { + c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true) + } err = sendRequest(ctx, cc.dopts, cc.dopts.cp, c, callHdr, stream, t, args, topts) if err != nil { if done != nil { updateRPCInfoInContext(ctx, rpcInfo{ - bytesSent: stream.BytesSent(), + bytesSent: true, bytesReceived: stream.BytesReceived(), }) done(balancer.DoneInfo{Err: err}) } // Retry a non-failfast RPC when - // i) there is a connection error; or - // ii) the server started to drain before this RPC was initiated. - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { - continue + // i) the server started to drain before this RPC was initiated. + // ii) the server refused the stream. + if !c.failFast && stream.Unprocessed() { + // In this case, the server did not receive the data, but we still + // created wire traffic, so we should not retry indefinitely. + if firstAttempt { + // TODO: Add a field to header for grpc-transparent-retry-attempts + firstAttempt = false + continue + } + // Otherwise, give up and return an error anyway. } return toRPCErr(err) } @@ -281,13 +302,20 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli if err != nil { if done != nil { updateRPCInfoInContext(ctx, rpcInfo{ - bytesSent: stream.BytesSent(), + bytesSent: true, bytesReceived: stream.BytesReceived(), }) done(balancer.DoneInfo{Err: err}) } - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { - continue + if !c.failFast && stream.Unprocessed() { + // In these cases, the server did not receive the data, but we still + // created wire traffic, so we should not retry indefinitely. + if firstAttempt { + // TODO: Add a field to header for grpc-transparent-retry-attempts + firstAttempt = false + continue + } + // Otherwise, give up and return an error anyway. } return toRPCErr(err) } @@ -297,11 +325,20 @@ func invoke(ctx context.Context, method string, args, reply interface{}, cc *Cli t.CloseStream(stream, nil) if done != nil { updateRPCInfoInContext(ctx, rpcInfo{ - bytesSent: stream.BytesSent(), + bytesSent: true, bytesReceived: stream.BytesReceived(), }) done(balancer.DoneInfo{Err: err}) } + if !c.failFast && stream.Unprocessed() { + // In these cases, the server did not receive the data, but we still + // created wire traffic, so we should not retry indefinitely. + if firstAttempt { + // TODO: Add a field to header for grpc-transparent-retry-attempts + firstAttempt = false + continue + } + } return stream.Status().Err() } } diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index 5462062be..ae605bc32 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -31,11 +31,14 @@ import ( "golang.org/x/net/context" "golang.org/x/net/trace" "google.golang.org/grpc/balancer" + _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin. "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/resolver" + _ "google.golang.org/grpc/resolver/dns" // To register dns resolver. + _ "google.golang.org/grpc/resolver/passthrough" // To register passthrough resolver. "google.golang.org/grpc/stats" "google.golang.org/grpc/transport" ) @@ -48,7 +51,20 @@ var ( // underlying connections within the specified timeout. // DEPRECATED: Please use context.DeadlineExceeded instead. ErrClientConnTimeout = errors.New("grpc: timed out when dialing") + // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs. + errConnDrain = errors.New("grpc: the connection is drained") + // errConnClosing indicates that the connection is closing. + errConnClosing = errors.New("grpc: the connection is closing") + // errConnUnavailable indicates that the connection is unavailable. + errConnUnavailable = errors.New("grpc: the connection is unavailable") + // errBalancerClosed indicates that the balancer is closed. + errBalancerClosed = errors.New("grpc: balancer is closed") + // minimum time to give a connection to complete + minConnectTimeout = 20 * time.Second +) +// The following errors are returned from Dial and DialContext +var ( // errNoTransportSecurity indicates that there is no transport security // being set for ClientConn. Users should either set one or explicitly // call WithInsecure DialOption to disable security. @@ -62,16 +78,6 @@ var ( errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)") // errNetworkIO indicates that the connection is down due to some network I/O error. errNetworkIO = errors.New("grpc: failed with network I/O error") - // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs. - errConnDrain = errors.New("grpc: the connection is drained") - // errConnClosing indicates that the connection is closing. - errConnClosing = errors.New("grpc: the connection is closing") - // errConnUnavailable indicates that the connection is unavailable. - errConnUnavailable = errors.New("grpc: the connection is unavailable") - // errBalancerClosed indicates that the balancer is closed. - errBalancerClosed = errors.New("grpc: balancer is closed") - // minimum time to give a connection to complete - minConnectTimeout = 20 * time.Second ) // dialOptions configure a Dial call. dialOptions are set by the DialOption @@ -152,16 +158,26 @@ func WithCodec(c Codec) DialOption { } } -// WithCompressor returns a DialOption which sets a CompressorGenerator for generating message -// compressor. +// WithCompressor returns a DialOption which sets a Compressor to use for +// message compression. It has lower priority than the compressor set by +// the UseCompressor CallOption. +// +// Deprecated: use UseCompressor instead. func WithCompressor(cp Compressor) DialOption { return func(o *dialOptions) { o.cp = cp } } -// WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating -// message decompressor. +// WithDecompressor returns a DialOption which sets a Decompressor to use for +// incoming message decompression. If incoming response messages are encoded +// using the decompressor's Type(), it will be used. Otherwise, the message +// encoding will be used to look up the compressor registered via +// encoding.RegisterCompressor, which will then be used to decompress the +// message. If no compressor is registered for the encoding, an Unimplemented +// status error will be returned. +// +// Deprecated: use encoding.RegisterCompressor instead. func WithDecompressor(dc Decompressor) DialOption { return func(o *dialOptions) { o.dc = dc @@ -189,6 +205,8 @@ func WithBalancerBuilder(b balancer.Builder) DialOption { } // WithServiceConfig returns a DialOption which has a channel to read the service configuration. +// DEPRECATED: service config should be received through name resolver, as specified here. +// https://github.com/grpc/grpc/blob/master/doc/service_config.md func WithServiceConfig(c <-chan ServiceConfig) DialOption { return func(o *dialOptions) { o.scChan = c @@ -378,7 +396,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if cc.dopts.copts.Dialer == nil { cc.dopts.copts.Dialer = newProxyDialer( func(ctx context.Context, addr string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, "tcp", addr) + return dialContext(ctx, "tcp", addr) }, ) } @@ -426,51 +444,18 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if cc.dopts.bs == nil { cc.dopts.bs = DefaultBackoffConfig } + cc.parsedTarget = parseTarget(cc.target) creds := cc.dopts.copts.TransportCredentials if creds != nil && creds.Info().ServerName != "" { cc.authority = creds.Info().ServerName } else if cc.dopts.insecure && cc.dopts.copts.Authority != "" { cc.authority = cc.dopts.copts.Authority } else { - cc.authority = target + // Use endpoint from "scheme://authority/endpoint" as the default + // authority for ClientConn. + cc.authority = cc.parsedTarget.Endpoint } - if cc.dopts.balancerBuilder != nil { - var credsClone credentials.TransportCredentials - if creds != nil { - credsClone = creds.Clone() - } - buildOpts := balancer.BuildOptions{ - DialCreds: credsClone, - Dialer: cc.dopts.copts.Dialer, - } - // Build should not take long time. So it's ok to not have a goroutine for it. - // TODO(bar) init balancer after first resolver result to support service config balancer. - cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, buildOpts) - } else { - waitC := make(chan error, 1) - go func() { - defer close(waitC) - // No balancer, or no resolver within the balancer. Connect directly. - ac, err := cc.newAddrConn([]resolver.Address{{Addr: target}}) - if err != nil { - waitC <- err - return - } - if err := ac.connect(cc.dopts.block); err != nil { - waitC <- err - return - } - }() - select { - case <-ctx.Done(): - return nil, ctx.Err() - case err := <-waitC: - if err != nil { - return nil, err - } - } - } if cc.dopts.scChan != nil && !scSet { // Blocking wait for the initial service config. select { @@ -486,20 +471,27 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * go cc.scWatcher() } + var credsClone credentials.TransportCredentials + if creds := cc.dopts.copts.TransportCredentials; creds != nil { + credsClone = creds.Clone() + } + cc.balancerBuildOpts = balancer.BuildOptions{ + DialCreds: credsClone, + Dialer: cc.dopts.copts.Dialer, + } + + if cc.dopts.balancerBuilder != nil { + cc.customBalancer = true + // Build should not take long time. So it's ok to not have a goroutine for it. + cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts) + } + // Build the resolver. cc.resolverWrapper, err = newCCResolverWrapper(cc) if err != nil { return nil, fmt.Errorf("failed to build resolver: %v", err) } - if cc.balancerWrapper != nil && cc.resolverWrapper == nil { - // TODO(bar) there should always be a resolver (DNS as the default). - // Unblock balancer initialization with a fake resolver update if there's no resolver. - // The balancer wrapper will not read the addresses, so an empty list works. - // TODO(bar) remove this after the real resolver is started. - cc.balancerWrapper.handleResolvedAddrs([]resolver.Address{}, nil) - } - // A blocking dial blocks until the clientConn is ready. if cc.dopts.block { for { @@ -565,21 +557,26 @@ type ClientConn struct { ctx context.Context cancel context.CancelFunc - target string - authority string - dopts dialOptions - csMgr *connectivityStateManager - - balancerWrapper *ccBalancerWrapper - resolverWrapper *ccResolverWrapper + target string + parsedTarget resolver.Target + authority string + dopts dialOptions + csMgr *connectivityStateManager - blockingpicker *pickerWrapper + customBalancer bool // If this is true, switching balancer will be disabled. + balancerBuildOpts balancer.BuildOptions + resolverWrapper *ccResolverWrapper + blockingpicker *pickerWrapper mu sync.RWMutex sc ServiceConfig + scRaw string conns map[*addrConn]struct{} // Keepalive parameter can be updated if a GoAway is received. - mkp keepalive.ClientParameters + mkp keepalive.ClientParameters + curBalancerName string + curAddresses []resolver.Address + balancerWrapper *ccBalancerWrapper } // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or @@ -615,6 +612,7 @@ func (cc *ClientConn) scWatcher() { // TODO: load balance policy runtime change is ignored. // We may revist this decision in the future. cc.sc = sc + cc.scRaw = "" cc.mu.Unlock() case <-cc.ctx.Done(): return @@ -622,6 +620,69 @@ func (cc *ClientConn) scWatcher() { } } +func (cc *ClientConn) handleResolvedAddrs(addrs []resolver.Address, err error) { + cc.mu.Lock() + defer cc.mu.Unlock() + if cc.conns == nil { + return + } + + // TODO(bar switching) when grpclb is submitted, check address type and start grpclb. + if !cc.customBalancer && cc.balancerWrapper == nil { + // No customBalancer was specified by DialOption, and this is the first + // time handling resolved addresses, create a pickfirst balancer. + builder := newPickfirstBuilder() + cc.curBalancerName = builder.Name() + cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts) + } + + // TODO(bar switching) compare addresses, if there's no update, don't notify balancer. + cc.curAddresses = addrs + cc.balancerWrapper.handleResolvedAddrs(addrs, nil) +} + +// switchBalancer starts the switching from current balancer to the balancer with name. +func (cc *ClientConn) switchBalancer(name string) { + if cc.conns == nil { + return + } + grpclog.Infof("ClientConn switching balancer to %q", name) + + if cc.customBalancer { + grpclog.Infoln("ignoring service config balancer configuration: WithBalancer DialOption used instead") + return + } + + if cc.curBalancerName == name { + return + } + + // TODO(bar switching) change this to two steps: drain and close. + // Keep track of sc in wrapper. + cc.balancerWrapper.close() + + builder := balancer.Get(name) + if builder == nil { + grpclog.Infof("failed to get balancer builder for: %v (this should never happen...)", name) + builder = newPickfirstBuilder() + } + cc.curBalancerName = builder.Name() + cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts) + cc.balancerWrapper.handleResolvedAddrs(cc.curAddresses, nil) +} + +func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { + cc.mu.Lock() + if cc.conns == nil { + cc.mu.Unlock() + return + } + // TODO(bar switching) send updates to all balancer wrappers when balancer + // gracefully switching is supported. + cc.balancerWrapper.handleSubConnStateChange(sc, s) + cc.mu.Unlock() +} + // newAddrConn creates an addrConn for addrs and adds it to cc.conns. func (cc *ClientConn) newAddrConn(addrs []resolver.Address) (*addrConn, error) { ac := &addrConn{ @@ -659,7 +720,7 @@ func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) { // It does nothing if the ac is not IDLE. // TODO(bar) Move this to the addrConn section. // This was part of resetAddrConn, keep it here to make the diff look clean. -func (ac *addrConn) connect(block bool) error { +func (ac *addrConn) connect() error { ac.mu.Lock() if ac.state == connectivity.Shutdown { ac.mu.Unlock() @@ -670,39 +731,21 @@ func (ac *addrConn) connect(block bool) error { return nil } ac.state = connectivity.Connecting - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) ac.mu.Unlock() - if block { + // Start a goroutine connecting to the server asynchronously. + go func() { if err := ac.resetTransport(); err != nil { + grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err) if err != errConnClosing { + // Keep this ac in cc.conns, to get the reason it's torn down. ac.tearDown(err) } - if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() { - return e.Origin() - } - return err + return } - // Start to monitor the error status of transport. - go ac.transportMonitor() - } else { - // Start a goroutine connecting to the server asynchronously. - go func() { - if err := ac.resetTransport(); err != nil { - grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err) - if err != errConnClosing { - // Keep this ac in cc.conns, to get the reason it's torn down. - ac.tearDown(err) - } - return - } - ac.transportMonitor() - }() - } + ac.transportMonitor() + }() return nil } @@ -756,31 +799,6 @@ func (cc *ClientConn) GetMethodConfig(method string) MethodConfig { } func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transport.ClientTransport, func(balancer.DoneInfo), error) { - if cc.balancerWrapper == nil { - // If balancer is nil, there should be only one addrConn available. - cc.mu.RLock() - if cc.conns == nil { - cc.mu.RUnlock() - // TODO this function returns toRPCErr and non-toRPCErr. Clean up - // the errors in ClientConn. - return nil, nil, toRPCErr(ErrClientConnClosing) - } - var ac *addrConn - for ac = range cc.conns { - // Break after the first iteration to get the first addrConn. - break - } - cc.mu.RUnlock() - if ac == nil { - return nil, nil, errConnClosing - } - t, err := ac.wait(ctx, false /*hasBalancer*/, failfast) - if err != nil { - return nil, nil, err - } - return t, nil, nil - } - t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickOptions{}) if err != nil { return nil, nil, toRPCErr(err) @@ -788,6 +806,23 @@ func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transpor return t, done, nil } +// handleServiceConfig parses the service config string in JSON format to Go native +// struct ServiceConfig, and store both the struct and the JSON string in ClientConn. +func (cc *ClientConn) handleServiceConfig(js string) error { + sc, err := parseServiceConfig(js) + if err != nil { + return err + } + cc.mu.Lock() + cc.scRaw = js + cc.sc = sc + if sc.LB != nil { + cc.switchBalancer(*sc.LB) + } + cc.mu.Unlock() + return nil +} + // Close tears down the ClientConn and all underlying connections. func (cc *ClientConn) Close() error { cc.cancel() @@ -800,13 +835,18 @@ func (cc *ClientConn) Close() error { conns := cc.conns cc.conns = nil cc.csMgr.updateState(connectivity.Shutdown) + + rWrapper := cc.resolverWrapper + cc.resolverWrapper = nil + bWrapper := cc.balancerWrapper + cc.balancerWrapper = nil cc.mu.Unlock() cc.blockingpicker.close() - if cc.resolverWrapper != nil { - cc.resolverWrapper.close() + if rWrapper != nil { + rWrapper.close() } - if cc.balancerWrapper != nil { - cc.balancerWrapper.close() + if bWrapper != nil { + bWrapper.close() } for ac := range conns { ac.tearDown(ErrClientConnClosing) @@ -841,7 +881,7 @@ type addrConn struct { // receiving a GoAway. func (ac *addrConn) adjustParams(r transport.GoAwayReason) { switch r { - case transport.TooManyPings: + case transport.GoAwayTooManyPings: v := 2 * ac.dopts.copts.KeepaliveParams.Time ac.cc.mu.Lock() if v > ac.cc.mkp.Time { @@ -902,12 +942,7 @@ func (ac *addrConn) resetTransport() error { ac.printf("connecting") if ac.state != connectivity.Connecting { ac.state = connectivity.Connecting - // TODO(bar) remove condition once we always have a balancer. - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) } // copy ac.addrs in case of race addrsIter := make([]resolver.Address, len(ac.addrs)) @@ -923,12 +958,19 @@ func (ac *addrConn) resetTransport() error { } ac.mu.Unlock() sinfo := transport.TargetInfo{ - Addr: addr.Addr, - Metadata: addr.Metadata, + Addr: addr.Addr, + Metadata: addr.Metadata, + Authority: ac.cc.authority, } newTransport, err := transport.NewClientTransport(ac.cc.ctx, sinfo, copts, timeout) if err != nil { if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() { + ac.mu.Lock() + if ac.state != connectivity.Shutdown { + ac.state = connectivity.TransientFailure + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) + } + ac.mu.Unlock() return err } grpclog.Warningf("grpc: addrConn.resetTransport failed to create client transport: %v; Reconnecting to %v", err, addr) @@ -950,11 +992,7 @@ func (ac *addrConn) resetTransport() error { return errConnClosing } ac.state = connectivity.Ready - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) t := ac.transport ac.transport = newTransport if t != nil { @@ -970,11 +1008,7 @@ func (ac *addrConn) resetTransport() error { } ac.mu.Lock() ac.state = connectivity.TransientFailure - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) if ac.ready != nil { close(ac.ready) ac.ready = nil @@ -1018,11 +1052,7 @@ func (ac *addrConn) transportMonitor() { // Set connectivity state to TransientFailure before calling // resetTransport. Transition READY->CONNECTING is not valid. ac.state = connectivity.TransientFailure - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) ac.curAddr = resolver.Address{} ac.mu.Unlock() if err := ac.resetTransport(); err != nil { @@ -1096,7 +1126,7 @@ func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) { ac.mu.Unlock() // Trigger idle ac to connect. if idle { - ac.connect(false) + ac.connect() } return nil, false } @@ -1109,8 +1139,8 @@ func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) { func (ac *addrConn) tearDown(err error) { ac.cancel() ac.mu.Lock() - ac.curAddr = resolver.Address{} defer ac.mu.Unlock() + ac.curAddr = resolver.Address{} if err == errConnDrain && ac.transport != nil { // GracefulClose(...) may be executed multiple times when // i) receiving multiple GoAway frames from the server; or @@ -1123,11 +1153,7 @@ func (ac *addrConn) tearDown(err error) { } ac.state = connectivity.Shutdown ac.tearDownErr = err - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) if ac.events != nil { ac.events.Finish() ac.events = nil diff --git a/vendor/google.golang.org/grpc/clientconn_test.go b/vendor/google.golang.org/grpc/clientconn_test.go index 47801e962..c0b0ba436 100644 --- a/vendor/google.golang.org/grpc/clientconn_test.go +++ b/vendor/google.golang.org/grpc/clientconn_test.go @@ -30,6 +30,7 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/naming" + _ "google.golang.org/grpc/resolver/passthrough" "google.golang.org/grpc/test/leakcheck" "google.golang.org/grpc/testdata" ) @@ -47,7 +48,7 @@ func TestConnectivityStates(t *testing.T) { defer leakcheck.Check(t) servers, resolver, cleanup := startServers(t, 2, math.MaxUint32) defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(resolver)), WithInsecure()) + cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(resolver)), WithInsecure()) if err != nil { t.Fatalf("Dial(\"foo.bar.com\", WithBalancer(_)) = _, %v, want _ <nil>", err) } @@ -82,7 +83,7 @@ func TestConnectivityStates(t *testing.T) { func TestDialTimeout(t *testing.T) { defer leakcheck.Check(t) - conn, err := Dial("Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) + conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) if err == nil { conn.Close() } @@ -97,7 +98,7 @@ func TestTLSDialTimeout(t *testing.T) { if err != nil { t.Fatalf("Failed to create credentials %v", err) } - conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds), WithTimeout(time.Millisecond), WithBlock()) + conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds), WithTimeout(time.Millisecond), WithBlock()) if err == nil { conn.Close() } @@ -113,7 +114,7 @@ func TestDefaultAuthority(t *testing.T) { if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } - conn.Close() + defer conn.Close() if conn.authority != target { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, target) } @@ -126,11 +127,11 @@ func TestTLSServerNameOverwrite(t *testing.T) { if err != nil { t.Fatalf("Failed to create credentials %v", err) } - conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds)) + conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds)) if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } - conn.Close() + defer conn.Close() if conn.authority != overwriteServerName { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) } @@ -139,11 +140,11 @@ func TestTLSServerNameOverwrite(t *testing.T) { func TestWithAuthority(t *testing.T) { defer leakcheck.Check(t) overwriteServerName := "over.write.server.name" - conn, err := Dial("Non-Existent.Server:80", WithInsecure(), WithAuthority(overwriteServerName)) + conn, err := Dial("passthrough:///Non-Existent.Server:80", WithInsecure(), WithAuthority(overwriteServerName)) if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } - conn.Close() + defer conn.Close() if conn.authority != overwriteServerName { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) } @@ -156,11 +157,11 @@ func TestWithAuthorityAndTLS(t *testing.T) { if err != nil { t.Fatalf("Failed to create credentials %v", err) } - conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds), WithAuthority("no.effect.authority")) + conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds), WithAuthority("no.effect.authority")) if err != nil { t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) } - conn.Close() + defer conn.Close() if conn.authority != overwriteServerName { t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) } @@ -231,11 +232,11 @@ func TestCredentialsMisuse(t *testing.T) { t.Fatalf("Failed to create authenticator %v", err) } // Two conflicting credential configurations - if _, err := Dial("Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict { + if _, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errCredentialsConflict) } // security info on insecure connection - if _, err := Dial("Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing { + if _, err := Dial("passthrough:///Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing { t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errTransportCredentialsMissing) } } @@ -263,10 +264,11 @@ func TestWithBackoffMaxDelay(t *testing.T) { func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOption) { opts = append(opts, WithInsecure()) - conn, err := Dial("foo:80", opts...) + conn, err := Dial("passthrough:///foo:80", opts...) if err != nil { t.Fatalf("unexpected error dialing connection: %v", err) } + defer conn.Close() if conn.dopts.bs == nil { t.Fatalf("backoff config not set") @@ -280,39 +282,6 @@ func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOpt if actual != *expected { t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected) } - conn.Close() -} - -type testErr struct { - temp bool -} - -func (e *testErr) Error() string { - return "test error" -} - -func (e *testErr) Temporary() bool { - return e.temp -} - -var nonTemporaryError = &testErr{false} - -func nonTemporaryErrorDialer(addr string, timeout time.Duration) (net.Conn, error) { - return nil, nonTemporaryError -} - -func TestDialWithBlockErrorOnNonTemporaryErrorDialer(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock(), FailOnNonTempDialError(true)); err != nonTemporaryError { - t.Fatalf("Dial(%q) = %v, want %v", "", err, nonTemporaryError) - } - - // Without FailOnNonTempDialError, gRPC will retry to connect, and dial should exit with time out error. - if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock()); err != context.DeadlineExceeded { - t.Fatalf("Dial(%q) = %v, want %v", "", err, context.DeadlineExceeded) - } } // emptyBalancer returns an empty set of servers. diff --git a/vendor/google.golang.org/grpc/codec.go b/vendor/google.golang.org/grpc/codec.go index 905b048e2..b452a4ae8 100644 --- a/vendor/google.golang.org/grpc/codec.go +++ b/vendor/google.golang.org/grpc/codec.go @@ -92,13 +92,11 @@ func (protoCodec) String() string { return "proto" } -var ( - protoBufferPool = &sync.Pool{ - New: func() interface{} { - return &cachedProtoBuffer{ - Buffer: proto.Buffer{}, - lastMarshaledSize: 16, - } - }, - } -) +var protoBufferPool = &sync.Pool{ + New: func() interface{} { + return &cachedProtoBuffer{ + Buffer: proto.Buffer{}, + lastMarshaledSize: 16, + } + }, +} diff --git a/vendor/google.golang.org/grpc/codec_benchmark_test.go b/vendor/google.golang.org/grpc/codec_benchmark_test.go index dee617ca2..2286fd813 100644 --- a/vendor/google.golang.org/grpc/codec_benchmark_test.go +++ b/vendor/google.golang.org/grpc/codec_benchmark_test.go @@ -28,7 +28,7 @@ import ( "google.golang.org/grpc/test/codec_perf" ) -func setupBenchmarkProtoCodecInputs(b *testing.B, payloadBaseSize uint32) []proto.Message { +func setupBenchmarkProtoCodecInputs(payloadBaseSize uint32) []proto.Message { payloadBase := make([]byte, payloadBaseSize) // arbitrary byte slices payloadSuffixes := [][]byte{ @@ -59,23 +59,21 @@ func BenchmarkProtoCodec(b *testing.B) { payloadBaseSizes = append(payloadBaseSizes, 1<<i) } // range of SetParallelism - parallelisms := make([]uint32, 0) + parallelisms := make([]int, 0) for i := uint32(0); i <= 16; i += 4 { - parallelisms = append(parallelisms, 1<<i) + parallelisms = append(parallelisms, int(1<<i)) } for _, s := range payloadBaseSizes { for _, p := range parallelisms { - func(parallelism int, payloadBaseSize uint32) { - protoStructs := setupBenchmarkProtoCodecInputs(b, payloadBaseSize) - name := fmt.Sprintf("MinPayloadSize:%v/SetParallelism(%v)", payloadBaseSize, parallelism) - b.Run(name, func(b *testing.B) { - codec := &protoCodec{} - b.SetParallelism(parallelism) - b.RunParallel(func(pb *testing.PB) { - benchmarkProtoCodec(codec, protoStructs, pb, b) - }) + protoStructs := setupBenchmarkProtoCodecInputs(s) + name := fmt.Sprintf("MinPayloadSize:%v/SetParallelism(%v)", s, p) + b.Run(name, func(b *testing.B) { + codec := &protoCodec{} + b.SetParallelism(p) + b.RunParallel(func(pb *testing.PB) { + benchmarkProtoCodec(codec, protoStructs, pb, b) }) - }(int(p), s) + }) } } } @@ -94,7 +92,8 @@ func fastMarshalAndUnmarshal(protoCodec Codec, protoStruct proto.Message, b *tes if err != nil { b.Errorf("protoCodec.Marshal(_) returned an error") } - if err := protoCodec.Unmarshal(marshaledBytes, protoStruct); err != nil { + res := codec_perf.Buffer{} + if err := protoCodec.Unmarshal(marshaledBytes, &res); err != nil { b.Errorf("protoCodec.Unmarshal(_) returned an error") } } diff --git a/vendor/google.golang.org/grpc/codes/code_string.go b/vendor/google.golang.org/grpc/codes/code_string.go index 259837060..d9cf9675b 100644 --- a/vendor/google.golang.org/grpc/codes/code_string.go +++ b/vendor/google.golang.org/grpc/codes/code_string.go @@ -2,7 +2,7 @@ package codes -import "fmt" +import "strconv" const _Code_name = "OKCanceledUnknownInvalidArgumentDeadlineExceededNotFoundAlreadyExistsPermissionDeniedResourceExhaustedFailedPreconditionAbortedOutOfRangeUnimplementedInternalUnavailableDataLossUnauthenticated" @@ -10,7 +10,7 @@ var _Code_index = [...]uint8{0, 2, 10, 17, 32, 48, 56, 69, 85, 102, 120, 127, 13 func (i Code) String() string { if i >= Code(len(_Code_index)-1) { - return fmt.Sprintf("Code(%d)", i) + return "Code(" + strconv.FormatInt(int64(i), 10) + ")" } return _Code_name[_Code_index[i]:_Code_index[i+1]] } diff --git a/vendor/google.golang.org/grpc/credentials/credentials.go b/vendor/google.golang.org/grpc/credentials/credentials.go index 2475fe832..1d2e864f8 100644 --- a/vendor/google.golang.org/grpc/credentials/credentials.go +++ b/vendor/google.golang.org/grpc/credentials/credentials.go @@ -34,10 +34,8 @@ import ( "golang.org/x/net/context" ) -var ( - // alpnProtoStr are the specified application level protocols for gRPC. - alpnProtoStr = []string{"h2"} -) +// alpnProtoStr are the specified application level protocols for gRPC. +var alpnProtoStr = []string{"h2"} // PerRPCCredentials defines the common interface for the credentials which need to // attach security information to every RPC (e.g., oauth2). @@ -74,11 +72,9 @@ type AuthInfo interface { AuthType() string } -var ( - // ErrConnDispatched indicates that rawConn has been dispatched out of gRPC - // and the caller should not close rawConn. - ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") -) +// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC +// and the caller should not close rawConn. +var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") // TransportCredentials defines the common interface for all the live gRPC wire // protocols and supported transport security protocols (e.g., TLS, SSL). @@ -91,10 +87,14 @@ type TransportCredentials interface { // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). // If the returned error is a wrapper error, implementations should make sure that // the error implements Temporary() to have the correct retry behaviors. + // + // If the returned net.Conn is closed, it MUST close the net.Conn provided. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) // ServerHandshake does the authentication handshake for servers. It returns // the authenticated connection and the corresponding auth information about // the connection. + // + // If the returned net.Conn is closed, it MUST close the net.Conn provided. ServerHandshake(net.Conn) (net.Conn, AuthInfo, error) // Info provides the ProtocolInfo of this TransportCredentials. Info() ProtocolInfo @@ -131,15 +131,15 @@ func (c tlsCreds) Info() ProtocolInfo { } } -func (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { +func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { // use local cfg to avoid clobbering ServerName if using multiple endpoints cfg := cloneTLSConfig(c.config) if cfg.ServerName == "" { - colonPos := strings.LastIndex(addr, ":") + colonPos := strings.LastIndex(authority, ":") if colonPos == -1 { - colonPos = len(addr) + colonPos = len(authority) } - cfg.ServerName = addr[:colonPos] + cfg.ServerName = authority[:colonPos] } conn := tls.Client(rawConn, cfg) errChannel := make(chan error, 1) diff --git a/vendor/google.golang.org/grpc/credentials/oauth/oauth.go b/vendor/google.golang.org/grpc/credentials/oauth/oauth.go deleted file mode 100644 index f6d597a14..000000000 --- a/vendor/google.golang.org/grpc/credentials/oauth/oauth.go +++ /dev/null @@ -1,173 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package oauth implements gRPC credentials using OAuth. -package oauth - -import ( - "fmt" - "io/ioutil" - "sync" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/grpc/credentials" -) - -// TokenSource supplies PerRPCCredentials from an oauth2.TokenSource. -type TokenSource struct { - oauth2.TokenSource -} - -// GetRequestMetadata gets the request metadata as a map from a TokenSource. -func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - token, err := ts.Token() - if err != nil { - return nil, err - } - return map[string]string{ - "authorization": token.Type() + " " + token.AccessToken, - }, nil -} - -// RequireTransportSecurity indicates whether the credentials requires transport security. -func (ts TokenSource) RequireTransportSecurity() bool { - return true -} - -type jwtAccess struct { - jsonKey []byte -} - -// NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile. -func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) - } - return NewJWTAccessFromKey(jsonKey) -} - -// NewJWTAccessFromKey creates PerRPCCredentials from the given jsonKey. -func NewJWTAccessFromKey(jsonKey []byte) (credentials.PerRPCCredentials, error) { - return jwtAccess{jsonKey}, nil -} - -func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, uri[0]) - if err != nil { - return nil, err - } - token, err := ts.Token() - if err != nil { - return nil, err - } - return map[string]string{ - "authorization": token.Type() + " " + token.AccessToken, - }, nil -} - -func (j jwtAccess) RequireTransportSecurity() bool { - return true -} - -// oauthAccess supplies PerRPCCredentials from a given token. -type oauthAccess struct { - token oauth2.Token -} - -// NewOauthAccess constructs the PerRPCCredentials using a given token. -func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials { - return oauthAccess{token: *token} -} - -func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return map[string]string{ - "authorization": oa.token.Type() + " " + oa.token.AccessToken, - }, nil -} - -func (oa oauthAccess) RequireTransportSecurity() bool { - return true -} - -// NewComputeEngine constructs the PerRPCCredentials that fetches access tokens from -// Google Compute Engine (GCE)'s metadata server. It is only valid to use this -// if your program is running on a GCE instance. -// TODO(dsymonds): Deprecate and remove this. -func NewComputeEngine() credentials.PerRPCCredentials { - return TokenSource{google.ComputeTokenSource("")} -} - -// serviceAccount represents PerRPCCredentials via JWT signing key. -type serviceAccount struct { - mu sync.Mutex - config *jwt.Config - t *oauth2.Token -} - -func (s *serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - s.mu.Lock() - defer s.mu.Unlock() - if !s.t.Valid() { - var err error - s.t, err = s.config.TokenSource(ctx).Token() - if err != nil { - return nil, err - } - } - return map[string]string{ - "authorization": s.t.Type() + " " + s.t.AccessToken, - }, nil -} - -func (s *serviceAccount) RequireTransportSecurity() bool { - return true -} - -// NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice -// from a Google Developers service account. -func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) { - config, err := google.JWTConfigFromJSON(jsonKey, scope...) - if err != nil { - return nil, err - } - return &serviceAccount{config: config}, nil -} - -// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file -// of a Google Developers service account. -func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) - } - return NewServiceAccountFromKey(jsonKey, scope...) -} - -// NewApplicationDefault returns "Application Default Credentials". For more -// detail, see https://developers.google.com/accounts/docs/application-default-credentials. -func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) { - t, err := google.DefaultTokenSource(ctx, scope...) - if err != nil { - return nil, err - } - return TokenSource{t}, nil -} diff --git a/vendor/google.golang.org/grpc/encoding/encoding.go b/vendor/google.golang.org/grpc/encoding/encoding.go new file mode 100644 index 000000000..47d10b076 --- /dev/null +++ b/vendor/google.golang.org/grpc/encoding/encoding.go @@ -0,0 +1,61 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Package encoding defines the interface for the compressor and the functions +// to register and get the compossor. +// This package is EXPERIMENTAL. +package encoding + +import ( + "io" +) + +var registerCompressor = make(map[string]Compressor) + +// Compressor is used for compressing and decompressing when sending or receiving messages. +type Compressor interface { + // Compress writes the data written to wc to w after compressing it. If an error + // occurs while initializing the compressor, that error is returned instead. + Compress(w io.Writer) (io.WriteCloser, error) + // Decompress reads data from r, decompresses it, and provides the uncompressed data + // via the returned io.Reader. If an error occurs while initializing the decompressor, that error + // is returned instead. + Decompress(r io.Reader) (io.Reader, error) + // Name is the name of the compression codec and is used to set the content coding header. + Name() string +} + +// RegisterCompressor registers the compressor with gRPC by its name. It can be activated when +// sending an RPC via grpc.UseCompressor(). It will be automatically accessed when receiving a +// message based on the content coding header. Servers also use it to send a response with the +// same encoding as the request. +// +// NOTE: this function must only be called during initialization time (i.e. in an init() function). If +// multiple Compressors are registered with the same name, the one registered last will take effect. +func RegisterCompressor(c Compressor) { + registerCompressor[c.Name()] = c +} + +// GetCompressor returns Compressor for the given compressor name. +func GetCompressor(name string) Compressor { + return registerCompressor[name] +} + +// Identity specifies the optional encoding for uncompressed streams. +// It is intended for grpc internal use only. +const Identity = "identity" diff --git a/vendor/google.golang.org/grpc/examples/README.md b/vendor/google.golang.org/grpc/examples/README.md deleted file mode 100644 index 6d9175c68..000000000 --- a/vendor/google.golang.org/grpc/examples/README.md +++ /dev/null @@ -1,60 +0,0 @@ -gRPC in 3 minutes (Go) -====================== - -BACKGROUND -------------- -For this sample, we've already generated the server and client stubs from [helloworld.proto](helloworld/helloworld/helloworld.proto). - -PREREQUISITES -------------- - -- This requires Go 1.7 or later -- Requires that [GOPATH is set](https://golang.org/doc/code.html#GOPATH) - -``` -$ go help gopath -$ # ensure the PATH contains $GOPATH/bin -$ export PATH=$PATH:$GOPATH/bin -``` - -INSTALL -------- - -``` -$ go get -u google.golang.org/grpc/examples/helloworld/greeter_client -$ go get -u google.golang.org/grpc/examples/helloworld/greeter_server -``` - -TRY IT! -------- - -- Run the server - -``` -$ greeter_server & -``` - -- Run the client - -``` -$ greeter_client -``` - -OPTIONAL - Rebuilding the generated code ----------------------------------------- - -1 First [install protoc](https://github.com/google/protobuf/blob/master/README.md) - - For now, this needs to be installed from source - - This is will change once proto3 is officially released - -2 Install the protoc Go plugin. - -``` -$ go get -a github.com/golang/protobuf/protoc-gen-go -``` - -3 Rebuild the generated Go code. - -``` -$ go generate google.golang.org/grpc/examples/helloworld/... -``` diff --git a/vendor/google.golang.org/grpc/examples/gotutorial.md b/vendor/google.golang.org/grpc/examples/gotutorial.md deleted file mode 100644 index a520a5a15..000000000 --- a/vendor/google.golang.org/grpc/examples/gotutorial.md +++ /dev/null @@ -1,431 +0,0 @@ -# gRPC Basics: Go - -This tutorial provides a basic Go programmer's introduction to working with gRPC. By walking through this example you'll learn how to: - -- Define a service in a `.proto` file. -- Generate server and client code using the protocol buffer compiler. -- Use the Go gRPC API to write a simple client and server for your service. - -It assumes that you have read the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide and are familiar with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository. - -This isn't a comprehensive guide to using gRPC in Go: more reference documentation is coming soon. - -## Why use gRPC? - -Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients. - -With gRPC we can define our service once in a `.proto` file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating. - -## Example code and setup - -The example code for our tutorial is in [grpc/grpc-go/examples/route_guide](https://github.com/grpc/grpc-go/tree/master/examples/route_guide). To download the example, clone the `grpc-go` repository by running the following command: -```shell -$ go get google.golang.org/grpc -``` - -Then change your current directory to `grpc-go/examples/route_guide`: -```shell -$ cd $GOPATH/src/google.golang.org/grpc/examples/route_guide -``` - -You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Go quick start guide](https://github.com/grpc/grpc-go/tree/master/examples/). - - -## Defining the service - -Our first step (as you'll know from the [quick start](https://grpc.io/docs/#quick-start)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete `.proto` file in [examples/route_guide/routeguide/route_guide.proto](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/routeguide/route_guide.proto). - -To define a service, you specify a named `service` in your `.proto` file: - -```proto -service RouteGuide { - ... -} -``` - -Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service: - -- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call. -```proto - // Obtains the feature at a given position. - rpc GetFeature(Point) returns (Feature) {} -``` - -- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type. -```proto - // Obtains the Features available within the given Rectangle. Results are - // 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 - // huge number of features. - rpc ListFeatures(Rectangle) returns (stream Feature) {} -``` - -- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the `stream` keyword before the *request* type. -```proto - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - rpc RecordRoute(stream Point) returns (RouteSummary) {} -``` - -- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response. -```proto - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} -``` - -Our `.proto` file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type: -```proto -// Points are represented as latitude-longitude pairs in the E7 representation -// (degrees multiplied by 10**7 and rounded to the nearest integer). -// Latitudes should be in the range +/- 90 degrees and longitude should be in -// the range +/- 180 degrees (inclusive). -message Point { - int32 latitude = 1; - int32 longitude = 2; -} -``` - - -## Generating client and server code - -Next we need to generate the gRPC client and server interfaces from our `.proto` service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Go plugin. - -For simplicity, we've provided a [bash script](https://github.com/grpc/grpc-go/blob/master/codegen.sh) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this by yourself, make sure you've installed protoc and followed the gRPC-Go [installation instructions](https://github.com/grpc/grpc-go/blob/master/README.md) first): - -```shell -$ codegen.sh route_guide.proto -``` - -which actually runs: - -```shell -$ protoc --go_out=plugins=grpc:. route_guide.proto -``` - -Running this command generates the following file in your current directory: -- `route_guide.pb.go` - -This contains: -- All the protocol buffer code to populate, serialize, and retrieve our request and response message types -- An interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service. -- An interface type for servers to implement, also with the methods defined in the `RouteGuide` service. - - -<a name="server"></a> -## Creating the server - -First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!). - -There are two parts to making our `RouteGuide` service do its job: -- Implementing the service interface generated from our service definition: doing the actual "work" of our service. -- Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation. - -You can find our example `RouteGuide` server in [grpc-go/examples/route_guide/server/server.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/server/server.go). Let's take a closer look at how it works. - -### Implementing RouteGuide - -As you can see, our server has a `routeGuideServer` struct type that implements the generated `RouteGuideServer` interface: - -```go -type routeGuideServer struct { - ... -} -... - -func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { - ... -} -... - -func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { - ... -} -... - -func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { - ... -} -... - -func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { - ... -} -... -``` - -#### Simple RPC -`routeGuideServer` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. - -```go -func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - return feature, nil - } - } - // No feature was found, return an unnamed feature - return &pb.Feature{"", point}, nil -} -``` - -The method is passed a context object for the RPC and the client's `Point` protocol buffer request. It returns a `Feature` protocol buffer object with the response information and an `error`. In the method we populate the `Feature` with the appropriate information, and then `return` it along with an `nil` error to tell gRPC that we've finished dealing with the RPC and that the `Feature` can be returned to the client. - -#### Server-side streaming RPC -Now let's look at one of our streaming RPCs. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. - -```go -func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { - for _, feature := range s.savedFeatures { - if inRange(feature.Location, rect) { - if err := stream.Send(feature); err != nil { - return err - } - } - } - return nil -} -``` - -As you can see, instead of getting simple request and response objects in our method parameters, this time we get a request object (the `Rectangle` in which our client wants to find `Feature`s) and a special `RouteGuide_ListFeaturesServer` object to write our responses. - -In the method, we populate as many `Feature` objects as we need to return, writing them to the `RouteGuide_ListFeaturesServer` using its `Send()` method. Finally, as in our simple RPC, we return a `nil` error to tell gRPC that we've finished writing responses. Should any error happen in this call, we return a non-`nil` error; the gRPC layer will translate it into an appropriate RPC status to be sent on the wire. - -#### Client-side streaming RPC -Now let's look at something a little more complicated: the client-side streaming method `RecordRoute`, where we get a stream of `Point`s from the client and return a single `RouteSummary` with information about their trip. As you can see, this time the method doesn't have a request parameter at all. Instead, it gets a `RouteGuide_RecordRouteServer` stream, which the server can use to both read *and* write messages - it can receive client messages using its `Recv()` method and return its single response using its `SendAndClose()` method. - -```go -func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { - var pointCount, featureCount, distance int32 - var lastPoint *pb.Point - startTime := time.Now() - for { - point, err := stream.Recv() - if err == io.EOF { - endTime := time.Now() - return stream.SendAndClose(&pb.RouteSummary{ - PointCount: pointCount, - FeatureCount: featureCount, - Distance: distance, - ElapsedTime: int32(endTime.Sub(startTime).Seconds()), - }) - } - if err != nil { - return err - } - pointCount++ - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - featureCount++ - } - } - if lastPoint != nil { - distance += calcDistance(lastPoint, point) - } - lastPoint = point - } -} -``` - -In the method body we use the `RouteGuide_RecordRouteServer`s `Recv()` method to repeatedly read in our client's requests to a request object (in this case a `Point`) until there are no more messages: the server needs to check the the error returned from `Recv()` after each call. If this is `nil`, the stream is still good and it can continue reading; if it's `io.EOF` the message stream has ended and the server can return its `RouteSummary`. If it has any other value, we return the error "as is" so that it'll be translated to an RPC status by the gRPC layer. - -#### Bidirectional streaming RPC -Finally, let's look at our bidirectional streaming RPC `RouteChat()`. - -```go -func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - key := serialize(in.Location) - ... // look for notes to be sent to client - for _, note := range s.routeNotes[key] { - if err := stream.Send(note); err != nil { - return err - } - } - } -} -``` - -This time we get a `RouteGuide_RouteChatServer` stream that, as in our client-side streaming example, can be used to read and write messages. However, this time we return values via our method's stream while the client is still writing messages to *their* message stream. - -The syntax for reading and writing here is very similar to our client-streaming method, except the server uses the stream's `Send()` method rather than `SendAndClose()` because it's writing multiple responses. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. - -### Starting the server - -Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service: - -```go -flag.Parse() -lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port)) -if err != nil { - log.Fatalf("failed to listen: %v", err) -} -grpcServer := grpc.NewServer() -pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{}) -... // determine whether to use TLS -grpcServer.Serve(lis) -``` -To build and start a server, we: - -1. Specify the port we want to use to listen for client requests using `lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))`. -2. Create an instance of the gRPC server using `grpc.NewServer()`. -3. Register our service implementation with the gRPC server. -4. Call `Serve()` on the server with our port details to do a blocking wait until the process is killed or `Stop()` is called. - -<a name="client"></a> -## Creating the client - -In this section, we'll look at creating a Go client for our `RouteGuide` service. You can see our complete example client code in [grpc-go/examples/route_guide/client/client.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/client/client.go). - -### Creating a stub - -To call service methods, we first need to create a gRPC *channel* to communicate with the server. We create this by passing the server address and port number to `grpc.Dial()` as follows: - -```go -conn, err := grpc.Dial(*serverAddr) -if err != nil { - ... -} -defer conn.Close() -``` - -You can use `DialOptions` to set the auth credentials (e.g., TLS, GCE credentials, JWT credentials) in `grpc.Dial` if the service you request requires that - however, we don't need to do this for our `RouteGuide` service. - -Once the gRPC *channel* is setup, we need a client *stub* to perform RPCs. We get this using the `NewRouteGuideClient` method provided in the `pb` package we generated from our `.proto` file. - -```go -client := pb.NewRouteGuideClient(conn) -``` - -### Calling service methods - -Now let's look at how we call our service methods. Note that in gRPC-Go, RPCs operate in a blocking/synchronous mode, which means that the RPC call waits for the server to respond, and will either return a response or an error. - -#### Simple RPC - -Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method. - -```go -feature, err := client.GetFeature(context.Background(), &pb.Point{409146138, -746188906}) -if err != nil { - ... -} -``` - -As you can see, we call the method on the stub we got earlier. In our method parameters we create and populate a request protocol buffer object (in our case `Point`). We also pass a `context.Context` object which lets us change our RPC's behaviour if necessary, such as time-out/cancel an RPC in flight. If the call doesn't return an error, then we can read the response information from the server from the first return value. - -```go -log.Println(feature) -``` - -#### Server-side streaming RPC - -Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. - -```go -rect := &pb.Rectangle{ ... } // initialize a pb.Rectangle -stream, err := client.ListFeatures(context.Background(), rect) -if err != nil { - ... -} -for { - feature, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - log.Println(feature) -} -``` - -As in the simple RPC, we pass the method a context and a request. However, instead of getting a response object back, we get back an instance of `RouteGuide_ListFeaturesClient`. The client can use the `RouteGuide_ListFeaturesClient` stream to read the server's responses. - -We use the `RouteGuide_ListFeaturesClient`'s `Recv()` method to repeatedly read in the server's responses to a response protocol buffer object (in this case a `Feature`) until there are no more messages: the client needs to check the error `err` returned from `Recv()` after each call. If `nil`, the stream is still good and it can continue reading; if it's `io.EOF` then the message stream has ended; otherwise there must be an RPC error, which is passed over through `err`. - -#### Client-side streaming RPC - -The client-side streaming method `RecordRoute` is similar to the server-side method, except that we only pass the method a context and get a `RouteGuide_RecordRouteClient` stream back, which we can use to both write *and* read messages. - -```go -// Create a random number of random points -r := rand.New(rand.NewSource(time.Now().UnixNano())) -pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points -var points []*pb.Point -for i := 0; i < pointCount; i++ { - points = append(points, randomPoint(r)) -} -log.Printf("Traversing %d points.", len(points)) -stream, err := client.RecordRoute(context.Background()) -if err != nil { - log.Fatalf("%v.RecordRoute(_) = _, %v", client, err) -} -for _, point := range points { - if err := stream.Send(point); err != nil { - log.Fatalf("%v.Send(%v) = %v", stream, point, err) - } -} -reply, err := stream.CloseAndRecv() -if err != nil { - log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) -} -log.Printf("Route summary: %v", reply) -``` - -The `RouteGuide_RecordRouteClient` has a `Send()` method that we can use to send requests to the server. Once we've finished writing our client's requests to the stream using `Send()`, we need to call `CloseAndRecv()` on the stream to let gRPC know that we've finished writing and are expecting to receive a response. We get our RPC status from the `err` returned from `CloseAndRecv()`. If the status is `nil`, then the first return value from `CloseAndRecv()` will be a valid server response. - -#### Bidirectional streaming RPC - -Finally, let's look at our bidirectional streaming RPC `RouteChat()`. As in the case of `RecordRoute`, we only pass the method a context object and get back a stream that we can use to both write and read messages. However, this time we return values via our method's stream while the server is still writing messages to *their* message stream. - -```go -stream, err := client.RouteChat(context.Background()) -waitc := make(chan struct{}) -go func() { - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - close(waitc) - return - } - if err != nil { - log.Fatalf("Failed to receive a note : %v", err) - } - log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude) - } -}() -for _, note := range notes { - if err := stream.Send(note); err != nil { - log.Fatalf("Failed to send a note: %v", err) - } -} -stream.CloseSend() -<-waitc -``` - -The syntax for reading and writing here is very similar to our client-side streaming method, except we use the stream's `CloseSend()` method once we've finished our call. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. - -## Try it out! - -To compile and run the server, assuming you are in the folder -`$GOPATH/src/google.golang.org/grpc/examples/route_guide`, simply: - -```sh -$ go run server/server.go -``` - -Likewise, to run the client: - -```sh -$ go run client/client.go -``` - diff --git a/vendor/google.golang.org/grpc/examples/helloworld/greeter_client/main.go b/vendor/google.golang.org/grpc/examples/helloworld/greeter_client/main.go deleted file mode 100644 index 3dc426e24..000000000 --- a/vendor/google.golang.org/grpc/examples/helloworld/greeter_client/main.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "log" - "os" - - "golang.org/x/net/context" - "google.golang.org/grpc" - pb "google.golang.org/grpc/examples/helloworld/helloworld" -) - -const ( - address = "localhost:50051" - defaultName = "world" -) - -func main() { - // Set up a connection to the server. - conn, err := grpc.Dial(address, grpc.WithInsecure()) - if err != nil { - log.Fatalf("did not connect: %v", err) - } - defer conn.Close() - c := pb.NewGreeterClient(conn) - - // Contact the server and print out its response. - name := defaultName - if len(os.Args) > 1 { - name = os.Args[1] - } - r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) - if err != nil { - log.Fatalf("could not greet: %v", err) - } - log.Printf("Greeting: %s", r.Message) -} diff --git a/vendor/google.golang.org/grpc/examples/helloworld/greeter_server/main.go b/vendor/google.golang.org/grpc/examples/helloworld/greeter_server/main.go deleted file mode 100644 index 702a3b617..000000000 --- a/vendor/google.golang.org/grpc/examples/helloworld/greeter_server/main.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc -I ../helloworld --go_out=plugins=grpc:../helloworld ../helloworld/helloworld.proto - -package main - -import ( - "log" - "net" - - "golang.org/x/net/context" - "google.golang.org/grpc" - pb "google.golang.org/grpc/examples/helloworld/helloworld" - "google.golang.org/grpc/reflection" -) - -const ( - port = ":50051" -) - -// server is used to implement helloworld.GreeterServer. -type server struct{} - -// 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 -} - -func main() { - lis, err := net.Listen("tcp", port) - if err != nil { - log.Fatalf("failed to listen: %v", err) - } - s := grpc.NewServer() - pb.RegisterGreeterServer(s, &server{}) - // Register reflection service on gRPC server. - reflection.Register(s) - if err := s.Serve(lis); err != nil { - log.Fatalf("failed to serve: %v", err) - } -} diff --git a/vendor/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go b/vendor/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go deleted file mode 100644 index 64bd1ef3c..000000000 --- a/vendor/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helloworld.proto - -/* -Package helloworld is a generated protocol buffer package. - -It is generated from these files: - helloworld.proto - -It has these top-level messages: - HelloRequest - HelloReply -*/ -package helloworld - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The request message containing the user's name. -type HelloRequest struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` -} - -func (m *HelloRequest) Reset() { *m = HelloRequest{} } -func (m *HelloRequest) String() string { return proto.CompactTextString(m) } -func (*HelloRequest) ProtoMessage() {} -func (*HelloRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *HelloRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// The response message containing the greetings -type HelloReply struct { - Message string `protobuf:"bytes,1,opt,name=message" json:"message,omitempty"` -} - -func (m *HelloReply) Reset() { *m = HelloReply{} } -func (m *HelloReply) String() string { return proto.CompactTextString(m) } -func (*HelloReply) ProtoMessage() {} -func (*HelloReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *HelloReply) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func init() { - proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") - proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for Greeter service - -type GreeterClient interface { - // Sends a greeting - SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) -} - -type greeterClient struct { - cc *grpc.ClientConn -} - -func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { - return &greeterClient{cc} -} - -func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { - out := new(HelloReply) - err := grpc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Greeter service - -type GreeterServer interface { - // Sends a greeting - SayHello(context.Context, *HelloRequest) (*HelloReply, error) -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(GreeterServer).SayHello(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/helloworld.Greeter/SayHello", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Greeter_serviceDesc = grpc.ServiceDesc{ - ServiceName: "helloworld.Greeter", - HandlerType: (*GreeterServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "SayHello", - Handler: _Greeter_SayHello_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "helloworld.proto", -} - -func init() { proto.RegisterFile("helloworld.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 175 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0x48, 0xcd, 0xc9, - 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, - 0x28, 0x29, 0x71, 0xf1, 0x78, 0x80, 0x78, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0x42, - 0x5c, 0x2c, 0x79, 0x89, 0xb9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x92, - 0x1a, 0x17, 0x17, 0x54, 0x4d, 0x41, 0x4e, 0xa5, 0x90, 0x04, 0x17, 0x7b, 0x6e, 0x6a, 0x71, 0x71, - 0x62, 0x3a, 0x4c, 0x11, 0x8c, 0x6b, 0xe4, 0xc9, 0xc5, 0xee, 0x5e, 0x94, 0x9a, 0x5a, 0x92, 0x5a, - 0x24, 0x64, 0xc7, 0xc5, 0x11, 0x9c, 0x58, 0x09, 0xd6, 0x25, 0x24, 0xa1, 0x87, 0xe4, 0x02, 0x64, - 0xcb, 0xa4, 0xc4, 0xb0, 0xc8, 0x14, 0xe4, 0x54, 0x2a, 0x31, 0x38, 0x19, 0x70, 0x49, 0x67, 0xe6, - 0xeb, 0xa5, 0x17, 0x15, 0x24, 0xeb, 0xa5, 0x56, 0x24, 0xe6, 0x16, 0xe4, 0xa4, 0x16, 0x23, 0xa9, - 0x75, 0xe2, 0x07, 0x2b, 0x0e, 0x07, 0xb1, 0x03, 0x40, 0x5e, 0x0a, 0x60, 0x4c, 0x62, 0x03, 0xfb, - 0xcd, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x0f, 0xb7, 0xcd, 0xf2, 0xef, 0x00, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto b/vendor/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto deleted file mode 100644 index d79a6a0d1..000000000 --- a/vendor/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -option java_multiple_files = true; -option java_package = "io.grpc.examples.helloworld"; -option java_outer_classname = "HelloWorldProto"; - -package helloworld; - -// The greeting service definition. -service Greeter { - // Sends a greeting - rpc SayHello (HelloRequest) returns (HelloReply) {} -} - -// The request message containing the user's name. -message HelloRequest { - string name = 1; -} - -// The response message containing the greetings -message HelloReply { - string message = 1; -} diff --git a/vendor/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock.go b/vendor/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock.go deleted file mode 100644 index 14957ed5f..000000000 --- a/vendor/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock.go +++ /dev/null @@ -1,48 +0,0 @@ -// Automatically generated by MockGen. DO NOT EDIT! -// Source: google.golang.org/grpc/examples/helloworld/helloworld (interfaces: GreeterClient) - -package mock_helloworld - -import ( - gomock "github.com/golang/mock/gomock" - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" - helloworld "google.golang.org/grpc/examples/helloworld/helloworld" -) - -// Mock of GreeterClient interface -type MockGreeterClient struct { - ctrl *gomock.Controller - recorder *_MockGreeterClientRecorder -} - -// Recorder for MockGreeterClient (not exported) -type _MockGreeterClientRecorder struct { - mock *MockGreeterClient -} - -func NewMockGreeterClient(ctrl *gomock.Controller) *MockGreeterClient { - mock := &MockGreeterClient{ctrl: ctrl} - mock.recorder = &_MockGreeterClientRecorder{mock} - return mock -} - -func (_m *MockGreeterClient) EXPECT() *_MockGreeterClientRecorder { - return _m.recorder -} - -func (_m *MockGreeterClient) SayHello(_param0 context.Context, _param1 *helloworld.HelloRequest, _param2 ...grpc.CallOption) (*helloworld.HelloReply, error) { - _s := []interface{}{_param0, _param1} - for _, _x := range _param2 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "SayHello", _s...) - ret0, _ := ret[0].(*helloworld.HelloReply) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockGreeterClientRecorder) SayHello(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1}, arg2...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "SayHello", _s...) -} diff --git a/vendor/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock_test.go b/vendor/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock_test.go deleted file mode 100644 index 5ad9b8b0d..000000000 --- a/vendor/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock_test.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package mock_helloworld_test - -import ( - "fmt" - "testing" - - "github.com/golang/mock/gomock" - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - helloworld "google.golang.org/grpc/examples/helloworld/helloworld" - hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld" -) - -// rpcMsg implements the gomock.Matcher interface -type rpcMsg struct { - msg proto.Message -} - -func (r *rpcMsg) Matches(msg interface{}) bool { - m, ok := msg.(proto.Message) - if !ok { - return false - } - return proto.Equal(m, r.msg) -} - -func (r *rpcMsg) String() string { - return fmt.Sprintf("is %s", r.msg) -} - -func TestSayHello(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mockGreeterClient := hwmock.NewMockGreeterClient(ctrl) - req := &helloworld.HelloRequest{Name: "unit_test"} - mockGreeterClient.EXPECT().SayHello( - gomock.Any(), - &rpcMsg{msg: req}, - ).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil) - testSayHello(t, mockGreeterClient) -} - -func testSayHello(t *testing.T, client helloworld.GreeterClient) { - r, err := client.SayHello(context.Background(), &helloworld.HelloRequest{Name: "unit_test"}) - if err != nil || r.Message != "Mocked Interface" { - t.Errorf("mocking failed") - } - t.Log("Reply : ", r.Message) -} diff --git a/vendor/google.golang.org/grpc/examples/route_guide/README.md b/vendor/google.golang.org/grpc/examples/route_guide/README.md deleted file mode 100644 index 7f009d5ca..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Description -The route guide server and client demonstrate how to use grpc go libraries to -perform unary, client streaming, server streaming and full duplex RPCs. - -Please refer to [gRPC Basics: Go] (https://grpc.io/docs/tutorials/basic/go.html) for more information. - -See the definition of the route guide service in routeguide/route_guide.proto. - -# Run the sample code -To compile and run the server, assuming you are in the root of the route_guide -folder, i.e., .../examples/route_guide/, simply: - -```sh -$ go run server/server.go -``` - -Likewise, to run the client: - -```sh -$ go run client/client.go -``` - -# Optional command line flags -The server and client both take optional command line flags. For example, the -client and server run without TLS by default. To enable TLS: - -```sh -$ go run server/server.go -tls=true -``` - -and - -```sh -$ go run client/client.go -tls=true -``` diff --git a/vendor/google.golang.org/grpc/examples/route_guide/client/client.go b/vendor/google.golang.org/grpc/examples/route_guide/client/client.go deleted file mode 100644 index 6fc7a079c..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/client/client.go +++ /dev/null @@ -1,184 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries -// to perform unary, client streaming, server streaming and full duplex RPCs. -// -// It interacts with the route guide service whose definition can be found in routeguide/route_guide.proto. -package main - -import ( - "flag" - "io" - "log" - "math/rand" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - pb "google.golang.org/grpc/examples/route_guide/routeguide" - "google.golang.org/grpc/testdata" -) - -var ( - tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP") - caFile = flag.String("ca_file", "", "The file containning the CA root cert file") - serverAddr = flag.String("server_addr", "127.0.0.1:10000", "The server address in the format of host:port") - serverHostOverride = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake") -) - -// printFeature gets the feature for the given point. -func printFeature(client pb.RouteGuideClient, point *pb.Point) { - log.Printf("Getting feature for point (%d, %d)", point.Latitude, point.Longitude) - feature, err := client.GetFeature(context.Background(), point) - if err != nil { - log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err) - } - log.Println(feature) -} - -// printFeatures lists all the features within the given bounding Rectangle. -func printFeatures(client pb.RouteGuideClient, rect *pb.Rectangle) { - log.Printf("Looking for features within %v", rect) - stream, err := client.ListFeatures(context.Background(), rect) - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - for { - feature, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - log.Println(feature) - } -} - -// runRecordRoute sends a sequence of points to server and expects to get a RouteSummary from server. -func runRecordRoute(client pb.RouteGuideClient) { - // Create a random number of random points - r := rand.New(rand.NewSource(time.Now().UnixNano())) - pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points - var points []*pb.Point - for i := 0; i < pointCount; i++ { - points = append(points, randomPoint(r)) - } - log.Printf("Traversing %d points.", len(points)) - stream, err := client.RecordRoute(context.Background()) - if err != nil { - log.Fatalf("%v.RecordRoute(_) = _, %v", client, err) - } - for _, point := range points { - if err := stream.Send(point); err != nil { - log.Fatalf("%v.Send(%v) = %v", stream, point, err) - } - } - reply, err := stream.CloseAndRecv() - if err != nil { - log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) - } - log.Printf("Route summary: %v", reply) -} - -// runRouteChat receives a sequence of route notes, while sending notes for various locations. -func runRouteChat(client pb.RouteGuideClient) { - notes := []*pb.RouteNote{ - {&pb.Point{Latitude: 0, Longitude: 1}, "First message"}, - {&pb.Point{Latitude: 0, Longitude: 2}, "Second message"}, - {&pb.Point{Latitude: 0, Longitude: 3}, "Third message"}, - {&pb.Point{Latitude: 0, Longitude: 1}, "Fourth message"}, - {&pb.Point{Latitude: 0, Longitude: 2}, "Fifth message"}, - {&pb.Point{Latitude: 0, Longitude: 3}, "Sixth message"}, - } - stream, err := client.RouteChat(context.Background()) - if err != nil { - log.Fatalf("%v.RouteChat(_) = _, %v", client, err) - } - waitc := make(chan struct{}) - go func() { - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - close(waitc) - return - } - if err != nil { - log.Fatalf("Failed to receive a note : %v", err) - } - log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude) - } - }() - for _, note := range notes { - if err := stream.Send(note); err != nil { - log.Fatalf("Failed to send a note: %v", err) - } - } - stream.CloseSend() - <-waitc -} - -func randomPoint(r *rand.Rand) *pb.Point { - lat := (r.Int31n(180) - 90) * 1e7 - long := (r.Int31n(360) - 180) * 1e7 - return &pb.Point{Latitude: lat, Longitude: long} -} - -func main() { - flag.Parse() - var opts []grpc.DialOption - if *tls { - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err := credentials.NewClientTLSFromFile(*caFile, *serverHostOverride) - if err != nil { - log.Fatalf("Failed to create TLS credentials %v", err) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - } else { - opts = append(opts, grpc.WithInsecure()) - } - conn, err := grpc.Dial(*serverAddr, opts...) - if err != nil { - log.Fatalf("fail to dial: %v", err) - } - defer conn.Close() - client := pb.NewRouteGuideClient(conn) - - // Looking for a valid feature - printFeature(client, &pb.Point{Latitude: 409146138, Longitude: -746188906}) - - // Feature missing. - printFeature(client, &pb.Point{Latitude: 0, Longitude: 0}) - - // Looking for features between 40, -75 and 42, -73. - printFeatures(client, &pb.Rectangle{ - Lo: &pb.Point{Latitude: 400000000, Longitude: -750000000}, - Hi: &pb.Point{Latitude: 420000000, Longitude: -730000000}, - }) - - // RecordRoute - runRecordRoute(client) - - // RouteChat - runRouteChat(client) -} diff --git a/vendor/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock.go b/vendor/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock.go deleted file mode 100644 index 328c929fa..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock.go +++ /dev/null @@ -1,200 +0,0 @@ -// Automatically generated by MockGen. DO NOT EDIT! -// Source: google.golang.org/grpc/examples/route_guide/routeguide (interfaces: RouteGuideClient,RouteGuide_RouteChatClient) - -package mock_routeguide - -import ( - gomock "github.com/golang/mock/gomock" - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" - routeguide "google.golang.org/grpc/examples/route_guide/routeguide" - metadata "google.golang.org/grpc/metadata" -) - -// Mock of RouteGuideClient interface -type MockRouteGuideClient struct { - ctrl *gomock.Controller - recorder *_MockRouteGuideClientRecorder -} - -// Recorder for MockRouteGuideClient (not exported) -type _MockRouteGuideClientRecorder struct { - mock *MockRouteGuideClient -} - -func NewMockRouteGuideClient(ctrl *gomock.Controller) *MockRouteGuideClient { - mock := &MockRouteGuideClient{ctrl: ctrl} - mock.recorder = &_MockRouteGuideClientRecorder{mock} - return mock -} - -func (_m *MockRouteGuideClient) EXPECT() *_MockRouteGuideClientRecorder { - return _m.recorder -} - -func (_m *MockRouteGuideClient) GetFeature(_param0 context.Context, _param1 *routeguide.Point, _param2 ...grpc.CallOption) (*routeguide.Feature, error) { - _s := []interface{}{_param0, _param1} - for _, _x := range _param2 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "GetFeature", _s...) - ret0, _ := ret[0].(*routeguide.Feature) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) GetFeature(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1}, arg2...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "GetFeature", _s...) -} - -func (_m *MockRouteGuideClient) ListFeatures(_param0 context.Context, _param1 *routeguide.Rectangle, _param2 ...grpc.CallOption) (routeguide.RouteGuide_ListFeaturesClient, error) { - _s := []interface{}{_param0, _param1} - for _, _x := range _param2 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "ListFeatures", _s...) - ret0, _ := ret[0].(routeguide.RouteGuide_ListFeaturesClient) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) ListFeatures(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1}, arg2...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "ListFeatures", _s...) -} - -func (_m *MockRouteGuideClient) RecordRoute(_param0 context.Context, _param1 ...grpc.CallOption) (routeguide.RouteGuide_RecordRouteClient, error) { - _s := []interface{}{_param0} - for _, _x := range _param1 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "RecordRoute", _s...) - ret0, _ := ret[0].(routeguide.RouteGuide_RecordRouteClient) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) RecordRoute(arg0 interface{}, arg1 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0}, arg1...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "RecordRoute", _s...) -} - -func (_m *MockRouteGuideClient) RouteChat(_param0 context.Context, _param1 ...grpc.CallOption) (routeguide.RouteGuide_RouteChatClient, error) { - _s := []interface{}{_param0} - for _, _x := range _param1 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "RouteChat", _s...) - ret0, _ := ret[0].(routeguide.RouteGuide_RouteChatClient) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) RouteChat(arg0 interface{}, arg1 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0}, arg1...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "RouteChat", _s...) -} - -// Mock of RouteGuide_RouteChatClient interface -type MockRouteGuide_RouteChatClient struct { - ctrl *gomock.Controller - recorder *_MockRouteGuide_RouteChatClientRecorder -} - -// Recorder for MockRouteGuide_RouteChatClient (not exported) -type _MockRouteGuide_RouteChatClientRecorder struct { - mock *MockRouteGuide_RouteChatClient -} - -func NewMockRouteGuide_RouteChatClient(ctrl *gomock.Controller) *MockRouteGuide_RouteChatClient { - mock := &MockRouteGuide_RouteChatClient{ctrl: ctrl} - mock.recorder = &_MockRouteGuide_RouteChatClientRecorder{mock} - return mock -} - -func (_m *MockRouteGuide_RouteChatClient) EXPECT() *_MockRouteGuide_RouteChatClientRecorder { - return _m.recorder -} - -func (_m *MockRouteGuide_RouteChatClient) CloseSend() error { - ret := _m.ctrl.Call(_m, "CloseSend") - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) CloseSend() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "CloseSend") -} - -func (_m *MockRouteGuide_RouteChatClient) Context() context.Context { - ret := _m.ctrl.Call(_m, "Context") - ret0, _ := ret[0].(context.Context) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Context() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Context") -} - -func (_m *MockRouteGuide_RouteChatClient) Header() (metadata.MD, error) { - ret := _m.ctrl.Call(_m, "Header") - ret0, _ := ret[0].(metadata.MD) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Header() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Header") -} - -func (_m *MockRouteGuide_RouteChatClient) Recv() (*routeguide.RouteNote, error) { - ret := _m.ctrl.Call(_m, "Recv") - ret0, _ := ret[0].(*routeguide.RouteNote) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Recv() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Recv") -} - -func (_m *MockRouteGuide_RouteChatClient) RecvMsg(_param0 interface{}) error { - ret := _m.ctrl.Call(_m, "RecvMsg", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) RecvMsg(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "RecvMsg", arg0) -} - -func (_m *MockRouteGuide_RouteChatClient) Send(_param0 *routeguide.RouteNote) error { - ret := _m.ctrl.Call(_m, "Send", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Send(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Send", arg0) -} - -func (_m *MockRouteGuide_RouteChatClient) SendMsg(_param0 interface{}) error { - ret := _m.ctrl.Call(_m, "SendMsg", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) SendMsg(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "SendMsg", arg0) -} - -func (_m *MockRouteGuide_RouteChatClient) Trailer() metadata.MD { - ret := _m.ctrl.Call(_m, "Trailer") - ret0, _ := ret[0].(metadata.MD) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Trailer() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Trailer") -} diff --git a/vendor/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock_test.go b/vendor/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock_test.go deleted file mode 100644 index 8c6d63c72..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock_test.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package mock_routeguide_test - -import ( - "fmt" - "testing" - - "github.com/golang/mock/gomock" - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - rgmock "google.golang.org/grpc/examples/route_guide/mock_routeguide" - rgpb "google.golang.org/grpc/examples/route_guide/routeguide" -) - -var ( - msg = &rgpb.RouteNote{ - Location: &rgpb.Point{Latitude: 17, Longitude: 29}, - Message: "Taxi-cab", - } -) - -func TestRouteChat(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - // Create mock for the stream returned by RouteChat - stream := rgmock.NewMockRouteGuide_RouteChatClient(ctrl) - // set expectation on sending. - stream.EXPECT().Send( - gomock.Any(), - ).Return(nil) - // Set expectation on receiving. - stream.EXPECT().Recv().Return(msg, nil) - stream.EXPECT().CloseSend().Return(nil) - // Create mock for the client interface. - rgclient := rgmock.NewMockRouteGuideClient(ctrl) - // Set expectation on RouteChat - rgclient.EXPECT().RouteChat( - gomock.Any(), - ).Return(stream, nil) - if err := testRouteChat(rgclient); err != nil { - t.Fatalf("Test failed: %v", err) - } -} - -func testRouteChat(client rgpb.RouteGuideClient) error { - stream, err := client.RouteChat(context.Background()) - if err != nil { - return err - } - if err := stream.Send(msg); err != nil { - return err - } - if err := stream.CloseSend(); err != nil { - return err - } - got, err := stream.Recv() - if err != nil { - return err - } - if !proto.Equal(got, msg) { - return fmt.Errorf("stream.Recv() = %v, want %v", got, msg) - } - return nil -} diff --git a/vendor/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go b/vendor/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go deleted file mode 100644 index cf7f3937e..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go +++ /dev/null @@ -1,543 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: route_guide.proto - -/* -Package routeguide is a generated protocol buffer package. - -It is generated from these files: - route_guide.proto - -It has these top-level messages: - Point - Rectangle - Feature - RouteNote - RouteSummary -*/ -package routeguide - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Points are represented as latitude-longitude pairs in the E7 representation -// (degrees multiplied by 10**7 and rounded to the nearest integer). -// Latitudes should be in the range +/- 90 degrees and longitude should be in -// the range +/- 180 degrees (inclusive). -type Point struct { - Latitude int32 `protobuf:"varint,1,opt,name=latitude" json:"latitude,omitempty"` - Longitude int32 `protobuf:"varint,2,opt,name=longitude" json:"longitude,omitempty"` -} - -func (m *Point) Reset() { *m = Point{} } -func (m *Point) String() string { return proto.CompactTextString(m) } -func (*Point) ProtoMessage() {} -func (*Point) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *Point) GetLatitude() int32 { - if m != nil { - return m.Latitude - } - return 0 -} - -func (m *Point) GetLongitude() int32 { - if m != nil { - return m.Longitude - } - return 0 -} - -// A latitude-longitude rectangle, represented as two diagonally opposite -// points "lo" and "hi". -type Rectangle struct { - // One corner of the rectangle. - Lo *Point `protobuf:"bytes,1,opt,name=lo" json:"lo,omitempty"` - // The other corner of the rectangle. - Hi *Point `protobuf:"bytes,2,opt,name=hi" json:"hi,omitempty"` -} - -func (m *Rectangle) Reset() { *m = Rectangle{} } -func (m *Rectangle) String() string { return proto.CompactTextString(m) } -func (*Rectangle) ProtoMessage() {} -func (*Rectangle) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *Rectangle) GetLo() *Point { - if m != nil { - return m.Lo - } - return nil -} - -func (m *Rectangle) GetHi() *Point { - if m != nil { - return m.Hi - } - return nil -} - -// A feature names something at a given point. -// -// If a feature could not be named, the name is empty. -type Feature struct { - // The name of the feature. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // The point where the feature is detected. - Location *Point `protobuf:"bytes,2,opt,name=location" json:"location,omitempty"` -} - -func (m *Feature) Reset() { *m = Feature{} } -func (m *Feature) String() string { return proto.CompactTextString(m) } -func (*Feature) ProtoMessage() {} -func (*Feature) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *Feature) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Feature) GetLocation() *Point { - if m != nil { - return m.Location - } - return nil -} - -// A RouteNote is a message sent while at a given point. -type RouteNote struct { - // The location from which the message is sent. - Location *Point `protobuf:"bytes,1,opt,name=location" json:"location,omitempty"` - // The message to be sent. - Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` -} - -func (m *RouteNote) Reset() { *m = RouteNote{} } -func (m *RouteNote) String() string { return proto.CompactTextString(m) } -func (*RouteNote) ProtoMessage() {} -func (*RouteNote) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *RouteNote) GetLocation() *Point { - if m != nil { - return m.Location - } - return nil -} - -func (m *RouteNote) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -// A RouteSummary is received in response to a RecordRoute rpc. -// -// It contains the number of individual points received, the number of -// detected features, and the total distance covered as the cumulative sum of -// the distance between each point. -type RouteSummary struct { - // The number of points received. - PointCount int32 `protobuf:"varint,1,opt,name=point_count,json=pointCount" json:"point_count,omitempty"` - // The number of known features passed while traversing the route. - FeatureCount int32 `protobuf:"varint,2,opt,name=feature_count,json=featureCount" json:"feature_count,omitempty"` - // The distance covered in metres. - Distance int32 `protobuf:"varint,3,opt,name=distance" json:"distance,omitempty"` - // The duration of the traversal in seconds. - ElapsedTime int32 `protobuf:"varint,4,opt,name=elapsed_time,json=elapsedTime" json:"elapsed_time,omitempty"` -} - -func (m *RouteSummary) Reset() { *m = RouteSummary{} } -func (m *RouteSummary) String() string { return proto.CompactTextString(m) } -func (*RouteSummary) ProtoMessage() {} -func (*RouteSummary) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -func (m *RouteSummary) GetPointCount() int32 { - if m != nil { - return m.PointCount - } - return 0 -} - -func (m *RouteSummary) GetFeatureCount() int32 { - if m != nil { - return m.FeatureCount - } - return 0 -} - -func (m *RouteSummary) GetDistance() int32 { - if m != nil { - return m.Distance - } - return 0 -} - -func (m *RouteSummary) GetElapsedTime() int32 { - if m != nil { - return m.ElapsedTime - } - return 0 -} - -func init() { - proto.RegisterType((*Point)(nil), "routeguide.Point") - proto.RegisterType((*Rectangle)(nil), "routeguide.Rectangle") - proto.RegisterType((*Feature)(nil), "routeguide.Feature") - proto.RegisterType((*RouteNote)(nil), "routeguide.RouteNote") - proto.RegisterType((*RouteSummary)(nil), "routeguide.RouteSummary") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for RouteGuide service - -type RouteGuideClient interface { - // A simple RPC. - // - // Obtains the feature at a given position. - // - // A feature with an empty name is returned if there's no feature at the given - // position. - GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // 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 - // huge number of features. - ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) - // A client-to-server streaming RPC. - // - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) - // A Bidirectional streaming RPC. - // - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) -} - -type routeGuideClient struct { - cc *grpc.ClientConn -} - -func NewRouteGuideClient(cc *grpc.ClientConn) RouteGuideClient { - return &routeGuideClient{cc} -} - -func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) { - out := new(Feature) - err := grpc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *routeGuideClient) ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) { - stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[0], c.cc, "/routeguide.RouteGuide/ListFeatures", opts...) - if err != nil { - return nil, err - } - x := &routeGuideListFeaturesClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type RouteGuide_ListFeaturesClient interface { - Recv() (*Feature, error) - grpc.ClientStream -} - -type routeGuideListFeaturesClient struct { - grpc.ClientStream -} - -func (x *routeGuideListFeaturesClient) Recv() (*Feature, error) { - m := new(Feature) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *routeGuideClient) RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) { - stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[1], c.cc, "/routeguide.RouteGuide/RecordRoute", opts...) - if err != nil { - return nil, err - } - x := &routeGuideRecordRouteClient{stream} - return x, nil -} - -type RouteGuide_RecordRouteClient interface { - Send(*Point) error - CloseAndRecv() (*RouteSummary, error) - grpc.ClientStream -} - -type routeGuideRecordRouteClient struct { - grpc.ClientStream -} - -func (x *routeGuideRecordRouteClient) Send(m *Point) error { - return x.ClientStream.SendMsg(m) -} - -func (x *routeGuideRecordRouteClient) CloseAndRecv() (*RouteSummary, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(RouteSummary) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *routeGuideClient) RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) { - stream, err := grpc.NewClientStream(ctx, &_RouteGuide_serviceDesc.Streams[2], c.cc, "/routeguide.RouteGuide/RouteChat", opts...) - if err != nil { - return nil, err - } - x := &routeGuideRouteChatClient{stream} - return x, nil -} - -type RouteGuide_RouteChatClient interface { - Send(*RouteNote) error - Recv() (*RouteNote, error) - grpc.ClientStream -} - -type routeGuideRouteChatClient struct { - grpc.ClientStream -} - -func (x *routeGuideRouteChatClient) Send(m *RouteNote) error { - return x.ClientStream.SendMsg(m) -} - -func (x *routeGuideRouteChatClient) Recv() (*RouteNote, error) { - m := new(RouteNote) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for RouteGuide service - -type RouteGuideServer interface { - // A simple RPC. - // - // Obtains the feature at a given position. - // - // A feature with an empty name is returned if there's no feature at the given - // position. - GetFeature(context.Context, *Point) (*Feature, error) - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // 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 - // huge number of features. - ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error - // A client-to-server streaming RPC. - // - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - RecordRoute(RouteGuide_RecordRouteServer) error - // A Bidirectional streaming RPC. - // - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - RouteChat(RouteGuide_RouteChatServer) error -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RouteGuideServer).GetFeature(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/routeguide.RouteGuide/GetFeature", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RouteGuideServer).GetFeature(ctx, req.(*Point)) - } - return interceptor(ctx, in, info, handler) -} - -func _RouteGuide_ListFeatures_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(Rectangle) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(RouteGuideServer).ListFeatures(m, &routeGuideListFeaturesServer{stream}) -} - -type RouteGuide_ListFeaturesServer interface { - Send(*Feature) error - grpc.ServerStream -} - -type routeGuideListFeaturesServer struct { - grpc.ServerStream -} - -func (x *routeGuideListFeaturesServer) Send(m *Feature) error { - 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 { - SendAndClose(*RouteSummary) error - Recv() (*Point, error) - grpc.ServerStream -} - -type routeGuideRecordRouteServer struct { - grpc.ServerStream -} - -func (x *routeGuideRecordRouteServer) SendAndClose(m *RouteSummary) error { - return x.ServerStream.SendMsg(m) -} - -func (x *routeGuideRecordRouteServer) Recv() (*Point, error) { - m := new(Point) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _RouteGuide_RouteChat_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(RouteGuideServer).RouteChat(&routeGuideRouteChatServer{stream}) -} - -type RouteGuide_RouteChatServer interface { - Send(*RouteNote) error - Recv() (*RouteNote, error) - grpc.ServerStream -} - -type routeGuideRouteChatServer struct { - grpc.ServerStream -} - -func (x *routeGuideRouteChatServer) Send(m *RouteNote) error { - return x.ServerStream.SendMsg(m) -} - -func (x *routeGuideRouteChatServer) Recv() (*RouteNote, error) { - m := new(RouteNote) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _RouteGuide_serviceDesc = grpc.ServiceDesc{ - ServiceName: "routeguide.RouteGuide", - HandlerType: (*RouteGuideServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetFeature", - Handler: _RouteGuide_GetFeature_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "ListFeatures", - Handler: _RouteGuide_ListFeatures_Handler, - ServerStreams: true, - }, - { - StreamName: "RecordRoute", - Handler: _RouteGuide_RecordRoute_Handler, - ClientStreams: true, - }, - { - StreamName: "RouteChat", - Handler: _RouteGuide_RouteChat_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "route_guide.proto", -} - -func init() { proto.RegisterFile("route_guide.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 404 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x53, 0xdd, 0xca, 0xd3, 0x40, - 0x10, 0xfd, 0x36, 0x7e, 0x9f, 0x6d, 0x26, 0x11, 0xe9, 0x88, 0x10, 0xa2, 0xa0, 0x8d, 0x37, 0xbd, - 0x31, 0x94, 0x0a, 0x5e, 0x56, 0x6c, 0xc1, 0xde, 0x14, 0xa9, 0xb1, 0xf7, 0x65, 0x4d, 0xc6, 0x74, - 0x61, 0x93, 0x0d, 0xc9, 0x06, 0xf4, 0x01, 0x7c, 0x02, 0x5f, 0x58, 0xb2, 0x49, 0xda, 0x54, 0x5b, - 0xbc, 0xdb, 0x39, 0x73, 0xce, 0xfc, 0x9c, 0x61, 0x61, 0x52, 0xaa, 0x5a, 0xd3, 0x21, 0xad, 0x45, - 0x42, 0x61, 0x51, 0x2a, 0xad, 0x10, 0x0c, 0x64, 0x90, 0xe0, 0x23, 0x3c, 0xec, 0x94, 0xc8, 0x35, - 0xfa, 0x30, 0x96, 0x5c, 0x0b, 0x5d, 0x27, 0xe4, 0xb1, 0xd7, 0x6c, 0xf6, 0x10, 0x9d, 0x62, 0x7c, - 0x09, 0xb6, 0x54, 0x79, 0xda, 0x26, 0x2d, 0x93, 0x3c, 0x03, 0xc1, 0x17, 0xb0, 0x23, 0x8a, 0x35, - 0xcf, 0x53, 0x49, 0x38, 0x05, 0x4b, 0x2a, 0x53, 0xc0, 0x59, 0x4c, 0xc2, 0x73, 0xa3, 0xd0, 0x74, - 0x89, 0x2c, 0xa9, 0x1a, 0xca, 0x51, 0x98, 0x32, 0xd7, 0x29, 0x47, 0x11, 0x6c, 0x61, 0xf4, 0x89, - 0xb8, 0xae, 0x4b, 0x42, 0x84, 0xfb, 0x9c, 0x67, 0xed, 0x4c, 0x76, 0x64, 0xde, 0xf8, 0x16, 0xc6, - 0x52, 0xc5, 0x5c, 0x0b, 0x95, 0xdf, 0xae, 0x73, 0xa2, 0x04, 0x7b, 0xb0, 0xa3, 0x26, 0xfb, 0x59, - 0xe9, 0x4b, 0x2d, 0xfb, 0xaf, 0x16, 0x3d, 0x18, 0x65, 0x54, 0x55, 0x3c, 0x6d, 0x17, 0xb7, 0xa3, - 0x3e, 0x0c, 0x7e, 0x33, 0x70, 0x4d, 0xd9, 0xaf, 0x75, 0x96, 0xf1, 0xf2, 0x27, 0xbe, 0x02, 0xa7, - 0x68, 0xd4, 0x87, 0x58, 0xd5, 0xb9, 0xee, 0x4c, 0x04, 0x03, 0xad, 0x1b, 0x04, 0xdf, 0xc0, 0x93, - 0xef, 0xed, 0x56, 0x1d, 0xa5, 0xb5, 0xd2, 0xed, 0xc0, 0x96, 0xe4, 0xc3, 0x38, 0x11, 0x95, 0xe6, - 0x79, 0x4c, 0xde, 0xa3, 0xf6, 0x0e, 0x7d, 0x8c, 0x53, 0x70, 0x49, 0xf2, 0xa2, 0xa2, 0xe4, 0xa0, - 0x45, 0x46, 0xde, 0xbd, 0xc9, 0x3b, 0x1d, 0xb6, 0x17, 0x19, 0x2d, 0x7e, 0x59, 0x00, 0x66, 0xaa, - 0x4d, 0xb3, 0x0e, 0xbe, 0x07, 0xd8, 0x90, 0xee, 0xbd, 0xfc, 0x77, 0x53, 0xff, 0xd9, 0x10, 0xea, - 0x78, 0xc1, 0x1d, 0x2e, 0xc1, 0xdd, 0x8a, 0xaa, 0x17, 0x56, 0xf8, 0x7c, 0x48, 0x3b, 0x5d, 0xfb, - 0x86, 0x7a, 0xce, 0x70, 0x09, 0x4e, 0x44, 0xb1, 0x2a, 0x13, 0x33, 0xcb, 0xb5, 0xc6, 0xde, 0x45, - 0xc5, 0x81, 0x8f, 0xc1, 0xdd, 0x8c, 0xe1, 0x87, 0xee, 0x64, 0xeb, 0x23, 0xd7, 0x7f, 0x35, 0xef, - 0x2f, 0xe9, 0x5f, 0x87, 0x1b, 0xf9, 0x9c, 0xad, 0xe6, 0xf0, 0x42, 0xa8, 0x30, 0x2d, 0x8b, 0x38, - 0xa4, 0x1f, 0x3c, 0x2b, 0x24, 0x55, 0x03, 0xfa, 0xea, 0xe9, 0xd9, 0xa3, 0x5d, 0xf3, 0x27, 0x76, - 0xec, 0xdb, 0x63, 0xf3, 0x39, 0xde, 0xfd, 0x09, 0x00, 0x00, 0xff, 0xff, 0xc8, 0xe4, 0xef, 0xe6, - 0x31, 0x03, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto b/vendor/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto deleted file mode 100644 index fe21e437a..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -option java_multiple_files = true; -option java_package = "io.grpc.examples.routeguide"; -option java_outer_classname = "RouteGuideProto"; - -package routeguide; - -// Interface exported by the server. -service RouteGuide { - // A simple RPC. - // - // Obtains the feature at a given position. - // - // A feature with an empty name is returned if there's no feature at the given - // position. - rpc GetFeature(Point) returns (Feature) {} - - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // 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 - // huge number of features. - rpc ListFeatures(Rectangle) returns (stream Feature) {} - - // A client-to-server streaming RPC. - // - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - rpc RecordRoute(stream Point) returns (RouteSummary) {} - - // A Bidirectional streaming RPC. - // - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} -} - -// Points are represented as latitude-longitude pairs in the E7 representation -// (degrees multiplied by 10**7 and rounded to the nearest integer). -// Latitudes should be in the range +/- 90 degrees and longitude should be in -// the range +/- 180 degrees (inclusive). -message Point { - int32 latitude = 1; - int32 longitude = 2; -} - -// A latitude-longitude rectangle, represented as two diagonally opposite -// points "lo" and "hi". -message Rectangle { - // One corner of the rectangle. - Point lo = 1; - - // The other corner of the rectangle. - Point hi = 2; -} - -// A feature names something at a given point. -// -// If a feature could not be named, the name is empty. -message Feature { - // The name of the feature. - string name = 1; - - // The point where the feature is detected. - Point location = 2; -} - -// A RouteNote is a message sent while at a given point. -message RouteNote { - // The location from which the message is sent. - Point location = 1; - - // The message to be sent. - string message = 2; -} - -// A RouteSummary is received in response to a RecordRoute rpc. -// -// It contains the number of individual points received, the number of -// detected features, and the total distance covered as the cumulative sum of -// the distance between each point. -message RouteSummary { - // The number of points received. - int32 point_count = 1; - - // The number of known features passed while traversing the route. - int32 feature_count = 2; - - // The distance covered in metres. - int32 distance = 3; - - // The duration of the traversal in seconds. - int32 elapsed_time = 4; -} diff --git a/vendor/google.golang.org/grpc/examples/route_guide/server/server.go b/vendor/google.golang.org/grpc/examples/route_guide/server/server.go deleted file mode 100644 index 5d919047e..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/server/server.go +++ /dev/null @@ -1,233 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc -I ../routeguide --go_out=plugins=grpc:../routeguide ../routeguide/route_guide.proto - -// Package main implements a simple gRPC server that demonstrates how to use gRPC-Go libraries -// to perform unary, client streaming, server streaming and full duplex RPCs. -// -// It implements the route guide service whose definition can be found in routeguide/route_guide.proto. -package main - -import ( - "encoding/json" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "math" - "net" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/testdata" - - "github.com/golang/protobuf/proto" - - pb "google.golang.org/grpc/examples/route_guide/routeguide" -) - -var ( - tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP") - certFile = flag.String("cert_file", "", "The TLS cert file") - keyFile = flag.String("key_file", "", "The TLS key file") - jsonDBFile = flag.String("json_db_file", "testdata/route_guide_db.json", "A json file containing a list of features") - port = flag.Int("port", 10000, "The server port") -) - -type routeGuideServer struct { - savedFeatures []*pb.Feature - routeNotes map[string][]*pb.RouteNote -} - -// GetFeature returns the feature at the given point. -func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - return feature, nil - } - } - // No feature was found, return an unnamed feature - return &pb.Feature{Location: point}, nil -} - -// ListFeatures lists all features contained within the given bounding Rectangle. -func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { - for _, feature := range s.savedFeatures { - if inRange(feature.Location, rect) { - if err := stream.Send(feature); err != nil { - return err - } - } - } - return nil -} - -// RecordRoute records a route composited of a sequence of points. -// -// It gets a stream of points, and responds with statistics about the "trip": -// number of points, number of known features visited, total distance traveled, and -// total time spent. -func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { - var pointCount, featureCount, distance int32 - var lastPoint *pb.Point - startTime := time.Now() - for { - point, err := stream.Recv() - if err == io.EOF { - endTime := time.Now() - return stream.SendAndClose(&pb.RouteSummary{ - PointCount: pointCount, - FeatureCount: featureCount, - Distance: distance, - ElapsedTime: int32(endTime.Sub(startTime).Seconds()), - }) - } - if err != nil { - return err - } - pointCount++ - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - featureCount++ - } - } - if lastPoint != nil { - distance += calcDistance(lastPoint, point) - } - lastPoint = point - } -} - -// RouteChat receives a stream of message/location pairs, and responds with a stream of all -// previous messages at each of those locations. -func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - key := serialize(in.Location) - if _, present := s.routeNotes[key]; !present { - s.routeNotes[key] = []*pb.RouteNote{in} - } else { - s.routeNotes[key] = append(s.routeNotes[key], in) - } - for _, note := range s.routeNotes[key] { - if err := stream.Send(note); err != nil { - return err - } - } - } -} - -// loadFeatures loads features from a JSON file. -func (s *routeGuideServer) loadFeatures(filePath string) { - file, err := ioutil.ReadFile(filePath) - if err != nil { - log.Fatalf("Failed to load default features: %v", err) - } - if err := json.Unmarshal(file, &s.savedFeatures); err != nil { - log.Fatalf("Failed to load default features: %v", err) - } -} - -func toRadians(num float64) float64 { - return num * math.Pi / float64(180) -} - -// calcDistance calculates the distance between two points using the "haversine" formula. -// This code was taken from http://www.movable-type.co.uk/scripts/latlong.html. -func calcDistance(p1 *pb.Point, p2 *pb.Point) int32 { - const CordFactor float64 = 1e7 - const R float64 = float64(6371000) // metres - lat1 := float64(p1.Latitude) / CordFactor - lat2 := float64(p2.Latitude) / CordFactor - lng1 := float64(p1.Longitude) / CordFactor - lng2 := float64(p2.Longitude) / CordFactor - φ1 := toRadians(lat1) - φ2 := toRadians(lat2) - Δφ := toRadians(lat2 - lat1) - Δλ := toRadians(lng2 - lng1) - - a := math.Sin(Δφ/2)*math.Sin(Δφ/2) + - math.Cos(φ1)*math.Cos(φ2)* - math.Sin(Δλ/2)*math.Sin(Δλ/2) - c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) - - distance := R * c - return int32(distance) -} - -func inRange(point *pb.Point, rect *pb.Rectangle) bool { - left := math.Min(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude)) - right := math.Max(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude)) - top := math.Max(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude)) - bottom := math.Min(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude)) - - if float64(point.Longitude) >= left && - float64(point.Longitude) <= right && - float64(point.Latitude) >= bottom && - float64(point.Latitude) <= top { - return true - } - return false -} - -func serialize(point *pb.Point) string { - return fmt.Sprintf("%d %d", point.Latitude, point.Longitude) -} - -func newServer() *routeGuideServer { - s := new(routeGuideServer) - s.loadFeatures(*jsonDBFile) - s.routeNotes = make(map[string][]*pb.RouteNote) - return s -} - -func main() { - flag.Parse() - lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port)) - if err != nil { - log.Fatalf("failed to listen: %v", err) - } - var opts []grpc.ServerOption - if *tls { - if *certFile == "" { - *certFile = testdata.Path("server1.pem") - } - if *keyFile == "" { - *keyFile = testdata.Path("server1.key") - } - creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) - if err != nil { - log.Fatalf("Failed to generate credentials %v", err) - } - opts = []grpc.ServerOption{grpc.Creds(creds)} - } - grpcServer := grpc.NewServer(opts...) - pb.RegisterRouteGuideServer(grpcServer, newServer()) - grpcServer.Serve(lis) -} diff --git a/vendor/google.golang.org/grpc/examples/route_guide/testdata/route_guide_db.json b/vendor/google.golang.org/grpc/examples/route_guide/testdata/route_guide_db.json deleted file mode 100644 index 9d6a980ab..000000000 --- a/vendor/google.golang.org/grpc/examples/route_guide/testdata/route_guide_db.json +++ /dev/null @@ -1,601 +0,0 @@ -[{ - "location": { - "latitude": 407838351, - "longitude": -746143763 - }, - "name": "Patriots Path, Mendham, NJ 07945, USA" -}, { - "location": { - "latitude": 408122808, - "longitude": -743999179 - }, - "name": "101 New Jersey 10, Whippany, NJ 07981, USA" -}, { - "location": { - "latitude": 413628156, - "longitude": -749015468 - }, - "name": "U.S. 6, Shohola, PA 18458, USA" -}, { - "location": { - "latitude": 419999544, - "longitude": -740371136 - }, - "name": "5 Conners Road, Kingston, NY 12401, USA" -}, { - "location": { - "latitude": 414008389, - "longitude": -743951297 - }, - "name": "Mid Hudson Psychiatric Center, New Hampton, NY 10958, USA" -}, { - "location": { - "latitude": 419611318, - "longitude": -746524769 - }, - "name": "287 Flugertown Road, Livingston Manor, NY 12758, USA" -}, { - "location": { - "latitude": 406109563, - "longitude": -742186778 - }, - "name": "4001 Tremley Point Road, Linden, NJ 07036, USA" -}, { - "location": { - "latitude": 416802456, - "longitude": -742370183 - }, - "name": "352 South Mountain Road, Wallkill, NY 12589, USA" -}, { - "location": { - "latitude": 412950425, - "longitude": -741077389 - }, - "name": "Bailey Turn Road, Harriman, NY 10926, USA" -}, { - "location": { - "latitude": 412144655, - "longitude": -743949739 - }, - "name": "193-199 Wawayanda Road, Hewitt, NJ 07421, USA" -}, { - "location": { - "latitude": 415736605, - "longitude": -742847522 - }, - "name": "406-496 Ward Avenue, Pine Bush, NY 12566, USA" -}, { - "location": { - "latitude": 413843930, - "longitude": -740501726 - }, - "name": "162 Merrill Road, Highland Mills, NY 10930, USA" -}, { - "location": { - "latitude": 410873075, - "longitude": -744459023 - }, - "name": "Clinton Road, West Milford, NJ 07480, USA" -}, { - "location": { - "latitude": 412346009, - "longitude": -744026814 - }, - "name": "16 Old Brook Lane, Warwick, NY 10990, USA" -}, { - "location": { - "latitude": 402948455, - "longitude": -747903913 - }, - "name": "3 Drake Lane, Pennington, NJ 08534, USA" -}, { - "location": { - "latitude": 406337092, - "longitude": -740122226 - }, - "name": "6324 8th Avenue, Brooklyn, NY 11220, USA" -}, { - "location": { - "latitude": 406421967, - "longitude": -747727624 - }, - "name": "1 Merck Access Road, Whitehouse Station, NJ 08889, USA" -}, { - "location": { - "latitude": 416318082, - "longitude": -749677716 - }, - "name": "78-98 Schalck Road, Narrowsburg, NY 12764, USA" -}, { - "location": { - "latitude": 415301720, - "longitude": -748416257 - }, - "name": "282 Lakeview Drive Road, Highland Lake, NY 12743, USA" -}, { - "location": { - "latitude": 402647019, - "longitude": -747071791 - }, - "name": "330 Evelyn Avenue, Hamilton Township, NJ 08619, USA" -}, { - "location": { - "latitude": 412567807, - "longitude": -741058078 - }, - "name": "New York State Reference Route 987E, Southfields, NY 10975, USA" -}, { - "location": { - "latitude": 416855156, - "longitude": -744420597 - }, - "name": "103-271 Tempaloni Road, Ellenville, NY 12428, USA" -}, { - "location": { - "latitude": 404663628, - "longitude": -744820157 - }, - "name": "1300 Airport Road, North Brunswick Township, NJ 08902, USA" -}, { - "location": { - "latitude": 407113723, - "longitude": -749746483 - }, - "name": "" -}, { - "location": { - "latitude": 402133926, - "longitude": -743613249 - }, - "name": "" -}, { - "location": { - "latitude": 400273442, - "longitude": -741220915 - }, - "name": "" -}, { - "location": { - "latitude": 411236786, - "longitude": -744070769 - }, - "name": "" -}, { - "location": { - "latitude": 411633782, - "longitude": -746784970 - }, - "name": "211-225 Plains Road, Augusta, NJ 07822, USA" -}, { - "location": { - "latitude": 415830701, - "longitude": -742952812 - }, - "name": "" -}, { - "location": { - "latitude": 413447164, - "longitude": -748712898 - }, - "name": "165 Pedersen Ridge Road, Milford, PA 18337, USA" -}, { - "location": { - "latitude": 405047245, - "longitude": -749800722 - }, - "name": "100-122 Locktown Road, Frenchtown, NJ 08825, USA" -}, { - "location": { - "latitude": 418858923, - "longitude": -746156790 - }, - "name": "" -}, { - "location": { - "latitude": 417951888, - "longitude": -748484944 - }, - "name": "650-652 Willi Hill Road, Swan Lake, NY 12783, USA" -}, { - "location": { - "latitude": 407033786, - "longitude": -743977337 - }, - "name": "26 East 3rd Street, New Providence, NJ 07974, USA" -}, { - "location": { - "latitude": 417548014, - "longitude": -740075041 - }, - "name": "" -}, { - "location": { - "latitude": 410395868, - "longitude": -744972325 - }, - "name": "" -}, { - "location": { - "latitude": 404615353, - "longitude": -745129803 - }, - "name": "" -}, { - "location": { - "latitude": 406589790, - "longitude": -743560121 - }, - "name": "611 Lawrence Avenue, Westfield, NJ 07090, USA" -}, { - "location": { - "latitude": 414653148, - "longitude": -740477477 - }, - "name": "18 Lannis Avenue, New Windsor, NY 12553, USA" -}, { - "location": { - "latitude": 405957808, - "longitude": -743255336 - }, - "name": "82-104 Amherst Avenue, Colonia, NJ 07067, USA" -}, { - "location": { - "latitude": 411733589, - "longitude": -741648093 - }, - "name": "170 Seven Lakes Drive, Sloatsburg, NY 10974, USA" -}, { - "location": { - "latitude": 412676291, - "longitude": -742606606 - }, - "name": "1270 Lakes Road, Monroe, NY 10950, USA" -}, { - "location": { - "latitude": 409224445, - "longitude": -748286738 - }, - "name": "509-535 Alphano Road, Great Meadows, NJ 07838, USA" -}, { - "location": { - "latitude": 406523420, - "longitude": -742135517 - }, - "name": "652 Garden Street, Elizabeth, NJ 07202, USA" -}, { - "location": { - "latitude": 401827388, - "longitude": -740294537 - }, - "name": "349 Sea Spray Court, Neptune City, NJ 07753, USA" -}, { - "location": { - "latitude": 410564152, - "longitude": -743685054 - }, - "name": "13-17 Stanley Street, West Milford, NJ 07480, USA" -}, { - "location": { - "latitude": 408472324, - "longitude": -740726046 - }, - "name": "47 Industrial Avenue, Teterboro, NJ 07608, USA" -}, { - "location": { - "latitude": 412452168, - "longitude": -740214052 - }, - "name": "5 White Oak Lane, Stony Point, NY 10980, USA" -}, { - "location": { - "latitude": 409146138, - "longitude": -746188906 - }, - "name": "Berkshire Valley Management Area Trail, Jefferson, NJ, USA" -}, { - "location": { - "latitude": 404701380, - "longitude": -744781745 - }, - "name": "1007 Jersey Avenue, New Brunswick, NJ 08901, USA" -}, { - "location": { - "latitude": 409642566, - "longitude": -746017679 - }, - "name": "6 East Emerald Isle Drive, Lake Hopatcong, NJ 07849, USA" -}, { - "location": { - "latitude": 408031728, - "longitude": -748645385 - }, - "name": "1358-1474 New Jersey 57, Port Murray, NJ 07865, USA" -}, { - "location": { - "latitude": 413700272, - "longitude": -742135189 - }, - "name": "367 Prospect Road, Chester, NY 10918, USA" -}, { - "location": { - "latitude": 404310607, - "longitude": -740282632 - }, - "name": "10 Simon Lake Drive, Atlantic Highlands, NJ 07716, USA" -}, { - "location": { - "latitude": 409319800, - "longitude": -746201391 - }, - "name": "11 Ward Street, Mount Arlington, NJ 07856, USA" -}, { - "location": { - "latitude": 406685311, - "longitude": -742108603 - }, - "name": "300-398 Jefferson Avenue, Elizabeth, NJ 07201, USA" -}, { - "location": { - "latitude": 419018117, - "longitude": -749142781 - }, - "name": "43 Dreher Road, Roscoe, NY 12776, USA" -}, { - "location": { - "latitude": 412856162, - "longitude": -745148837 - }, - "name": "Swan Street, Pine Island, NY 10969, USA" -}, { - "location": { - "latitude": 416560744, - "longitude": -746721964 - }, - "name": "66 Pleasantview Avenue, Monticello, NY 12701, USA" -}, { - "location": { - "latitude": 405314270, - "longitude": -749836354 - }, - "name": "" -}, { - "location": { - "latitude": 414219548, - "longitude": -743327440 - }, - "name": "" -}, { - "location": { - "latitude": 415534177, - "longitude": -742900616 - }, - "name": "565 Winding Hills Road, Montgomery, NY 12549, USA" -}, { - "location": { - "latitude": 406898530, - "longitude": -749127080 - }, - "name": "231 Rocky Run Road, Glen Gardner, NJ 08826, USA" -}, { - "location": { - "latitude": 407586880, - "longitude": -741670168 - }, - "name": "100 Mount Pleasant Avenue, Newark, NJ 07104, USA" -}, { - "location": { - "latitude": 400106455, - "longitude": -742870190 - }, - "name": "517-521 Huntington Drive, Manchester Township, NJ 08759, USA" -}, { - "location": { - "latitude": 400066188, - "longitude": -746793294 - }, - "name": "" -}, { - "location": { - "latitude": 418803880, - "longitude": -744102673 - }, - "name": "40 Mountain Road, Napanoch, NY 12458, USA" -}, { - "location": { - "latitude": 414204288, - "longitude": -747895140 - }, - "name": "" -}, { - "location": { - "latitude": 414777405, - "longitude": -740615601 - }, - "name": "" -}, { - "location": { - "latitude": 415464475, - "longitude": -747175374 - }, - "name": "48 North Road, Forestburgh, NY 12777, USA" -}, { - "location": { - "latitude": 404062378, - "longitude": -746376177 - }, - "name": "" -}, { - "location": { - "latitude": 405688272, - "longitude": -749285130 - }, - "name": "" -}, { - "location": { - "latitude": 400342070, - "longitude": -748788996 - }, - "name": "" -}, { - "location": { - "latitude": 401809022, - "longitude": -744157964 - }, - "name": "" -}, { - "location": { - "latitude": 404226644, - "longitude": -740517141 - }, - "name": "9 Thompson Avenue, Leonardo, NJ 07737, USA" -}, { - "location": { - "latitude": 410322033, - "longitude": -747871659 - }, - "name": "" -}, { - "location": { - "latitude": 407100674, - "longitude": -747742727 - }, - "name": "" -}, { - "location": { - "latitude": 418811433, - "longitude": -741718005 - }, - "name": "213 Bush Road, Stone Ridge, NY 12484, USA" -}, { - "location": { - "latitude": 415034302, - "longitude": -743850945 - }, - "name": "" -}, { - "location": { - "latitude": 411349992, - "longitude": -743694161 - }, - "name": "" -}, { - "location": { - "latitude": 404839914, - "longitude": -744759616 - }, - "name": "1-17 Bergen Court, New Brunswick, NJ 08901, USA" -}, { - "location": { - "latitude": 414638017, - "longitude": -745957854 - }, - "name": "35 Oakland Valley Road, Cuddebackville, NY 12729, USA" -}, { - "location": { - "latitude": 412127800, - "longitude": -740173578 - }, - "name": "" -}, { - "location": { - "latitude": 401263460, - "longitude": -747964303 - }, - "name": "" -}, { - "location": { - "latitude": 412843391, - "longitude": -749086026 - }, - "name": "" -}, { - "location": { - "latitude": 418512773, - "longitude": -743067823 - }, - "name": "" -}, { - "location": { - "latitude": 404318328, - "longitude": -740835638 - }, - "name": "42-102 Main Street, Belford, NJ 07718, USA" -}, { - "location": { - "latitude": 419020746, - "longitude": -741172328 - }, - "name": "" -}, { - "location": { - "latitude": 404080723, - "longitude": -746119569 - }, - "name": "" -}, { - "location": { - "latitude": 401012643, - "longitude": -744035134 - }, - "name": "" -}, { - "location": { - "latitude": 404306372, - "longitude": -741079661 - }, - "name": "" -}, { - "location": { - "latitude": 403966326, - "longitude": -748519297 - }, - "name": "" -}, { - "location": { - "latitude": 405002031, - "longitude": -748407866 - }, - "name": "" -}, { - "location": { - "latitude": 409532885, - "longitude": -742200683 - }, - "name": "" -}, { - "location": { - "latitude": 416851321, - "longitude": -742674555 - }, - "name": "" -}, { - "location": { - "latitude": 406411633, - "longitude": -741722051 - }, - "name": "3387 Richmond Terrace, Staten Island, NY 10303, USA" -}, { - "location": { - "latitude": 413069058, - "longitude": -744597778 - }, - "name": "261 Van Sickle Road, Goshen, NY 10924, USA" -}, { - "location": { - "latitude": 418465462, - "longitude": -746859398 - }, - "name": "" -}, { - "location": { - "latitude": 411733222, - "longitude": -744228360 - }, - "name": "" -}, { - "location": { - "latitude": 410248224, - "longitude": -747127767 - }, - "name": "3 Hasta Way, Newton, NJ 07860, USA" -}] diff --git a/vendor/google.golang.org/grpc/go16.go b/vendor/google.golang.org/grpc/go16.go new file mode 100644 index 000000000..f3dbf2170 --- /dev/null +++ b/vendor/google.golang.org/grpc/go16.go @@ -0,0 +1,98 @@ +// +build go1.6,!go1.7 + +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "fmt" + "io" + "net" + "net/http" + "os" + + "golang.org/x/net/context" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/grpc/transport" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) +} + +func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { + req.Cancel = ctx.Done() + if err := req.Write(conn); err != nil { + return fmt.Errorf("failed to write the HTTP request: %v", err) + } + return nil +} + +// toRPCErr converts an error into an error from the status package. +func toRPCErr(err error) error { + if _, ok := status.FromError(err); ok { + return err + } + switch e := err.(type) { + case transport.StreamError: + return status.Error(e.Code, e.Desc) + case transport.ConnectionError: + return status.Error(codes.Unavailable, e.Desc) + default: + switch err { + case context.DeadlineExceeded: + return status.Error(codes.DeadlineExceeded, err.Error()) + case context.Canceled: + return status.Error(codes.Canceled, err.Error()) + case ErrClientConnClosing: + return status.Error(codes.FailedPrecondition, err.Error()) + } + } + return status.Error(codes.Unknown, err.Error()) +} + +// convertCode converts a standard Go error into its canonical code. Note that +// this is only used to translate the error returned by the server applications. +func convertCode(err error) codes.Code { + switch err { + case nil: + return codes.OK + case io.EOF: + return codes.OutOfRange + case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF: + return codes.FailedPrecondition + case os.ErrInvalid: + return codes.InvalidArgument + case context.Canceled: + return codes.Canceled + case context.DeadlineExceeded: + return codes.DeadlineExceeded + } + switch { + case os.IsExist(err): + return codes.AlreadyExists + case os.IsNotExist(err): + return codes.NotFound + case os.IsPermission(err): + return codes.PermissionDenied + } + return codes.Unknown +} diff --git a/vendor/google.golang.org/grpc/go17.go b/vendor/google.golang.org/grpc/go17.go new file mode 100644 index 000000000..de23098eb --- /dev/null +++ b/vendor/google.golang.org/grpc/go17.go @@ -0,0 +1,99 @@ +// +build go1.7 + +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "os" + + netctx "golang.org/x/net/context" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/grpc/transport" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, network, address) +} + +func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { + req = req.WithContext(ctx) + if err := req.Write(conn); err != nil { + return fmt.Errorf("failed to write the HTTP request: %v", err) + } + return nil +} + +// toRPCErr converts an error into an error from the status package. +func toRPCErr(err error) error { + if _, ok := status.FromError(err); ok { + return err + } + switch e := err.(type) { + case transport.StreamError: + return status.Error(e.Code, e.Desc) + case transport.ConnectionError: + return status.Error(codes.Unavailable, e.Desc) + default: + switch err { + case context.DeadlineExceeded, netctx.DeadlineExceeded: + return status.Error(codes.DeadlineExceeded, err.Error()) + case context.Canceled, netctx.Canceled: + return status.Error(codes.Canceled, err.Error()) + case ErrClientConnClosing: + return status.Error(codes.FailedPrecondition, err.Error()) + } + } + return status.Error(codes.Unknown, err.Error()) +} + +// convertCode converts a standard Go error into its canonical code. Note that +// this is only used to translate the error returned by the server applications. +func convertCode(err error) codes.Code { + switch err { + case nil: + return codes.OK + case io.EOF: + return codes.OutOfRange + case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF: + return codes.FailedPrecondition + case os.ErrInvalid: + return codes.InvalidArgument + case context.Canceled, netctx.Canceled: + return codes.Canceled + case context.DeadlineExceeded, netctx.DeadlineExceeded: + return codes.DeadlineExceeded + } + switch { + case os.IsExist(err): + return codes.AlreadyExists + case os.IsNotExist(err): + return codes.NotFound + case os.IsPermission(err): + return codes.PermissionDenied + } + return codes.Unknown +} diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto index 2ed04551f..42d99c109 100644 --- a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto +++ b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto @@ -15,7 +15,7 @@ syntax = "proto3"; package grpc.lb.v1; -option go_package = "messages"; +option go_package = "google.golang.org/grpc/grpclb/grpc_lb_v1/messages"; message Duration { // Signed seconds of the span of time. Must be from -315,576,000,000 diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.pb.go b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.pb.go deleted file mode 100644 index ebcbe56d8..000000000 --- a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.pb.go +++ /dev/null @@ -1,154 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_lb_v1/service/service.proto - -/* -Package service is a generated protocol buffer package. - -It is generated from these files: - grpc_lb_v1/service/service.proto - -It has these top-level messages: -*/ -package service - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import grpc_lb_v1 "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for LoadBalancer service - -type LoadBalancerClient interface { - // Bidirectional rpc to get a list of servers. - BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) -} - -type loadBalancerClient struct { - cc *grpc.ClientConn -} - -func NewLoadBalancerClient(cc *grpc.ClientConn) LoadBalancerClient { - return &loadBalancerClient{cc} -} - -func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) { - stream, err := grpc.NewClientStream(ctx, &_LoadBalancer_serviceDesc.Streams[0], c.cc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) - if err != nil { - return nil, err - } - x := &loadBalancerBalanceLoadClient{stream} - return x, nil -} - -type LoadBalancer_BalanceLoadClient interface { - Send(*grpc_lb_v1.LoadBalanceRequest) error - Recv() (*grpc_lb_v1.LoadBalanceResponse, error) - grpc.ClientStream -} - -type loadBalancerBalanceLoadClient struct { - grpc.ClientStream -} - -func (x *loadBalancerBalanceLoadClient) Send(m *grpc_lb_v1.LoadBalanceRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *loadBalancerBalanceLoadClient) Recv() (*grpc_lb_v1.LoadBalanceResponse, error) { - m := new(grpc_lb_v1.LoadBalanceResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for LoadBalancer service - -type LoadBalancerServer interface { - // Bidirectional rpc to get a list of servers. - BalanceLoad(LoadBalancer_BalanceLoadServer) error -} - -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 { - Send(*grpc_lb_v1.LoadBalanceResponse) error - Recv() (*grpc_lb_v1.LoadBalanceRequest, error) - grpc.ServerStream -} - -type loadBalancerBalanceLoadServer struct { - grpc.ServerStream -} - -func (x *loadBalancerBalanceLoadServer) Send(m *grpc_lb_v1.LoadBalanceResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *loadBalancerBalanceLoadServer) Recv() (*grpc_lb_v1.LoadBalanceRequest, error) { - m := new(grpc_lb_v1.LoadBalanceRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _LoadBalancer_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.lb.v1.LoadBalancer", - HandlerType: (*LoadBalancerServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "BalanceLoad", - Handler: _LoadBalancer_BalanceLoad_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_lb_v1/service/service.proto", -} - -func init() { proto.RegisterFile("grpc_lb_v1/service/service.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 142 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0x2f, 0x2a, 0x48, - 0x8e, 0xcf, 0x49, 0x8a, 0x2f, 0x33, 0xd4, 0x2f, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0x85, 0xd1, - 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x5c, 0x20, 0x15, 0x7a, 0x39, 0x49, 0x7a, 0x65, 0x86, - 0x52, 0x4a, 0x48, 0xaa, 0x73, 0x53, 0x8b, 0x8b, 0x13, 0xd3, 0x53, 0x8b, 0xe1, 0x0c, 0x88, 0x7a, - 0xa3, 0x24, 0x2e, 0x1e, 0x9f, 0xfc, 0xc4, 0x14, 0xa7, 0xc4, 0x9c, 0xc4, 0xbc, 0xe4, 0xd4, 0x22, - 0xa1, 0x20, 0x2e, 0x6e, 0x28, 0x1b, 0x24, 0x2c, 0x24, 0xa7, 0x87, 0x30, 0x4f, 0x0f, 0x49, 0x61, - 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x94, 0x3c, 0x4e, 0xf9, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, - 0x54, 0x0d, 0x46, 0x03, 0x46, 0x27, 0xce, 0x28, 0x76, 0xa8, 0x23, 0x93, 0xd8, 0xc0, 0xb6, 0x1a, - 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x39, 0x4e, 0xb0, 0xf8, 0xc9, 0x00, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.proto b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.proto deleted file mode 100644 index 02c1a8b77..000000000 --- a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.proto +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.lb.v1; -option go_package = "service"; - -import "grpc_lb_v1/messages/messages.proto"; - -service LoadBalancer { - // Bidirectional rpc to get a list of servers. - rpc BalanceLoad(stream LoadBalanceRequest) - returns (stream LoadBalanceResponse); -} diff --git a/vendor/google.golang.org/grpc/grpclb/grpclb_test.go b/vendor/google.golang.org/grpc/grpclb/grpclb_test.go index 46c1fe5b9..1491be788 100644 --- a/vendor/google.golang.org/grpc/grpclb/grpclb_test.go +++ b/vendor/google.golang.org/grpc/grpclb/grpclb_test.go @@ -16,8 +16,8 @@ * */ -//go:generate protoc --go_out=plugins=:. grpc_lb_v1/messages/messages.proto -//go:generate protoc --go_out=Mgrpc_lb_v1/messages/messages.proto=google.golang.org/grpc/grpclb/grpc_lb_v1/messages,plugins=grpc:. grpc_lb_v1/service/service.proto +//go:generate protoc --go_out=plugins=:$GOPATH grpc_lb_v1/messages/messages.proto +//go:generate protoc --go_out=plugins=grpc:$GOPATH grpc_lb_v1/service/service.proto // Package grpclb_test is currently used only for grpclb testing. package grpclb_test @@ -42,6 +42,7 @@ import ( _ "google.golang.org/grpc/grpclog/glogger" "google.golang.org/grpc/metadata" "google.golang.org/grpc/naming" + "google.golang.org/grpc/status" testpb "google.golang.org/grpc/test/grpc_testing" "google.golang.org/grpc/test/leakcheck" ) @@ -151,9 +152,19 @@ func (c *serverNameCheckCreds) ClientHandshake(ctx context.Context, addr string, c.mu.Lock() defer c.mu.Unlock() b := make([]byte, len(c.expected)) - if _, err := rawConn.Read(b); err != nil { - fmt.Printf("Failed to read the server name from the server %v", err) - return nil, nil, err + errCh := make(chan error, 1) + go func() { + _, err := rawConn.Read(b) + errCh <- err + }() + select { + case err := <-errCh: + if err != nil { + fmt.Printf("Failed to read the server name from the server %v", err) + return nil, nil, err + } + case <-ctx.Done(): + return nil, nil, ctx.Err() } if c.expected != string(b) { fmt.Printf("Read the server name %s want %s", string(b), c.expected) @@ -215,7 +226,7 @@ func (b *remoteBalancer) BalanceLoad(stream lbspb.LoadBalancer_BalanceLoadServer } initReq := req.GetInitialRequest() if initReq.Name != besn { - return grpc.Errorf(codes.InvalidArgument, "invalid service name: %v", initReq.Name) + return status.Errorf(codes.InvalidArgument, "invalid service name: %v", initReq.Name) } resp := &lbmpb.LoadBalanceResponse{ LoadBalanceResponseType: &lbmpb.LoadBalanceResponse_InitialResponse{ @@ -275,10 +286,10 @@ const testmdkey = "testmd" func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { - return nil, grpc.Errorf(codes.Internal, "failed to receive metadata") + return nil, status.Error(codes.Internal, "failed to receive metadata") } if md == nil || md["lb-token"][0] != lbToken { - return nil, grpc.Errorf(codes.Internal, "received unexpected metadata: %v", md) + return nil, status.Errorf(codes.Internal, "received unexpected metadata: %v", md) } grpc.SetTrailer(ctx, metadata.Pairs(testmdkey, s.addr)) return &testpb.Empty{}, nil diff --git a/vendor/google.golang.org/grpc/grpclog/glogger/glogger.go b/vendor/google.golang.org/grpc/grpclog/glogger/glogger.go deleted file mode 100644 index e5498f823..000000000 --- a/vendor/google.golang.org/grpc/grpclog/glogger/glogger.go +++ /dev/null @@ -1,86 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package glogger defines glog-based logging for grpc. -// Importing this package will install glog as the logger used by grpclog. -package glogger - -import ( - "fmt" - - "github.com/golang/glog" - "google.golang.org/grpc/grpclog" -) - -func init() { - grpclog.SetLoggerV2(&glogger{}) -} - -type glogger struct{} - -func (g *glogger) Info(args ...interface{}) { - glog.InfoDepth(2, args...) -} - -func (g *glogger) Infoln(args ...interface{}) { - glog.InfoDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Infof(format string, args ...interface{}) { - glog.InfoDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) Warning(args ...interface{}) { - glog.WarningDepth(2, args...) -} - -func (g *glogger) Warningln(args ...interface{}) { - glog.WarningDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Warningf(format string, args ...interface{}) { - glog.WarningDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) Error(args ...interface{}) { - glog.ErrorDepth(2, args...) -} - -func (g *glogger) Errorln(args ...interface{}) { - glog.ErrorDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Errorf(format string, args ...interface{}) { - glog.ErrorDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) Fatal(args ...interface{}) { - glog.FatalDepth(2, args...) -} - -func (g *glogger) Fatalln(args ...interface{}) { - glog.FatalDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Fatalf(format string, args ...interface{}) { - glog.FatalDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) V(l int) bool { - return bool(glog.V(glog.Level(l))) -} diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go deleted file mode 100644 index fdcbb9e0b..000000000 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ /dev/null @@ -1,190 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_health_v1/health.proto - -/* -Package grpc_health_v1 is a generated protocol buffer package. - -It is generated from these files: - grpc_health_v1/health.proto - -It has these top-level messages: - HealthCheckRequest - HealthCheckResponse -*/ -package grpc_health_v1 - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type HealthCheckResponse_ServingStatus int32 - -const ( - HealthCheckResponse_UNKNOWN HealthCheckResponse_ServingStatus = 0 - HealthCheckResponse_SERVING HealthCheckResponse_ServingStatus = 1 - HealthCheckResponse_NOT_SERVING HealthCheckResponse_ServingStatus = 2 -) - -var HealthCheckResponse_ServingStatus_name = map[int32]string{ - 0: "UNKNOWN", - 1: "SERVING", - 2: "NOT_SERVING", -} -var HealthCheckResponse_ServingStatus_value = map[string]int32{ - "UNKNOWN": 0, - "SERVING": 1, - "NOT_SERVING": 2, -} - -func (x HealthCheckResponse_ServingStatus) String() string { - return proto.EnumName(HealthCheckResponse_ServingStatus_name, int32(x)) -} -func (HealthCheckResponse_ServingStatus) EnumDescriptor() ([]byte, []int) { - return fileDescriptor0, []int{1, 0} -} - -type HealthCheckRequest struct { - Service string `protobuf:"bytes,1,opt,name=service" json:"service,omitempty"` -} - -func (m *HealthCheckRequest) Reset() { *m = HealthCheckRequest{} } -func (m *HealthCheckRequest) String() string { return proto.CompactTextString(m) } -func (*HealthCheckRequest) ProtoMessage() {} -func (*HealthCheckRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *HealthCheckRequest) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -type HealthCheckResponse struct { - Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,enum=grpc.health.v1.HealthCheckResponse_ServingStatus" json:"status,omitempty"` -} - -func (m *HealthCheckResponse) Reset() { *m = HealthCheckResponse{} } -func (m *HealthCheckResponse) String() string { return proto.CompactTextString(m) } -func (*HealthCheckResponse) ProtoMessage() {} -func (*HealthCheckResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *HealthCheckResponse) GetStatus() HealthCheckResponse_ServingStatus { - if m != nil { - return m.Status - } - return HealthCheckResponse_UNKNOWN -} - -func init() { - proto.RegisterType((*HealthCheckRequest)(nil), "grpc.health.v1.HealthCheckRequest") - proto.RegisterType((*HealthCheckResponse)(nil), "grpc.health.v1.HealthCheckResponse") - proto.RegisterEnum("grpc.health.v1.HealthCheckResponse_ServingStatus", HealthCheckResponse_ServingStatus_name, HealthCheckResponse_ServingStatus_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for Health service - -type HealthClient interface { - Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) -} - -type healthClient struct { - cc *grpc.ClientConn -} - -func NewHealthClient(cc *grpc.ClientConn) HealthClient { - return &healthClient{cc} -} - -func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { - out := new(HealthCheckResponse) - err := grpc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Health service - -type HealthServer interface { - Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) -} - -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) -} - -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{}, - Metadata: "grpc_health_v1/health.proto", -} - -func init() { proto.RegisterFile("grpc_health_v1/health.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 213 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0x2f, 0x2a, 0x48, - 0x8e, 0xcf, 0x48, 0x4d, 0xcc, 0x29, 0xc9, 0x88, 0x2f, 0x33, 0xd4, 0x87, 0xb0, 0xf4, 0x0a, 0x8a, - 0xf2, 0x4b, 0xf2, 0x85, 0xf8, 0x40, 0x92, 0x7a, 0x50, 0xa1, 0x32, 0x43, 0x25, 0x3d, 0x2e, 0x21, - 0x0f, 0x30, 0xc7, 0x39, 0x23, 0x35, 0x39, 0x3b, 0x28, 0xb5, 0xb0, 0x34, 0xb5, 0xb8, 0x44, 0x48, - 0x82, 0x8b, 0xbd, 0x38, 0xb5, 0xa8, 0x2c, 0x33, 0x39, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, - 0x08, 0xc6, 0x55, 0x9a, 0xc3, 0xc8, 0x25, 0x8c, 0xa2, 0xa1, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, - 0xc8, 0x93, 0x8b, 0xad, 0xb8, 0x24, 0xb1, 0xa4, 0xb4, 0x18, 0xac, 0x81, 0xcf, 0xc8, 0x50, 0x0f, - 0xd5, 0x22, 0x3d, 0x2c, 0x9a, 0xf4, 0x82, 0x41, 0x86, 0xe6, 0xa5, 0x07, 0x83, 0x35, 0x06, 0x41, - 0x0d, 0x50, 0xb2, 0xe2, 0xe2, 0x45, 0x91, 0x10, 0xe2, 0xe6, 0x62, 0x0f, 0xf5, 0xf3, 0xf6, 0xf3, - 0x0f, 0xf7, 0x13, 0x60, 0x00, 0x71, 0x82, 0x5d, 0x83, 0xc2, 0x3c, 0xfd, 0xdc, 0x05, 0x18, 0x85, - 0xf8, 0xb9, 0xb8, 0xfd, 0xfc, 0x43, 0xe2, 0x61, 0x02, 0x4c, 0x46, 0x51, 0x5c, 0x6c, 0x10, 0x8b, - 0x84, 0x02, 0xb8, 0x58, 0xc1, 0x96, 0x09, 0x29, 0xe1, 0x75, 0x09, 0xd8, 0xbf, 0x52, 0xca, 0x44, - 0xb8, 0x36, 0x89, 0x0d, 0x1c, 0x82, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x53, 0x2b, 0x65, - 0x20, 0x60, 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.proto b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.proto deleted file mode 100644 index 6072fdc3b..000000000 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.proto +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.health.v1; - -message HealthCheckRequest { - string service = 1; -} - -message HealthCheckResponse { - enum ServingStatus { - UNKNOWN = 0; - SERVING = 1; - NOT_SERVING = 2; - } - ServingStatus status = 1; -} - -service Health{ - rpc Check(HealthCheckRequest) returns (HealthCheckResponse); -} diff --git a/vendor/google.golang.org/grpc/health/health.go b/vendor/google.golang.org/grpc/health/health.go deleted file mode 100644 index c6212f406..000000000 --- a/vendor/google.golang.org/grpc/health/health.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_health_v1/health.proto - -// Package health provides some utility functions to health-check a server. The implementation -// is based on protobuf. Users need to write their own implementations if other IDLs are used. -package health - -import ( - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - healthpb "google.golang.org/grpc/health/grpc_health_v1" -) - -// Server implements `service Health`. -type Server struct { - mu sync.Mutex - // statusMap stores the serving status of the services this Server monitors. - statusMap map[string]healthpb.HealthCheckResponse_ServingStatus -} - -// NewServer returns a new Server. -func NewServer() *Server { - return &Server{ - statusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus), - } -} - -// Check implements `service Health`. -func (s *Server) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) { - s.mu.Lock() - defer s.mu.Unlock() - if in.Service == "" { - // check the server overall health status. - return &healthpb.HealthCheckResponse{ - Status: healthpb.HealthCheckResponse_SERVING, - }, nil - } - if status, ok := s.statusMap[in.Service]; ok { - return &healthpb.HealthCheckResponse{ - Status: status, - }, nil - } - return nil, grpc.Errorf(codes.NotFound, "unknown service") -} - -// SetServingStatus is called when need to reset the serving status of a service -// or insert a new service entry into the statusMap. -func (s *Server) SetServingStatus(service string, status healthpb.HealthCheckResponse_ServingStatus) { - s.mu.Lock() - s.statusMap[service] = status - s.mu.Unlock() -} diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 07083832c..53f177520 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -19,13 +19,6 @@ // the godoc of the top-level grpc package. package internal -// TestingCloseConns closes all existing transports but keeps -// grpcServer.lis accepting new connections. -// -// The provided grpcServer must be of type *grpc.Server. It is untyped -// for circular dependency reasons. -var TestingCloseConns func(grpcServer interface{}) - // TestingUseHandlerImpl enables the http.Handler-based server implementation. // It must be called before Serve and requires TLS credentials. // diff --git a/vendor/google.golang.org/grpc/interop/client/client.go b/vendor/google.golang.org/grpc/interop/client/client.go deleted file mode 100644 index da6bc2d20..000000000 --- a/vendor/google.golang.org/grpc/interop/client/client.go +++ /dev/null @@ -1,190 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "net" - "strconv" - - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/oauth" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/testdata" -) - -var ( - caFile = flag.String("ca_file", "", "The file containning the CA root cert file") - useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP") - testCA = flag.Bool("use_test_ca", false, "Whether to replace platform root CAs with test CA as the CA root") - serviceAccountKeyFile = flag.String("service_account_key_file", "", "Path to service account json key file") - oauthScope = flag.String("oauth_scope", "", "The scope for OAuth2 tokens") - defaultServiceAccount = flag.String("default_service_account", "", "Email of GCE default service account") - serverHost = flag.String("server_host", "localhost", "The server host name") - serverPort = flag.Int("server_port", 10000, "The server port number") - tlsServerName = flag.String("server_host_override", "", "The server name use to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.") - testCase = flag.String("test_case", "large_unary", - `Configure different test cases. Valid options are: - empty_unary : empty (zero bytes) request and response; - large_unary : single request and (large) response; - client_streaming : request streaming with single response; - server_streaming : single request with response streaming; - ping_pong : full-duplex streaming; - empty_stream : full-duplex streaming with zero message; - timeout_on_sleeping_server: fullduplex streaming on a sleeping server; - compute_engine_creds: large_unary with compute engine auth; - service_account_creds: large_unary with service account auth; - jwt_token_creds: large_unary with jwt token auth; - per_rpc_creds: large_unary with per rpc token; - oauth2_auth_token: large_unary with oauth2 token auth; - cancel_after_begin: cancellation after metadata has been sent but before payloads are sent; - cancel_after_first_response: cancellation after receiving 1st message from the server; - status_code_and_message: status code propagated back to client; - custom_metadata: server will echo custom metadata; - unimplemented_method: client attempts to call unimplemented method; - unimplemented_service: client attempts to call unimplemented service.`) -) - -func main() { - flag.Parse() - serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort)) - var opts []grpc.DialOption - if *useTLS { - var sn string - if *tlsServerName != "" { - sn = *tlsServerName - } - var creds credentials.TransportCredentials - if *testCA { - var err error - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err = credentials.NewClientTLSFromFile(*caFile, sn) - if err != nil { - grpclog.Fatalf("Failed to create TLS credentials %v", err) - } - } else { - creds = credentials.NewClientTLSFromCert(nil, sn) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - if *testCase == "compute_engine_creds" { - opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine())) - } else if *testCase == "service_account_creds" { - jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope) - if err != nil { - grpclog.Fatalf("Failed to create JWT credentials: %v", err) - } - opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds)) - } else if *testCase == "jwt_token_creds" { - jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile) - if err != nil { - grpclog.Fatalf("Failed to create JWT credentials: %v", err) - } - opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds)) - } else if *testCase == "oauth2_auth_token" { - opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(interop.GetToken(*serviceAccountKeyFile, *oauthScope)))) - } - } else { - opts = append(opts, grpc.WithInsecure()) - } - opts = append(opts, grpc.WithBlock()) - conn, err := grpc.Dial(serverAddr, opts...) - if err != nil { - grpclog.Fatalf("Fail to dial: %v", err) - } - defer conn.Close() - tc := testpb.NewTestServiceClient(conn) - switch *testCase { - case "empty_unary": - interop.DoEmptyUnaryCall(tc) - grpclog.Println("EmptyUnaryCall done") - case "large_unary": - interop.DoLargeUnaryCall(tc) - grpclog.Println("LargeUnaryCall done") - case "client_streaming": - interop.DoClientStreaming(tc) - grpclog.Println("ClientStreaming done") - case "server_streaming": - interop.DoServerStreaming(tc) - grpclog.Println("ServerStreaming done") - case "ping_pong": - interop.DoPingPong(tc) - grpclog.Println("Pingpong done") - case "empty_stream": - interop.DoEmptyStream(tc) - grpclog.Println("Emptystream done") - case "timeout_on_sleeping_server": - interop.DoTimeoutOnSleepingServer(tc) - grpclog.Println("TimeoutOnSleepingServer done") - case "compute_engine_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.") - } - interop.DoComputeEngineCreds(tc, *defaultServiceAccount, *oauthScope) - grpclog.Println("ComputeEngineCreds done") - case "service_account_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.") - } - interop.DoServiceAccountCreds(tc, *serviceAccountKeyFile, *oauthScope) - grpclog.Println("ServiceAccountCreds done") - case "jwt_token_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute jwt_token_creds test case.") - } - interop.DoJWTTokenCreds(tc, *serviceAccountKeyFile) - grpclog.Println("JWTtokenCreds done") - case "per_rpc_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute per_rpc_creds test case.") - } - interop.DoPerRPCCreds(tc, *serviceAccountKeyFile, *oauthScope) - grpclog.Println("PerRPCCreds done") - case "oauth2_auth_token": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute oauth2_auth_token test case.") - } - interop.DoOauth2TokenCreds(tc, *serviceAccountKeyFile, *oauthScope) - grpclog.Println("Oauth2TokenCreds done") - case "cancel_after_begin": - interop.DoCancelAfterBegin(tc) - grpclog.Println("CancelAfterBegin done") - case "cancel_after_first_response": - interop.DoCancelAfterFirstResponse(tc) - grpclog.Println("CancelAfterFirstResponse done") - case "status_code_and_message": - interop.DoStatusCodeAndMessage(tc) - grpclog.Println("StatusCodeAndMessage done") - case "custom_metadata": - interop.DoCustomMetadata(tc) - grpclog.Println("CustomMetadata done") - case "unimplemented_method": - interop.DoUnimplementedMethod(conn) - grpclog.Println("UnimplementedMethod done") - case "unimplemented_service": - interop.DoUnimplementedService(testpb.NewUnimplementedServiceClient(conn)) - grpclog.Println("UnimplementedService done") - default: - grpclog.Fatal("Unsupported test case: ", *testCase) - } -} diff --git a/vendor/google.golang.org/grpc/interop/grpc_testing/test.pb.go b/vendor/google.golang.org/grpc/interop/grpc_testing/test.pb.go deleted file mode 100644 index b03c728c3..000000000 --- a/vendor/google.golang.org/grpc/interop/grpc_testing/test.pb.go +++ /dev/null @@ -1,905 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_testing/test.proto - -/* -Package grpc_testing is a generated protocol buffer package. - -It is generated from these files: - grpc_testing/test.proto - -It has these top-level messages: - Empty - Payload - EchoStatus - SimpleRequest - SimpleResponse - StreamingInputCallRequest - StreamingInputCallResponse - ResponseParameters - StreamingOutputCallRequest - StreamingOutputCallResponse -*/ -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The type of payload that should be returned. -type PayloadType int32 - -const ( - // Compressable text format. - PayloadType_COMPRESSABLE PayloadType = 0 - // Uncompressable binary format. - PayloadType_UNCOMPRESSABLE PayloadType = 1 - // Randomly chosen from all other formats defined in this enum. - PayloadType_RANDOM PayloadType = 2 -) - -var PayloadType_name = map[int32]string{ - 0: "COMPRESSABLE", - 1: "UNCOMPRESSABLE", - 2: "RANDOM", -} -var PayloadType_value = map[string]int32{ - "COMPRESSABLE": 0, - "UNCOMPRESSABLE": 1, - "RANDOM": 2, -} - -func (x PayloadType) Enum() *PayloadType { - p := new(PayloadType) - *p = x - return p -} -func (x PayloadType) String() string { - return proto.EnumName(PayloadType_name, int32(x)) -} -func (x *PayloadType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PayloadType_value, data, "PayloadType") - if err != nil { - return err - } - *x = PayloadType(value) - return nil -} -func (PayloadType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -type Empty struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -// A block of data, to simply increase gRPC message size. -type Payload struct { - // The type of data in body. - Type *PayloadType `protobuf:"varint,1,opt,name=type,enum=grpc.testing.PayloadType" json:"type,omitempty"` - // Primary contents of payload. - Body []byte `protobuf:"bytes,2,opt,name=body" json:"body,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Payload) Reset() { *m = Payload{} } -func (m *Payload) String() string { return proto.CompactTextString(m) } -func (*Payload) ProtoMessage() {} -func (*Payload) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *Payload) GetType() PayloadType { - if m != nil && m.Type != nil { - return *m.Type - } - return PayloadType_COMPRESSABLE -} - -func (m *Payload) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -type EchoStatus struct { - Code *int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` - Message *string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *EchoStatus) Reset() { *m = EchoStatus{} } -func (m *EchoStatus) String() string { return proto.CompactTextString(m) } -func (*EchoStatus) ProtoMessage() {} -func (*EchoStatus) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *EchoStatus) GetCode() int32 { - if m != nil && m.Code != nil { - return *m.Code - } - return 0 -} - -func (m *EchoStatus) GetMessage() string { - if m != nil && m.Message != nil { - return *m.Message - } - return "" -} - -// Unary request. -type SimpleRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - ResponseSize *int32 `protobuf:"varint,2,opt,name=response_size,json=responseSize" json:"response_size,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"` - // Whether SimpleResponse should include username. - FillUsername *bool `protobuf:"varint,4,opt,name=fill_username,json=fillUsername" json:"fill_username,omitempty"` - // Whether SimpleResponse should include OAuth scope. - FillOauthScope *bool `protobuf:"varint,5,opt,name=fill_oauth_scope,json=fillOauthScope" json:"fill_oauth_scope,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus" json:"response_status,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *SimpleRequest) GetResponseType() PayloadType { - if m != nil && m.ResponseType != nil { - return *m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *SimpleRequest) GetResponseSize() int32 { - if m != nil && m.ResponseSize != nil { - return *m.ResponseSize - } - return 0 -} - -func (m *SimpleRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleRequest) GetFillUsername() bool { - if m != nil && m.FillUsername != nil { - return *m.FillUsername - } - return false -} - -func (m *SimpleRequest) GetFillOauthScope() bool { - if m != nil && m.FillOauthScope != nil { - return *m.FillOauthScope - } - return false -} - -func (m *SimpleRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Unary response, as configured by the request. -type SimpleResponse struct { - // Payload to increase message size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` - // The user the request came from, for verifying authentication was - // successful when the client expected it. - Username *string `protobuf:"bytes,2,opt,name=username" json:"username,omitempty"` - // OAuth scope. - OauthScope *string `protobuf:"bytes,3,opt,name=oauth_scope,json=oauthScope" json:"oauth_scope,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -func (m *SimpleResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleResponse) GetUsername() string { - if m != nil && m.Username != nil { - return *m.Username - } - return "" -} - -func (m *SimpleResponse) GetOauthScope() string { - if m != nil && m.OauthScope != nil { - return *m.OauthScope - } - return "" -} - -// Client-streaming request. -type StreamingInputCallRequest struct { - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} } -func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallRequest) ProtoMessage() {} -func (*StreamingInputCallRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } - -func (m *StreamingInputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Client-streaming response. -type StreamingInputCallResponse struct { - // Aggregated size of payloads received from the client. - AggregatedPayloadSize *int32 `protobuf:"varint,1,opt,name=aggregated_payload_size,json=aggregatedPayloadSize" json:"aggregated_payload_size,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} } -func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallResponse) ProtoMessage() {} -func (*StreamingInputCallResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } - -func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 { - if m != nil && m.AggregatedPayloadSize != nil { - return *m.AggregatedPayloadSize - } - return 0 -} - -// Configuration for a particular response. -type ResponseParameters struct { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - Size *int32 `protobuf:"varint,1,opt,name=size" json:"size,omitempty"` - // Desired interval between consecutive responses in the response stream in - // microseconds. - IntervalUs *int32 `protobuf:"varint,2,opt,name=interval_us,json=intervalUs" json:"interval_us,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ResponseParameters) Reset() { *m = ResponseParameters{} } -func (m *ResponseParameters) String() string { return proto.CompactTextString(m) } -func (*ResponseParameters) ProtoMessage() {} -func (*ResponseParameters) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } - -func (m *ResponseParameters) GetSize() int32 { - if m != nil && m.Size != nil { - return *m.Size - } - return 0 -} - -func (m *ResponseParameters) GetIntervalUs() int32 { - if m != nil && m.IntervalUs != nil { - return *m.IntervalUs - } - return 0 -} - -// Server-streaming request. -type StreamingOutputCallRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Configuration for each expected response message. - ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters,json=responseParameters" json:"response_parameters,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus" json:"response_status,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} } -func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallRequest) ProtoMessage() {} -func (*StreamingOutputCallRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } - -func (m *StreamingOutputCallRequest) GetResponseType() PayloadType { - if m != nil && m.ResponseType != nil { - return *m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters { - if m != nil { - return m.ResponseParameters - } - return nil -} - -func (m *StreamingOutputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *StreamingOutputCallRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Server-streaming response, as configured by the request and parameters. -type StreamingOutputCallResponse struct { - // Payload to increase response size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} } -func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallResponse) ProtoMessage() {} -func (*StreamingOutputCallResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } - -func (m *StreamingOutputCallResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func init() { - proto.RegisterType((*Empty)(nil), "grpc.testing.Empty") - proto.RegisterType((*Payload)(nil), "grpc.testing.Payload") - proto.RegisterType((*EchoStatus)(nil), "grpc.testing.EchoStatus") - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") - proto.RegisterType((*StreamingInputCallRequest)(nil), "grpc.testing.StreamingInputCallRequest") - proto.RegisterType((*StreamingInputCallResponse)(nil), "grpc.testing.StreamingInputCallResponse") - proto.RegisterType((*ResponseParameters)(nil), "grpc.testing.ResponseParameters") - proto.RegisterType((*StreamingOutputCallRequest)(nil), "grpc.testing.StreamingOutputCallRequest") - proto.RegisterType((*StreamingOutputCallResponse)(nil), "grpc.testing.StreamingOutputCallResponse") - proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for TestService service - -type TestServiceClient interface { - // One empty request followed by one empty response. - EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) - // A sequence of requests followed by a sequence of responses. - // 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 - // first request. - HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) -} - -type testServiceClient struct { - cc *grpc.ClientConn -} - -func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient { - return &testServiceClient{cc} -} - -func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := grpc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := grpc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[0], c.cc, "/grpc.testing.TestService/StreamingOutputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingOutputCallClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type TestService_StreamingOutputCallClient interface { - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingOutputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[1], c.cc, "/grpc.testing.TestService/StreamingInputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingInputCallClient{stream} - return x, nil -} - -type TestService_StreamingInputCallClient interface { - Send(*StreamingInputCallRequest) error - CloseAndRecv() (*StreamingInputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingInputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingInputCallClient) Send(m *StreamingInputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCallResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(StreamingInputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[2], c.cc, "/grpc.testing.TestService/FullDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceFullDuplexCallClient{stream} - return x, nil -} - -type TestService_FullDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceFullDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceFullDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[3], c.cc, "/grpc.testing.TestService/HalfDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceHalfDuplexCallClient{stream} - return x, nil -} - -type TestService_HalfDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceHalfDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceHalfDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for TestService service - -type TestServiceServer interface { - // One empty request followed by one empty response. - EmptyCall(context.Context, *Empty) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(TestService_StreamingInputCallServer) error - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(TestService_FullDuplexCallServer) error - // A sequence of requests followed by a sequence of responses. - // 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 - // first request. - HalfDuplexCall(TestService_HalfDuplexCallServer) error -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).EmptyCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/EmptyCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(StreamingOutputCallRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) -} - -type TestService_StreamingOutputCallServer interface { - Send(*StreamingOutputCallResponse) error - grpc.ServerStream -} - -type testServiceStreamingOutputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallResponse) error { - 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 { - SendAndClose(*StreamingInputCallResponse) error - Recv() (*StreamingInputCallRequest, error) - grpc.ServerStream -} - -type testServiceStreamingInputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingInputCallServer) SendAndClose(m *StreamingInputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest, error) { - m := new(StreamingInputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} - -type TestService_FullDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceFullDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceFullDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) -} - -type TestService_HalfDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceHalfDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceHalfDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _TestService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - HandlerType: (*TestServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "EmptyCall", - Handler: _TestService_EmptyCall_Handler, - }, - { - MethodName: "UnaryCall", - Handler: _TestService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - 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: "grpc_testing/test.proto", -} - -// Client API for UnimplementedService service - -type UnimplementedServiceClient interface { - // A call that no server should implement - UnimplementedCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) -} - -type unimplementedServiceClient struct { - cc *grpc.ClientConn -} - -func NewUnimplementedServiceClient(cc *grpc.ClientConn) UnimplementedServiceClient { - return &unimplementedServiceClient{cc} -} - -func (c *unimplementedServiceClient) UnimplementedCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := grpc.Invoke(ctx, "/grpc.testing.UnimplementedService/UnimplementedCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for UnimplementedService service - -type UnimplementedServiceServer interface { - // A call that no server should implement - UnimplementedCall(context.Context, *Empty) (*Empty, error) -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.UnimplementedService/UnimplementedCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -var _UnimplementedService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.UnimplementedService", - HandlerType: (*UnimplementedServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UnimplementedCall", - Handler: _UnimplementedService_UnimplementedCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "grpc_testing/test.proto", -} - -func init() { proto.RegisterFile("grpc_testing/test.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 656 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0x4d, 0x6f, 0xd3, 0x40, - 0x10, 0xc5, 0x69, 0x42, 0xda, 0x49, 0x6a, 0xc2, 0x94, 0xaa, 0x6e, 0x8a, 0x44, 0x64, 0x0e, 0x18, - 0x24, 0x52, 0x14, 0x09, 0x0e, 0x48, 0x80, 0x4a, 0x9b, 0x8a, 0x4a, 0x6d, 0x53, 0xec, 0xe6, 0x1c, - 0x2d, 0xc9, 0xd4, 0xb5, 0xe4, 0x2f, 0xec, 0x75, 0x45, 0x7a, 0xe0, 0xcf, 0xf0, 0x23, 0x38, 0xf0, - 0xe7, 0xd0, 0xae, 0xed, 0xc4, 0x49, 0x53, 0xd1, 0xf2, 0x75, 0xca, 0xee, 0x9b, 0x37, 0xb3, 0xf3, - 0x66, 0x5e, 0x0c, 0x1b, 0x76, 0x14, 0x0e, 0x07, 0x9c, 0x62, 0xee, 0xf8, 0xf6, 0xb6, 0xf8, 0x6d, - 0x87, 0x51, 0xc0, 0x03, 0xac, 0x8b, 0x40, 0x3b, 0x0b, 0xe8, 0x55, 0xa8, 0x74, 0xbd, 0x90, 0x8f, - 0xf5, 0x43, 0xa8, 0x9e, 0xb0, 0xb1, 0x1b, 0xb0, 0x11, 0x3e, 0x87, 0x32, 0x1f, 0x87, 0xa4, 0x29, - 0x2d, 0xc5, 0x50, 0x3b, 0x9b, 0xed, 0x62, 0x42, 0x3b, 0x23, 0x9d, 0x8e, 0x43, 0x32, 0x25, 0x0d, - 0x11, 0xca, 0x9f, 0x82, 0xd1, 0x58, 0x2b, 0xb5, 0x14, 0xa3, 0x6e, 0xca, 0xb3, 0xfe, 0x1a, 0xa0, - 0x3b, 0x3c, 0x0f, 0x2c, 0xce, 0x78, 0x12, 0x0b, 0xc6, 0x30, 0x18, 0xa5, 0x05, 0x2b, 0xa6, 0x3c, - 0xa3, 0x06, 0x55, 0x8f, 0xe2, 0x98, 0xd9, 0x24, 0x13, 0x57, 0xcc, 0xfc, 0xaa, 0x7f, 0x2f, 0xc1, - 0xaa, 0xe5, 0x78, 0xa1, 0x4b, 0x26, 0x7d, 0x4e, 0x28, 0xe6, 0xf8, 0x16, 0x56, 0x23, 0x8a, 0xc3, - 0xc0, 0x8f, 0x69, 0x70, 0xb3, 0xce, 0xea, 0x39, 0x5f, 0xdc, 0xf0, 0x71, 0x21, 0x3f, 0x76, 0x2e, - 0xd3, 0x17, 0x2b, 0x53, 0x92, 0xe5, 0x5c, 0x12, 0x6e, 0x43, 0x35, 0x4c, 0x2b, 0x68, 0x4b, 0x2d, - 0xc5, 0xa8, 0x75, 0xd6, 0x17, 0x96, 0x37, 0x73, 0x96, 0xa8, 0x7a, 0xe6, 0xb8, 0xee, 0x20, 0x89, - 0x29, 0xf2, 0x99, 0x47, 0x5a, 0xb9, 0xa5, 0x18, 0xcb, 0x66, 0x5d, 0x80, 0xfd, 0x0c, 0x43, 0x03, - 0x1a, 0x92, 0x14, 0xb0, 0x84, 0x9f, 0x0f, 0xe2, 0x61, 0x10, 0x92, 0x56, 0x91, 0x3c, 0x55, 0xe0, - 0x3d, 0x01, 0x5b, 0x02, 0xc5, 0x1d, 0xb8, 0x37, 0x6d, 0x52, 0xce, 0x4d, 0xab, 0xca, 0x3e, 0xb4, - 0xd9, 0x3e, 0xa6, 0x73, 0x35, 0xd5, 0x89, 0x00, 0x79, 0xd7, 0xbf, 0x82, 0x9a, 0x0f, 0x2e, 0xc5, - 0x8b, 0xa2, 0x94, 0x1b, 0x89, 0x6a, 0xc2, 0xf2, 0x44, 0x4f, 0xba, 0x97, 0xc9, 0x1d, 0x1f, 0x41, - 0xad, 0x28, 0x63, 0x49, 0x86, 0x21, 0x98, 0x48, 0xd0, 0x0f, 0x61, 0xd3, 0xe2, 0x11, 0x31, 0xcf, - 0xf1, 0xed, 0x03, 0x3f, 0x4c, 0xf8, 0x2e, 0x73, 0xdd, 0x7c, 0x89, 0xb7, 0x6d, 0x45, 0x3f, 0x85, - 0xe6, 0xa2, 0x6a, 0x99, 0xb2, 0x57, 0xb0, 0xc1, 0x6c, 0x3b, 0x22, 0x9b, 0x71, 0x1a, 0x0d, 0xb2, - 0x9c, 0x74, 0xbb, 0xa9, 0xcd, 0xd6, 0xa7, 0xe1, 0xac, 0xb4, 0x58, 0xb3, 0x7e, 0x00, 0x98, 0xd7, - 0x38, 0x61, 0x11, 0xf3, 0x88, 0x53, 0x24, 0x1d, 0x5a, 0x48, 0x95, 0x67, 0x21, 0xd7, 0xf1, 0x39, - 0x45, 0x17, 0x4c, 0xec, 0x38, 0xf3, 0x0c, 0xe4, 0x50, 0x3f, 0xd6, 0xbf, 0x95, 0x0a, 0x1d, 0xf6, - 0x12, 0x3e, 0x27, 0xf8, 0x4f, 0x5d, 0xfb, 0x11, 0xd6, 0x26, 0xf9, 0xe1, 0xa4, 0x55, 0xad, 0xd4, - 0x5a, 0x32, 0x6a, 0x9d, 0xd6, 0x6c, 0x95, 0xab, 0x92, 0x4c, 0x8c, 0xae, 0xca, 0xbc, 0xb5, 0xc7, - 0xff, 0x82, 0x29, 0x8f, 0x61, 0x6b, 0xe1, 0x90, 0x7e, 0xd3, 0xa1, 0xcf, 0xde, 0x41, 0xad, 0x30, - 0x33, 0x6c, 0x40, 0x7d, 0xb7, 0x77, 0x74, 0x62, 0x76, 0x2d, 0x6b, 0xe7, 0xfd, 0x61, 0xb7, 0x71, - 0x07, 0x11, 0xd4, 0xfe, 0xf1, 0x0c, 0xa6, 0x20, 0xc0, 0x5d, 0x73, 0xe7, 0x78, 0xaf, 0x77, 0xd4, - 0x28, 0x75, 0x7e, 0x94, 0xa1, 0x76, 0x4a, 0x31, 0xb7, 0x28, 0xba, 0x70, 0x86, 0x84, 0x2f, 0x61, - 0x45, 0x7e, 0x02, 0x45, 0x5b, 0xb8, 0x36, 0xa7, 0x4b, 0x04, 0x9a, 0x8b, 0x40, 0xdc, 0x87, 0x95, - 0xbe, 0xcf, 0xa2, 0x34, 0x6d, 0x6b, 0x96, 0x31, 0xf3, 0xf9, 0x6a, 0x3e, 0x5c, 0x1c, 0xcc, 0x06, - 0xe0, 0xc2, 0xda, 0x82, 0xf9, 0xa0, 0x31, 0x97, 0x74, 0xad, 0xcf, 0x9a, 0x4f, 0x6f, 0xc0, 0x4c, - 0xdf, 0x7a, 0xa1, 0xa0, 0x03, 0x78, 0xf5, 0x4f, 0x85, 0x4f, 0xae, 0x29, 0x31, 0xff, 0x27, 0x6e, - 0x1a, 0xbf, 0x26, 0xa6, 0x4f, 0x19, 0xe2, 0x29, 0x75, 0x3f, 0x71, 0xdd, 0xbd, 0x24, 0x74, 0xe9, - 0xcb, 0x3f, 0xd3, 0x64, 0x28, 0x52, 0x95, 0xfa, 0x81, 0xb9, 0x67, 0xff, 0xe1, 0xa9, 0x4e, 0x1f, - 0x1e, 0xf4, 0x7d, 0xb9, 0x41, 0x8f, 0x7c, 0x4e, 0xa3, 0xdc, 0x45, 0x6f, 0xe0, 0xfe, 0x0c, 0x7e, - 0x3b, 0x37, 0xfd, 0x0c, 0x00, 0x00, 0xff, 0xff, 0x15, 0x62, 0x93, 0xba, 0xaf, 0x07, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/interop/grpc_testing/test.proto b/vendor/google.golang.org/grpc/interop/grpc_testing/test.proto deleted file mode 100644 index 20d4366b0..000000000 --- a/vendor/google.golang.org/grpc/interop/grpc_testing/test.proto +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An integration test service that covers all the method signature permutations -// of unary/streaming requests/responses. -syntax = "proto2"; - -package grpc.testing; - -message Empty {} - -// The type of payload that should be returned. -enum PayloadType { - // Compressable text format. - COMPRESSABLE = 0; - - // Uncompressable binary format. - UNCOMPRESSABLE = 1; - - // Randomly chosen from all other formats defined in this enum. - RANDOM = 2; -} - -// A block of data, to simply increase gRPC message size. -message Payload { - // The type of data in body. - optional PayloadType type = 1; - // Primary contents of payload. - optional bytes body = 2; -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -message EchoStatus { - optional int32 code = 1; - optional string message = 2; -} - -// Unary request. -message SimpleRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - optional PayloadType response_type = 1; - - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - optional int32 response_size = 2; - - // Optional input payload sent along with the request. - optional Payload payload = 3; - - // Whether SimpleResponse should include username. - optional bool fill_username = 4; - - // Whether SimpleResponse should include OAuth scope. - optional bool fill_oauth_scope = 5; - - // Whether server should return a given status - optional EchoStatus response_status = 7; -} - -// Unary response, as configured by the request. -message SimpleResponse { - // Payload to increase message size. - optional Payload payload = 1; - - // The user the request came from, for verifying authentication was - // successful when the client expected it. - optional string username = 2; - - // OAuth scope. - optional string oauth_scope = 3; -} - -// Client-streaming request. -message StreamingInputCallRequest { - // Optional input payload sent along with the request. - optional Payload payload = 1; - - // Not expecting any payload from the response. -} - -// Client-streaming response. -message StreamingInputCallResponse { - // Aggregated size of payloads received from the client. - optional int32 aggregated_payload_size = 1; -} - -// Configuration for a particular response. -message ResponseParameters { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - optional int32 size = 1; - - // Desired interval between consecutive responses in the response stream in - // microseconds. - optional int32 interval_us = 2; -} - -// Server-streaming request. -message StreamingOutputCallRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - optional PayloadType response_type = 1; - - // Configuration for each expected response message. - repeated ResponseParameters response_parameters = 2; - - // Optional input payload sent along with the request. - optional Payload payload = 3; - - // Whether server should return a given status - optional EchoStatus response_status = 7; -} - -// Server-streaming response, as configured by the request and parameters. -message StreamingOutputCallResponse { - // Payload to increase response size. - optional Payload payload = 1; -} - -// A simple service to test the various types of RPCs and experiment with -// performance with various types of payload. -service TestService { - // One empty request followed by one empty response. - rpc EmptyCall(Empty) returns (Empty); - - // One request followed by one response. - // The server returns the client payload as-is. - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - rpc StreamingOutputCall(StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - rpc StreamingInputCall(stream StreamingInputCallRequest) - returns (StreamingInputCallResponse); - - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - rpc FullDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by a sequence of responses. - // 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 - // first request. - rpc HalfDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); -} - -// A simple service NOT implemented at servers so clients can test for -// that case. -service UnimplementedService { - // A call that no server should implement - rpc UnimplementedCall(grpc.testing.Empty) returns (grpc.testing.Empty); -} diff --git a/vendor/google.golang.org/grpc/interop/http2/negative_http2_client.go b/vendor/google.golang.org/grpc/interop/http2/negative_http2_client.go deleted file mode 100644 index 5b42b76a9..000000000 --- a/vendor/google.golang.org/grpc/interop/http2/negative_http2_client.go +++ /dev/null @@ -1,159 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * - * Client used to test http2 error edge cases like GOAWAYs and RST_STREAMs - * - * Documentation: - * https://github.com/grpc/grpc/blob/master/doc/negative-http2-interop-test-descriptions.md - */ - -package main - -import ( - "flag" - "net" - "strconv" - "sync" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" -) - -var ( - serverHost = flag.String("server_host", "127.0.0.1", "The server host name") - serverPort = flag.Int("server_port", 8080, "The server port number") - testCase = flag.String("test_case", "goaway", - `Configure different test cases. Valid options are: - goaway : client sends two requests, the server will send a goaway in between; - rst_after_header : server will send rst_stream after it sends headers; - rst_during_data : server will send rst_stream while sending data; - rst_after_data : server will send rst_stream after sending data; - ping : server will send pings between each http2 frame; - max_streams : server will ensure that the max_concurrent_streams limit is upheld;`) - largeReqSize = 271828 - largeRespSize = 314159 -) - -func largeSimpleRequest() *testpb.SimpleRequest { - pl := interop.ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - return &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeRespSize)), - Payload: pl, - } -} - -// sends two unary calls. The server asserts that the calls use different connections. -func goaway(tc testpb.TestServiceClient) { - interop.DoLargeUnaryCall(tc) - // sleep to ensure that the client has time to recv the GOAWAY. - // TODO(ncteisen): make this less hacky. - time.Sleep(1 * time.Second) - interop.DoLargeUnaryCall(tc) -} - -func rstAfterHeader(tc testpb.TestServiceClient) { - req := largeSimpleRequest() - reply, err := tc.UnaryCall(context.Background(), req) - if reply != nil { - grpclog.Fatalf("Client received reply despite server sending rst stream after header") - } - if grpc.Code(err) != codes.Internal { - grpclog.Fatalf("%v.UnaryCall() = _, %v, want _, %v", tc, grpc.Code(err), codes.Internal) - } -} - -func rstDuringData(tc testpb.TestServiceClient) { - req := largeSimpleRequest() - reply, err := tc.UnaryCall(context.Background(), req) - if reply != nil { - grpclog.Fatalf("Client received reply despite server sending rst stream during data") - } - if grpc.Code(err) != codes.Unknown { - grpclog.Fatalf("%v.UnaryCall() = _, %v, want _, %v", tc, grpc.Code(err), codes.Unknown) - } -} - -func rstAfterData(tc testpb.TestServiceClient) { - req := largeSimpleRequest() - reply, err := tc.UnaryCall(context.Background(), req) - if reply != nil { - grpclog.Fatalf("Client received reply despite server sending rst stream after data") - } - if grpc.Code(err) != codes.Internal { - grpclog.Fatalf("%v.UnaryCall() = _, %v, want _, %v", tc, grpc.Code(err), codes.Internal) - } -} - -func ping(tc testpb.TestServiceClient) { - // The server will assert that every ping it sends was ACK-ed by the client. - interop.DoLargeUnaryCall(tc) -} - -func maxStreams(tc testpb.TestServiceClient) { - interop.DoLargeUnaryCall(tc) - var wg sync.WaitGroup - for i := 0; i < 15; i++ { - wg.Add(1) - go func() { - defer wg.Done() - interop.DoLargeUnaryCall(tc) - }() - } - wg.Wait() -} - -func main() { - flag.Parse() - serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort)) - var opts []grpc.DialOption - opts = append(opts, grpc.WithInsecure()) - conn, err := grpc.Dial(serverAddr, opts...) - if err != nil { - grpclog.Fatalf("Fail to dial: %v", err) - } - defer conn.Close() - tc := testpb.NewTestServiceClient(conn) - switch *testCase { - case "goaway": - goaway(tc) - grpclog.Println("goaway done") - case "rst_after_header": - rstAfterHeader(tc) - grpclog.Println("rst_after_header done") - case "rst_during_data": - rstDuringData(tc) - grpclog.Println("rst_during_data done") - case "rst_after_data": - rstAfterData(tc) - grpclog.Println("rst_after_data done") - case "ping": - ping(tc) - grpclog.Println("ping done") - case "max_streams": - maxStreams(tc) - grpclog.Println("max_streams done") - default: - grpclog.Fatal("Unsupported test case: ", *testCase) - } -} diff --git a/vendor/google.golang.org/grpc/interop/server/server.go b/vendor/google.golang.org/grpc/interop/server/server.go deleted file mode 100644 index b833c76f6..000000000 --- a/vendor/google.golang.org/grpc/interop/server/server.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "net" - "strconv" - - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/testdata" -) - -var ( - useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP") - certFile = flag.String("tls_cert_file", "", "The TLS cert file") - keyFile = flag.String("tls_key_file", "", "The TLS key file") - port = flag.Int("port", 10000, "The server port") -) - -func main() { - flag.Parse() - p := strconv.Itoa(*port) - lis, err := net.Listen("tcp", ":"+p) - if err != nil { - grpclog.Fatalf("failed to listen: %v", err) - } - var opts []grpc.ServerOption - if *useTLS { - if *certFile == "" { - *certFile = testdata.Path("server1.pem") - } - if *keyFile == "" { - *keyFile = testdata.Path("server1.key") - } - creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) - if err != nil { - grpclog.Fatalf("Failed to generate credentials %v", err) - } - opts = []grpc.ServerOption{grpc.Creds(creds)} - } - server := grpc.NewServer(opts...) - testpb.RegisterTestServiceServer(server, interop.NewTestServer()) - server.Serve(lis) -} diff --git a/vendor/google.golang.org/grpc/interop/test_utils.go b/vendor/google.golang.org/grpc/interop/test_utils.go deleted file mode 100644 index 36285d362..000000000 --- a/vendor/google.golang.org/grpc/interop/test_utils.go +++ /dev/null @@ -1,748 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto - -package interop - -import ( - "fmt" - "io" - "io/ioutil" - "strings" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/metadata" -) - -var ( - reqSizes = []int{27182, 8, 1828, 45904} - respSizes = []int{31415, 9, 2653, 58979} - largeReqSize = 271828 - largeRespSize = 314159 - initialMetadataKey = "x-grpc-test-echo-initial" - trailingMetadataKey = "x-grpc-test-echo-trailing-bin" -) - -// ClientNewPayload returns a payload of the given type and size. -func ClientNewPayload(t testpb.PayloadType, size int) *testpb.Payload { - if size < 0 { - grpclog.Fatalf("Requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - grpclog.Fatalf("PayloadType UNCOMPRESSABLE is not supported") - default: - grpclog.Fatalf("Unsupported payload type: %d", t) - } - return &testpb.Payload{ - Type: t.Enum(), - Body: body, - } -} - -// DoEmptyUnaryCall performs a unary RPC with empty request and response messages. -func DoEmptyUnaryCall(tc testpb.TestServiceClient, args ...grpc.CallOption) { - reply, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, args...) - if err != nil { - grpclog.Fatal("/TestService/EmptyCall RPC failed: ", err) - } - if !proto.Equal(&testpb.Empty{}, reply) { - grpclog.Fatalf("/TestService/EmptyCall receives %v, want %v", reply, testpb.Empty{}) - } -} - -// DoLargeUnaryCall performs a unary RPC with large payload in the request and response. -func DoLargeUnaryCall(tc testpb.TestServiceClient, args ...grpc.CallOption) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeRespSize)), - Payload: pl, - } - reply, err := tc.UnaryCall(context.Background(), req, args...) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - t := reply.GetPayload().GetType() - s := len(reply.GetPayload().GetBody()) - if t != testpb.PayloadType_COMPRESSABLE || s != largeRespSize { - grpclog.Fatalf("Got the reply with type %d len %d; want %d, %d", t, s, testpb.PayloadType_COMPRESSABLE, largeRespSize) - } -} - -// DoClientStreaming performs a client streaming RPC. -func DoClientStreaming(tc testpb.TestServiceClient, args ...grpc.CallOption) { - stream, err := tc.StreamingInputCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err) - } - var sum int - for _, s := range reqSizes { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, s) - req := &testpb.StreamingInputCallRequest{ - Payload: pl, - } - if err := stream.Send(req); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, req) - } - sum += s - } - reply, err := stream.CloseAndRecv() - if err != nil { - grpclog.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) - } - if reply.GetAggregatedPayloadSize() != int32(sum) { - grpclog.Fatalf("%v.CloseAndRecv().GetAggregatePayloadSize() = %v; want %v", stream, reply.GetAggregatedPayloadSize(), sum) - } -} - -// DoServerStreaming performs a server streaming RPC. -func DoServerStreaming(tc testpb.TestServiceClient, args ...grpc.CallOption) { - respParam := make([]*testpb.ResponseParameters, len(respSizes)) - for i, s := range respSizes { - respParam[i] = &testpb.ResponseParameters{ - Size: proto.Int32(int32(s)), - } - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - } - stream, err := tc.StreamingOutputCall(context.Background(), req, args...) - if err != nil { - grpclog.Fatalf("%v.StreamingOutputCall(_) = _, %v", tc, err) - } - var rpcStatus error - var respCnt int - var index int - for { - reply, err := stream.Recv() - if err != nil { - rpcStatus = err - break - } - t := reply.GetPayload().GetType() - if t != testpb.PayloadType_COMPRESSABLE { - grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != int(respSizes[index]) { - grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - respCnt++ - } - if rpcStatus != io.EOF { - grpclog.Fatalf("Failed to finish the server streaming rpc: %v", rpcStatus) - } - if respCnt != len(respSizes) { - grpclog.Fatalf("Got %d reply, want %d", len(respSizes), respCnt) - } -} - -// DoPingPong performs ping-pong style bi-directional streaming RPC. -func DoPingPong(tc testpb.TestServiceClient, args ...grpc.CallOption) { - stream, err := tc.FullDuplexCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - var index int - for index < len(reqSizes) { - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(respSizes[index])), - }, - } - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, reqSizes[index]) - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: pl, - } - if err := stream.Send(req); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, req) - } - reply, err := stream.Recv() - if err != nil { - grpclog.Fatalf("%v.Recv() = %v", stream, err) - } - t := reply.GetPayload().GetType() - if t != testpb.PayloadType_COMPRESSABLE { - grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != int(respSizes[index]) { - grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - grpclog.Fatalf("%v failed to complele the ping pong test: %v", stream, err) - } -} - -// DoEmptyStream sets up a bi-directional streaming with zero message. -func DoEmptyStream(tc testpb.TestServiceClient, args ...grpc.CallOption) { - stream, err := tc.FullDuplexCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - grpclog.Fatalf("%v failed to complete the empty stream test: %v", stream, err) - } -} - -// DoTimeoutOnSleepingServer performs an RPC on a sleep server which causes RPC timeout. -func DoTimeoutOnSleepingServer(tc testpb.TestServiceClient, args ...grpc.CallOption) { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) - defer cancel() - stream, err := tc.FullDuplexCall(ctx, args...) - if err != nil { - if grpc.Code(err) == codes.DeadlineExceeded { - return - } - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, 27182) - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - Payload: pl, - } - if err := stream.Send(req); err != nil { - if grpc.Code(err) != codes.DeadlineExceeded { - grpclog.Fatalf("%v.Send(_) = %v", stream, err) - } - } - if _, err := stream.Recv(); grpc.Code(err) != codes.DeadlineExceeded { - grpclog.Fatalf("%v.Recv() = _, %v, want error code %d", stream, err, codes.DeadlineExceeded) - } -} - -// DoComputeEngineCreds performs a unary RPC with compute engine auth. -func DoComputeEngineCreds(tc testpb.TestServiceClient, serviceAccount, oauthScope string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeRespSize)), - Payload: pl, - FillUsername: proto.Bool(true), - FillOauthScope: proto.Bool(true), - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - user := reply.GetUsername() - scope := reply.GetOauthScope() - if user != serviceAccount { - grpclog.Fatalf("Got user name %q, want %q.", user, serviceAccount) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -func getServiceAccountJSONKey(keyFile string) []byte { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - grpclog.Fatalf("Failed to read the service account key file: %v", err) - } - return jsonKey -} - -// DoServiceAccountCreds performs a unary RPC with service account auth. -func DoServiceAccountCreds(tc testpb.TestServiceClient, serviceAccountKeyFile, oauthScope string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeRespSize)), - Payload: pl, - FillUsername: proto.Bool(true), - FillOauthScope: proto.Bool(true), - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - user := reply.GetUsername() - scope := reply.GetOauthScope() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -// DoJWTTokenCreds performs a unary RPC with JWT token auth. -func DoJWTTokenCreds(tc testpb.TestServiceClient, serviceAccountKeyFile string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeRespSize)), - Payload: pl, - FillUsername: proto.Bool(true), - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - user := reply.GetUsername() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } -} - -// GetToken obtains an OAUTH token from the input. -func GetToken(serviceAccountKeyFile string, oauthScope string) *oauth2.Token { - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - config, err := google.JWTConfigFromJSON(jsonKey, oauthScope) - if err != nil { - grpclog.Fatalf("Failed to get the config: %v", err) - } - token, err := config.TokenSource(context.Background()).Token() - if err != nil { - grpclog.Fatalf("Failed to get the token: %v", err) - } - return token -} - -// DoOauth2TokenCreds performs a unary RPC with OAUTH2 token auth. -func DoOauth2TokenCreds(tc testpb.TestServiceClient, serviceAccountKeyFile, oauthScope string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeRespSize)), - Payload: pl, - FillUsername: proto.Bool(true), - FillOauthScope: proto.Bool(true), - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - user := reply.GetUsername() - scope := reply.GetOauthScope() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -// DoPerRPCCreds performs a unary RPC with per RPC OAUTH2 token. -func DoPerRPCCreds(tc testpb.TestServiceClient, serviceAccountKeyFile, oauthScope string) { - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeRespSize)), - Payload: pl, - FillUsername: proto.Bool(true), - FillOauthScope: proto.Bool(true), - } - token := GetToken(serviceAccountKeyFile, oauthScope) - kv := map[string]string{"authorization": token.Type() + " " + token.AccessToken} - ctx := metadata.NewOutgoingContext(context.Background(), metadata.MD{"authorization": []string{kv["authorization"]}}) - reply, err := tc.UnaryCall(ctx, req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - user := reply.GetUsername() - scope := reply.GetOauthScope() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -var ( - testMetadata = metadata.MD{ - "key1": []string{"value1"}, - "key2": []string{"value2"}, - } -) - -// DoCancelAfterBegin cancels the RPC after metadata has been sent but before payloads are sent. -func DoCancelAfterBegin(tc testpb.TestServiceClient, args ...grpc.CallOption) { - ctx, cancel := context.WithCancel(metadata.NewOutgoingContext(context.Background(), testMetadata)) - stream, err := tc.StreamingInputCall(ctx, args...) - if err != nil { - grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err) - } - cancel() - _, err = stream.CloseAndRecv() - if grpc.Code(err) != codes.Canceled { - grpclog.Fatalf("%v.CloseAndRecv() got error code %d, want %d", stream, grpc.Code(err), codes.Canceled) - } -} - -// DoCancelAfterFirstResponse cancels the RPC after receiving the first message from the server. -func DoCancelAfterFirstResponse(tc testpb.TestServiceClient, args ...grpc.CallOption) { - ctx, cancel := context.WithCancel(context.Background()) - stream, err := tc.FullDuplexCall(ctx, args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(31415), - }, - } - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, 27182) - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: pl, - } - if err := stream.Send(req); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, req) - } - if _, err := stream.Recv(); err != nil { - grpclog.Fatalf("%v.Recv() = %v", stream, err) - } - cancel() - if _, err := stream.Recv(); grpc.Code(err) != codes.Canceled { - grpclog.Fatalf("%v compleled with error code %d, want %d", stream, grpc.Code(err), codes.Canceled) - } -} - -var ( - initialMetadataValue = "test_initial_metadata_value" - trailingMetadataValue = "\x0a\x0b\x0a\x0b\x0a\x0b" - customMetadata = metadata.Pairs( - initialMetadataKey, initialMetadataValue, - trailingMetadataKey, trailingMetadataValue, - ) -) - -func validateMetadata(header, trailer metadata.MD) { - if len(header[initialMetadataKey]) != 1 { - grpclog.Fatalf("Expected exactly one header from server. Received %d", len(header[initialMetadataKey])) - } - if header[initialMetadataKey][0] != initialMetadataValue { - grpclog.Fatalf("Got header %s; want %s", header[initialMetadataKey][0], initialMetadataValue) - } - if len(trailer[trailingMetadataKey]) != 1 { - grpclog.Fatalf("Expected exactly one trailer from server. Received %d", len(trailer[trailingMetadataKey])) - } - if trailer[trailingMetadataKey][0] != trailingMetadataValue { - grpclog.Fatalf("Got trailer %s; want %s", trailer[trailingMetadataKey][0], trailingMetadataValue) - } -} - -// DoCustomMetadata checks that metadata is echoed back to the client. -func DoCustomMetadata(tc testpb.TestServiceClient, args ...grpc.CallOption) { - // Testing with UnaryCall. - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, 1) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(1)), - Payload: pl, - } - ctx := metadata.NewOutgoingContext(context.Background(), customMetadata) - var header, trailer metadata.MD - args = append(args, grpc.Header(&header), grpc.Trailer(&trailer)) - reply, err := tc.UnaryCall( - ctx, - req, - args..., - ) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - t := reply.GetPayload().GetType() - s := len(reply.GetPayload().GetBody()) - if t != testpb.PayloadType_COMPRESSABLE || s != 1 { - grpclog.Fatalf("Got the reply with type %d len %d; want %d, %d", t, s, testpb.PayloadType_COMPRESSABLE, 1) - } - validateMetadata(header, trailer) - - // Testing with FullDuplex. - stream, err := tc.FullDuplexCall(ctx, args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(1), - }, - } - streamReq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: pl, - } - if err := stream.Send(streamReq); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, streamReq) - } - streamHeader, err := stream.Header() - if err != nil { - grpclog.Fatalf("%v.Header() = %v", stream, err) - } - if _, err := stream.Recv(); err != nil { - grpclog.Fatalf("%v.Recv() = %v", stream, err) - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() = %v, want <nil>", stream, err) - } - if _, err := stream.Recv(); err != io.EOF { - grpclog.Fatalf("%v failed to complete the custom metadata test: %v", stream, err) - } - streamTrailer := stream.Trailer() - validateMetadata(streamHeader, streamTrailer) -} - -// DoStatusCodeAndMessage checks that the status code is propagated back to the client. -func DoStatusCodeAndMessage(tc testpb.TestServiceClient, args ...grpc.CallOption) { - var code int32 = 2 - msg := "test status message" - expectedErr := grpc.Errorf(codes.Code(code), msg) - respStatus := &testpb.EchoStatus{ - Code: proto.Int32(code), - Message: proto.String(msg), - } - // Test UnaryCall. - req := &testpb.SimpleRequest{ - ResponseStatus: respStatus, - } - if _, err := tc.UnaryCall(context.Background(), req, args...); err == nil || err.Error() != expectedErr.Error() { - grpclog.Fatalf("%v.UnaryCall(_, %v) = _, %v, want _, %v", tc, req, err, expectedErr) - } - // Test FullDuplexCall. - stream, err := tc.FullDuplexCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - streamReq := &testpb.StreamingOutputCallRequest{ - ResponseStatus: respStatus, - } - if err := stream.Send(streamReq); err != nil { - grpclog.Fatalf("%v has error %v while sending %v, want <nil>", stream, err, streamReq) - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() = %v, want <nil>", stream, err) - } - if _, err = stream.Recv(); err.Error() != expectedErr.Error() { - grpclog.Fatalf("%v.Recv() returned error %v, want %v", stream, err, expectedErr) - } -} - -// DoUnimplementedService attempts to call a method from an unimplemented service. -func DoUnimplementedService(tc testpb.UnimplementedServiceClient) { - _, err := tc.UnimplementedCall(context.Background(), &testpb.Empty{}) - if grpc.Code(err) != codes.Unimplemented { - grpclog.Fatalf("%v.UnimplementedCall() = _, %v, want _, %v", tc, grpc.Code(err), codes.Unimplemented) - } -} - -// DoUnimplementedMethod attempts to call an unimplemented method. -func DoUnimplementedMethod(cc *grpc.ClientConn) { - var req, reply proto.Message - if err := grpc.Invoke(context.Background(), "/grpc.testing.TestService/UnimplementedCall", req, reply, cc); err == nil || grpc.Code(err) != codes.Unimplemented { - grpclog.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want error code %s", err, codes.Unimplemented) - } -} - -type testServer struct { -} - -// NewTestServer creates a test server for test service. -func NewTestServer() testpb.TestServiceServer { - return &testServer{} -} - -func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - return new(testpb.Empty), nil -} - -func serverNewPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) { - if size < 0 { - return nil, fmt.Errorf("requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - return nil, fmt.Errorf("payloadType UNCOMPRESSABLE is not supported") - default: - return nil, fmt.Errorf("unsupported payload type: %d", t) - } - return &testpb.Payload{ - Type: t.Enum(), - Body: body, - }, nil -} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - status := in.GetResponseStatus() - if md, ok := metadata.FromIncomingContext(ctx); ok { - if initialMetadata, ok := md[initialMetadataKey]; ok { - header := metadata.Pairs(initialMetadataKey, initialMetadata[0]) - grpc.SendHeader(ctx, header) - } - if trailingMetadata, ok := md[trailingMetadataKey]; ok { - trailer := metadata.Pairs(trailingMetadataKey, trailingMetadata[0]) - grpc.SetTrailer(ctx, trailer) - } - } - if status != nil && *status.Code != 0 { - return nil, grpc.Errorf(codes.Code(*status.Code), *status.Message) - } - pl, err := serverNewPayload(in.GetResponseType(), in.GetResponseSize()) - if err != nil { - return nil, err - } - return &testpb.SimpleResponse{ - Payload: pl, - }, nil -} - -func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { - cs := args.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - pl, err := serverNewPayload(args.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: pl, - }); err != nil { - return err - } - } - return nil -} - -func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { - var sum int - for { - in, err := stream.Recv() - if err == io.EOF { - return stream.SendAndClose(&testpb.StreamingInputCallResponse{ - AggregatedPayloadSize: proto.Int32(int32(sum)), - }) - } - if err != nil { - return err - } - p := in.GetPayload().GetBody() - sum += len(p) - } -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - if md, ok := metadata.FromIncomingContext(stream.Context()); ok { - if initialMetadata, ok := md[initialMetadataKey]; ok { - header := metadata.Pairs(initialMetadataKey, initialMetadata[0]) - stream.SendHeader(header) - } - if trailingMetadata, ok := md[trailingMetadataKey]; ok { - trailer := metadata.Pairs(trailingMetadataKey, trailingMetadata[0]) - stream.SetTrailer(trailer) - } - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return nil - } - if err != nil { - return err - } - status := in.GetResponseStatus() - if status != nil && *status.Code != 0 { - return grpc.Errorf(codes.Code(*status.Code), *status.Message) - } - cs := in.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - pl, err := serverNewPayload(in.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: pl, - }); err != nil { - return err - } - } - } -} - -func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error { - var msgBuf []*testpb.StreamingOutputCallRequest - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - break - } - if err != nil { - return err - } - msgBuf = append(msgBuf, in) - } - for _, m := range msgBuf { - cs := m.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - pl, err := serverNewPayload(m.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: pl, - }); err != nil { - return err - } - } - } - return nil -} diff --git a/vendor/google.golang.org/grpc/naming/go17.go b/vendor/google.golang.org/grpc/naming/go17.go index 8bdf21e79..a537b08c6 100644 --- a/vendor/google.golang.org/grpc/naming/go17.go +++ b/vendor/google.golang.org/grpc/naming/go17.go @@ -1,4 +1,4 @@ -// +build go1.7, !go1.8 +// +build go1.6, !go1.8 /* * diff --git a/vendor/google.golang.org/grpc/naming/go17_test.go b/vendor/google.golang.org/grpc/naming/go17_test.go index d1de221a5..db39b9ab7 100644 --- a/vendor/google.golang.org/grpc/naming/go17_test.go +++ b/vendor/google.golang.org/grpc/naming/go17_test.go @@ -1,4 +1,4 @@ -// +build go1.7, !go1.8 +// +build go1.6, !go1.8 /* * diff --git a/vendor/google.golang.org/grpc/picker_wrapper_test.go b/vendor/google.golang.org/grpc/picker_wrapper_test.go index 23bc8f243..37dffa9e9 100644 --- a/vendor/google.golang.org/grpc/picker_wrapper_test.go +++ b/vendor/google.golang.org/grpc/picker_wrapper_test.go @@ -100,7 +100,7 @@ func TestBlockingPickNoSubAvailable(t *testing.T) { bp := newPickerWrapper() var finishedCount uint64 bp.updatePicker(&testingPicker{err: balancer.ErrNoSubConnAvailable, maxCalled: goroutineCount}) - // All goroutines should block because picker returns no sc avilable. + // All goroutines should block because picker returns no sc available. for i := goroutineCount; i > 0; i-- { go func() { if tr, _, err := bp.pick(context.Background(), true, balancer.PickOptions{}); err != nil || tr != testT { diff --git a/vendor/google.golang.org/grpc/pickfirst.go b/vendor/google.golang.org/grpc/pickfirst.go index 7f993ef5a..e83ca2b0d 100644 --- a/vendor/google.golang.org/grpc/pickfirst.go +++ b/vendor/google.golang.org/grpc/pickfirst.go @@ -37,7 +37,7 @@ func (*pickfirstBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions } func (*pickfirstBuilder) Name() string { - return "pickfirst" + return "pick_first" } type pickfirstBalancer struct { @@ -57,14 +57,20 @@ func (b *pickfirstBalancer) HandleResolvedAddrs(addrs []resolver.Address, err er return } b.cc.UpdateBalancerState(connectivity.Idle, &picker{sc: b.sc}) + b.sc.Connect() } else { b.sc.UpdateAddresses(addrs) + b.sc.Connect() } } func (b *pickfirstBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { grpclog.Infof("pickfirstBalancer: HandleSubConnStateChange: %p, %v", sc, s) - if b.sc != sc || s == connectivity.Shutdown { + if b.sc != sc { + grpclog.Infof("pickfirstBalancer: ignored state change because sc is not recognized") + return + } + if s == connectivity.Shutdown { b.sc = nil return } @@ -93,3 +99,7 @@ func (p *picker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer. } return p.sc, nil, nil } + +func init() { + balancer.Register(newPickfirstBuilder()) +} diff --git a/vendor/google.golang.org/grpc/proxy.go b/vendor/google.golang.org/grpc/proxy.go index 3e17efec6..2d40236e2 100644 --- a/vendor/google.golang.org/grpc/proxy.go +++ b/vendor/google.golang.org/grpc/proxy.go @@ -82,8 +82,7 @@ func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, addr string) (_ Header: map[string][]string{"User-Agent": {grpcUA}}, }) - req = req.WithContext(ctx) - if err := req.Write(conn); err != nil { + if err := sendHTTPRequest(ctx, req, conn); err != nil { return nil, fmt.Errorf("failed to write the HTTP request: %v", err) } diff --git a/vendor/google.golang.org/grpc/reflection/README.md b/vendor/google.golang.org/grpc/reflection/README.md deleted file mode 100644 index 04b6371af..000000000 --- a/vendor/google.golang.org/grpc/reflection/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Reflection - -Package reflection implements server reflection service. - -The service implemented is defined in: https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. - -To register server reflection on a gRPC server: -```go -import "google.golang.org/grpc/reflection" - -s := grpc.NewServer() -pb.RegisterYourOwnServer(s, &server{}) - -// Register reflection service on gRPC server. -reflection.Register(s) - -s.Serve(lis) -``` diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go deleted file mode 100644 index b40725327..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go +++ /dev/null @@ -1,763 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_reflection_v1alpha/reflection.proto - -/* -Package grpc_reflection_v1alpha is a generated protocol buffer package. - -It is generated from these files: - grpc_reflection_v1alpha/reflection.proto - -It has these top-level messages: - ServerReflectionRequest - ExtensionRequest - ServerReflectionResponse - FileDescriptorResponse - ExtensionNumberResponse - ListServiceResponse - ServiceResponse - ErrorResponse -*/ -package grpc_reflection_v1alpha - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The message sent by the client when calling ServerReflectionInfo method. -type ServerReflectionRequest struct { - Host string `protobuf:"bytes,1,opt,name=host" json:"host,omitempty"` - // To use reflection service, the client should set one of the following - // fields in message_request. The server distinguishes requests by their - // defined field and then handles them using corresponding methods. - // - // Types that are valid to be assigned to MessageRequest: - // *ServerReflectionRequest_FileByFilename - // *ServerReflectionRequest_FileContainingSymbol - // *ServerReflectionRequest_FileContainingExtension - // *ServerReflectionRequest_AllExtensionNumbersOfType - // *ServerReflectionRequest_ListServices - MessageRequest isServerReflectionRequest_MessageRequest `protobuf_oneof:"message_request"` -} - -func (m *ServerReflectionRequest) Reset() { *m = ServerReflectionRequest{} } -func (m *ServerReflectionRequest) String() string { return proto.CompactTextString(m) } -func (*ServerReflectionRequest) ProtoMessage() {} -func (*ServerReflectionRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -type isServerReflectionRequest_MessageRequest interface { - isServerReflectionRequest_MessageRequest() -} - -type ServerReflectionRequest_FileByFilename struct { - FileByFilename string `protobuf:"bytes,3,opt,name=file_by_filename,json=fileByFilename,oneof"` -} -type ServerReflectionRequest_FileContainingSymbol struct { - FileContainingSymbol string `protobuf:"bytes,4,opt,name=file_containing_symbol,json=fileContainingSymbol,oneof"` -} -type ServerReflectionRequest_FileContainingExtension struct { - FileContainingExtension *ExtensionRequest `protobuf:"bytes,5,opt,name=file_containing_extension,json=fileContainingExtension,oneof"` -} -type ServerReflectionRequest_AllExtensionNumbersOfType struct { - AllExtensionNumbersOfType string `protobuf:"bytes,6,opt,name=all_extension_numbers_of_type,json=allExtensionNumbersOfType,oneof"` -} -type ServerReflectionRequest_ListServices struct { - ListServices string `protobuf:"bytes,7,opt,name=list_services,json=listServices,oneof"` -} - -func (*ServerReflectionRequest_FileByFilename) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_FileContainingSymbol) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_FileContainingExtension) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_AllExtensionNumbersOfType) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_ListServices) isServerReflectionRequest_MessageRequest() {} - -func (m *ServerReflectionRequest) GetMessageRequest() isServerReflectionRequest_MessageRequest { - if m != nil { - return m.MessageRequest - } - return nil -} - -func (m *ServerReflectionRequest) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *ServerReflectionRequest) GetFileByFilename() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileByFilename); ok { - return x.FileByFilename - } - return "" -} - -func (m *ServerReflectionRequest) GetFileContainingSymbol() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingSymbol); ok { - return x.FileContainingSymbol - } - return "" -} - -func (m *ServerReflectionRequest) GetFileContainingExtension() *ExtensionRequest { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingExtension); ok { - return x.FileContainingExtension - } - return nil -} - -func (m *ServerReflectionRequest) GetAllExtensionNumbersOfType() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_AllExtensionNumbersOfType); ok { - return x.AllExtensionNumbersOfType - } - return "" -} - -func (m *ServerReflectionRequest) GetListServices() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_ListServices); ok { - return x.ListServices - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerReflectionRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerReflectionRequest_OneofMarshaler, _ServerReflectionRequest_OneofUnmarshaler, _ServerReflectionRequest_OneofSizer, []interface{}{ - (*ServerReflectionRequest_FileByFilename)(nil), - (*ServerReflectionRequest_FileContainingSymbol)(nil), - (*ServerReflectionRequest_FileContainingExtension)(nil), - (*ServerReflectionRequest_AllExtensionNumbersOfType)(nil), - (*ServerReflectionRequest_ListServices)(nil), - } -} - -func _ServerReflectionRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerReflectionRequest) - // message_request - switch x := m.MessageRequest.(type) { - case *ServerReflectionRequest_FileByFilename: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.FileByFilename) - case *ServerReflectionRequest_FileContainingSymbol: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.FileContainingSymbol) - case *ServerReflectionRequest_FileContainingExtension: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.FileContainingExtension); err != nil { - return err - } - case *ServerReflectionRequest_AllExtensionNumbersOfType: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.AllExtensionNumbersOfType) - case *ServerReflectionRequest_ListServices: - b.EncodeVarint(7<<3 | proto.WireBytes) - b.EncodeStringBytes(x.ListServices) - case nil: - default: - return fmt.Errorf("ServerReflectionRequest.MessageRequest has unexpected type %T", x) - } - return nil -} - -func _ServerReflectionRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerReflectionRequest) - switch tag { - case 3: // message_request.file_by_filename - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_FileByFilename{x} - return true, err - case 4: // message_request.file_containing_symbol - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_FileContainingSymbol{x} - return true, err - case 5: // message_request.file_containing_extension - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ExtensionRequest) - err := b.DecodeMessage(msg) - m.MessageRequest = &ServerReflectionRequest_FileContainingExtension{msg} - return true, err - case 6: // message_request.all_extension_numbers_of_type - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_AllExtensionNumbersOfType{x} - return true, err - case 7: // message_request.list_services - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_ListServices{x} - return true, err - default: - return false, nil - } -} - -func _ServerReflectionRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerReflectionRequest) - // message_request - switch x := m.MessageRequest.(type) { - case *ServerReflectionRequest_FileByFilename: - n += proto.SizeVarint(3<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.FileByFilename))) - n += len(x.FileByFilename) - case *ServerReflectionRequest_FileContainingSymbol: - n += proto.SizeVarint(4<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.FileContainingSymbol))) - n += len(x.FileContainingSymbol) - case *ServerReflectionRequest_FileContainingExtension: - s := proto.Size(x.FileContainingExtension) - n += proto.SizeVarint(5<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionRequest_AllExtensionNumbersOfType: - n += proto.SizeVarint(6<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.AllExtensionNumbersOfType))) - n += len(x.AllExtensionNumbersOfType) - case *ServerReflectionRequest_ListServices: - n += proto.SizeVarint(7<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.ListServices))) - n += len(x.ListServices) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// The type name and extension number sent by the client when requesting -// file_containing_extension. -type ExtensionRequest struct { - // Fully-qualified type name. The format should be <package>.<type> - ContainingType string `protobuf:"bytes,1,opt,name=containing_type,json=containingType" json:"containing_type,omitempty"` - ExtensionNumber int32 `protobuf:"varint,2,opt,name=extension_number,json=extensionNumber" json:"extension_number,omitempty"` -} - -func (m *ExtensionRequest) Reset() { *m = ExtensionRequest{} } -func (m *ExtensionRequest) String() string { return proto.CompactTextString(m) } -func (*ExtensionRequest) ProtoMessage() {} -func (*ExtensionRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *ExtensionRequest) GetContainingType() string { - if m != nil { - return m.ContainingType - } - return "" -} - -func (m *ExtensionRequest) GetExtensionNumber() int32 { - if m != nil { - return m.ExtensionNumber - } - return 0 -} - -// The message sent by the server to answer ServerReflectionInfo method. -type ServerReflectionResponse struct { - ValidHost string `protobuf:"bytes,1,opt,name=valid_host,json=validHost" json:"valid_host,omitempty"` - OriginalRequest *ServerReflectionRequest `protobuf:"bytes,2,opt,name=original_request,json=originalRequest" json:"original_request,omitempty"` - // The server set one of the following fields according to the message_request - // in the request. - // - // Types that are valid to be assigned to MessageResponse: - // *ServerReflectionResponse_FileDescriptorResponse - // *ServerReflectionResponse_AllExtensionNumbersResponse - // *ServerReflectionResponse_ListServicesResponse - // *ServerReflectionResponse_ErrorResponse - MessageResponse isServerReflectionResponse_MessageResponse `protobuf_oneof:"message_response"` -} - -func (m *ServerReflectionResponse) Reset() { *m = ServerReflectionResponse{} } -func (m *ServerReflectionResponse) String() string { return proto.CompactTextString(m) } -func (*ServerReflectionResponse) ProtoMessage() {} -func (*ServerReflectionResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -type isServerReflectionResponse_MessageResponse interface { - isServerReflectionResponse_MessageResponse() -} - -type ServerReflectionResponse_FileDescriptorResponse struct { - FileDescriptorResponse *FileDescriptorResponse `protobuf:"bytes,4,opt,name=file_descriptor_response,json=fileDescriptorResponse,oneof"` -} -type ServerReflectionResponse_AllExtensionNumbersResponse struct { - AllExtensionNumbersResponse *ExtensionNumberResponse `protobuf:"bytes,5,opt,name=all_extension_numbers_response,json=allExtensionNumbersResponse,oneof"` -} -type ServerReflectionResponse_ListServicesResponse struct { - ListServicesResponse *ListServiceResponse `protobuf:"bytes,6,opt,name=list_services_response,json=listServicesResponse,oneof"` -} -type ServerReflectionResponse_ErrorResponse struct { - ErrorResponse *ErrorResponse `protobuf:"bytes,7,opt,name=error_response,json=errorResponse,oneof"` -} - -func (*ServerReflectionResponse_FileDescriptorResponse) isServerReflectionResponse_MessageResponse() {} -func (*ServerReflectionResponse_AllExtensionNumbersResponse) isServerReflectionResponse_MessageResponse() { -} -func (*ServerReflectionResponse_ListServicesResponse) isServerReflectionResponse_MessageResponse() {} -func (*ServerReflectionResponse_ErrorResponse) isServerReflectionResponse_MessageResponse() {} - -func (m *ServerReflectionResponse) GetMessageResponse() isServerReflectionResponse_MessageResponse { - if m != nil { - return m.MessageResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetValidHost() string { - if m != nil { - return m.ValidHost - } - return "" -} - -func (m *ServerReflectionResponse) GetOriginalRequest() *ServerReflectionRequest { - if m != nil { - return m.OriginalRequest - } - return nil -} - -func (m *ServerReflectionResponse) GetFileDescriptorResponse() *FileDescriptorResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_FileDescriptorResponse); ok { - return x.FileDescriptorResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetAllExtensionNumbersResponse() *ExtensionNumberResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_AllExtensionNumbersResponse); ok { - return x.AllExtensionNumbersResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetListServicesResponse() *ListServiceResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ListServicesResponse); ok { - return x.ListServicesResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetErrorResponse() *ErrorResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ErrorResponse); ok { - return x.ErrorResponse - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerReflectionResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerReflectionResponse_OneofMarshaler, _ServerReflectionResponse_OneofUnmarshaler, _ServerReflectionResponse_OneofSizer, []interface{}{ - (*ServerReflectionResponse_FileDescriptorResponse)(nil), - (*ServerReflectionResponse_AllExtensionNumbersResponse)(nil), - (*ServerReflectionResponse_ListServicesResponse)(nil), - (*ServerReflectionResponse_ErrorResponse)(nil), - } -} - -func _ServerReflectionResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerReflectionResponse) - // message_response - switch x := m.MessageResponse.(type) { - case *ServerReflectionResponse_FileDescriptorResponse: - b.EncodeVarint(4<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.FileDescriptorResponse); err != nil { - return err - } - case *ServerReflectionResponse_AllExtensionNumbersResponse: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.AllExtensionNumbersResponse); err != nil { - return err - } - case *ServerReflectionResponse_ListServicesResponse: - b.EncodeVarint(6<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ListServicesResponse); err != nil { - return err - } - case *ServerReflectionResponse_ErrorResponse: - b.EncodeVarint(7<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ErrorResponse); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ServerReflectionResponse.MessageResponse has unexpected type %T", x) - } - return nil -} - -func _ServerReflectionResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerReflectionResponse) - switch tag { - case 4: // message_response.file_descriptor_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(FileDescriptorResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_FileDescriptorResponse{msg} - return true, err - case 5: // message_response.all_extension_numbers_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ExtensionNumberResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_AllExtensionNumbersResponse{msg} - return true, err - case 6: // message_response.list_services_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ListServiceResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_ListServicesResponse{msg} - return true, err - case 7: // message_response.error_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ErrorResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_ErrorResponse{msg} - return true, err - default: - return false, nil - } -} - -func _ServerReflectionResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerReflectionResponse) - // message_response - switch x := m.MessageResponse.(type) { - case *ServerReflectionResponse_FileDescriptorResponse: - s := proto.Size(x.FileDescriptorResponse) - n += proto.SizeVarint(4<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_AllExtensionNumbersResponse: - s := proto.Size(x.AllExtensionNumbersResponse) - n += proto.SizeVarint(5<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_ListServicesResponse: - s := proto.Size(x.ListServicesResponse) - n += proto.SizeVarint(6<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_ErrorResponse: - s := proto.Size(x.ErrorResponse) - n += proto.SizeVarint(7<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// Serialized FileDescriptorProto messages sent by the server answering -// a file_by_filename, file_containing_symbol, or file_containing_extension -// request. -type FileDescriptorResponse struct { - // Serialized FileDescriptorProto messages. We avoid taking a dependency on - // descriptor.proto, which uses proto2 only features, by making them opaque - // bytes instead. - FileDescriptorProto [][]byte `protobuf:"bytes,1,rep,name=file_descriptor_proto,json=fileDescriptorProto,proto3" json:"file_descriptor_proto,omitempty"` -} - -func (m *FileDescriptorResponse) Reset() { *m = FileDescriptorResponse{} } -func (m *FileDescriptorResponse) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorResponse) ProtoMessage() {} -func (*FileDescriptorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *FileDescriptorResponse) GetFileDescriptorProto() [][]byte { - if m != nil { - return m.FileDescriptorProto - } - return nil -} - -// A list of extension numbers sent by the server answering -// all_extension_numbers_of_type request. -type ExtensionNumberResponse struct { - // Full name of the base type, including the package name. The format - // is <package>.<type> - BaseTypeName string `protobuf:"bytes,1,opt,name=base_type_name,json=baseTypeName" json:"base_type_name,omitempty"` - ExtensionNumber []int32 `protobuf:"varint,2,rep,packed,name=extension_number,json=extensionNumber" json:"extension_number,omitempty"` -} - -func (m *ExtensionNumberResponse) Reset() { *m = ExtensionNumberResponse{} } -func (m *ExtensionNumberResponse) String() string { return proto.CompactTextString(m) } -func (*ExtensionNumberResponse) ProtoMessage() {} -func (*ExtensionNumberResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -func (m *ExtensionNumberResponse) GetBaseTypeName() string { - if m != nil { - return m.BaseTypeName - } - return "" -} - -func (m *ExtensionNumberResponse) GetExtensionNumber() []int32 { - if m != nil { - return m.ExtensionNumber - } - return nil -} - -// A list of ServiceResponse sent by the server answering list_services request. -type ListServiceResponse struct { - // The information of each service may be expanded in the future, so we use - // ServiceResponse message to encapsulate it. - Service []*ServiceResponse `protobuf:"bytes,1,rep,name=service" json:"service,omitempty"` -} - -func (m *ListServiceResponse) Reset() { *m = ListServiceResponse{} } -func (m *ListServiceResponse) String() string { return proto.CompactTextString(m) } -func (*ListServiceResponse) ProtoMessage() {} -func (*ListServiceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } - -func (m *ListServiceResponse) GetService() []*ServiceResponse { - if m != nil { - return m.Service - } - return nil -} - -// The information of a single service used by ListServiceResponse to answer -// list_services request. -type ServiceResponse struct { - // Full name of a registered service, including its package name. The format - // is <package>.<service> - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` -} - -func (m *ServiceResponse) Reset() { *m = ServiceResponse{} } -func (m *ServiceResponse) String() string { return proto.CompactTextString(m) } -func (*ServiceResponse) ProtoMessage() {} -func (*ServiceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } - -func (m *ServiceResponse) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// The error code and error message sent by the server when an error occurs. -type ErrorResponse struct { - // This field uses the error codes defined in grpc::StatusCode. - ErrorCode int32 `protobuf:"varint,1,opt,name=error_code,json=errorCode" json:"error_code,omitempty"` - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage" json:"error_message,omitempty"` -} - -func (m *ErrorResponse) Reset() { *m = ErrorResponse{} } -func (m *ErrorResponse) String() string { return proto.CompactTextString(m) } -func (*ErrorResponse) ProtoMessage() {} -func (*ErrorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } - -func (m *ErrorResponse) GetErrorCode() int32 { - if m != nil { - return m.ErrorCode - } - return 0 -} - -func (m *ErrorResponse) GetErrorMessage() string { - if m != nil { - return m.ErrorMessage - } - return "" -} - -func init() { - proto.RegisterType((*ServerReflectionRequest)(nil), "grpc.reflection.v1alpha.ServerReflectionRequest") - proto.RegisterType((*ExtensionRequest)(nil), "grpc.reflection.v1alpha.ExtensionRequest") - proto.RegisterType((*ServerReflectionResponse)(nil), "grpc.reflection.v1alpha.ServerReflectionResponse") - proto.RegisterType((*FileDescriptorResponse)(nil), "grpc.reflection.v1alpha.FileDescriptorResponse") - proto.RegisterType((*ExtensionNumberResponse)(nil), "grpc.reflection.v1alpha.ExtensionNumberResponse") - proto.RegisterType((*ListServiceResponse)(nil), "grpc.reflection.v1alpha.ListServiceResponse") - proto.RegisterType((*ServiceResponse)(nil), "grpc.reflection.v1alpha.ServiceResponse") - proto.RegisterType((*ErrorResponse)(nil), "grpc.reflection.v1alpha.ErrorResponse") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for ServerReflection service - -type ServerReflectionClient interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) -} - -type serverReflectionClient struct { - cc *grpc.ClientConn -} - -func NewServerReflectionClient(cc *grpc.ClientConn) ServerReflectionClient { - return &serverReflectionClient{cc} -} - -func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) { - stream, err := grpc.NewClientStream(ctx, &_ServerReflection_serviceDesc.Streams[0], c.cc, "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...) - if err != nil { - return nil, err - } - x := &serverReflectionServerReflectionInfoClient{stream} - return x, nil -} - -type ServerReflection_ServerReflectionInfoClient interface { - Send(*ServerReflectionRequest) error - Recv() (*ServerReflectionResponse, error) - grpc.ClientStream -} - -type serverReflectionServerReflectionInfoClient struct { - grpc.ClientStream -} - -func (x *serverReflectionServerReflectionInfoClient) Send(m *ServerReflectionRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoClient) Recv() (*ServerReflectionResponse, error) { - m := new(ServerReflectionResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for ServerReflection service - -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 -} - -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 { - Send(*ServerReflectionResponse) error - Recv() (*ServerReflectionRequest, error) - grpc.ServerStream -} - -type serverReflectionServerReflectionInfoServer struct { - grpc.ServerStream -} - -func (x *serverReflectionServerReflectionInfoServer) Send(m *ServerReflectionResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoServer) Recv() (*ServerReflectionRequest, error) { - m := new(ServerReflectionRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _ServerReflection_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.reflection.v1alpha.ServerReflection", - HandlerType: (*ServerReflectionServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "ServerReflectionInfo", - Handler: _ServerReflection_ServerReflectionInfo_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_reflection_v1alpha/reflection.proto", -} - -func init() { proto.RegisterFile("grpc_reflection_v1alpha/reflection.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 656 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x51, 0x73, 0xd2, 0x40, - 0x10, 0x6e, 0x5a, 0x68, 0x87, 0x85, 0x02, 0x5e, 0x2b, 0xa4, 0x3a, 0x75, 0x98, 0x68, 0x35, 0x75, - 0x1c, 0xda, 0xe2, 0x8c, 0x3f, 0x80, 0xaa, 0x83, 0x33, 0xb5, 0x75, 0x0e, 0x5f, 0x1c, 0x1f, 0x6e, - 0x02, 0x2c, 0x34, 0x1a, 0x72, 0xf1, 0x2e, 0x45, 0x79, 0xf2, 0x47, 0xf8, 0xa3, 0xfc, 0x4b, 0x3e, - 0x3a, 0x77, 0x09, 0x21, 0xa4, 0x44, 0xa7, 0x4f, 0x30, 0xdf, 0xee, 0xde, 0xb7, 0xbb, 0xdf, 0xb7, - 0x01, 0x7b, 0x22, 0x82, 0x21, 0x13, 0x38, 0xf6, 0x70, 0x18, 0xba, 0xdc, 0x67, 0xb3, 0x33, 0xc7, - 0x0b, 0xae, 0x9d, 0x93, 0x25, 0xd4, 0x0e, 0x04, 0x0f, 0x39, 0x69, 0xaa, 0xcc, 0x76, 0x0a, 0x8e, - 0x33, 0xad, 0x3f, 0x9b, 0xd0, 0xec, 0xa3, 0x98, 0xa1, 0xa0, 0x49, 0x90, 0xe2, 0xb7, 0x1b, 0x94, - 0x21, 0x21, 0x50, 0xb8, 0xe6, 0x32, 0x34, 0x8d, 0x96, 0x61, 0x97, 0xa8, 0xfe, 0x4f, 0x9e, 0x43, - 0x7d, 0xec, 0x7a, 0xc8, 0x06, 0x73, 0xa6, 0x7e, 0x7d, 0x67, 0x8a, 0xe6, 0x96, 0x8a, 0xf7, 0x36, - 0x68, 0x55, 0x21, 0xdd, 0xf9, 0xdb, 0x18, 0x27, 0xaf, 0xa0, 0xa1, 0x73, 0x87, 0xdc, 0x0f, 0x1d, - 0xd7, 0x77, 0xfd, 0x09, 0x93, 0xf3, 0xe9, 0x80, 0x7b, 0x66, 0x21, 0xae, 0xd8, 0x57, 0xf1, 0xf3, - 0x24, 0xdc, 0xd7, 0x51, 0x32, 0x81, 0x83, 0x6c, 0x1d, 0xfe, 0x08, 0xd1, 0x97, 0x2e, 0xf7, 0xcd, - 0x62, 0xcb, 0xb0, 0xcb, 0x9d, 0xe3, 0x76, 0xce, 0x40, 0xed, 0x37, 0x8b, 0xcc, 0x78, 0x8a, 0xde, - 0x06, 0x6d, 0xae, 0xb2, 0x24, 0x19, 0xa4, 0x0b, 0x87, 0x8e, 0xe7, 0x2d, 0x1f, 0x67, 0xfe, 0xcd, - 0x74, 0x80, 0x42, 0x32, 0x3e, 0x66, 0xe1, 0x3c, 0x40, 0x73, 0x3b, 0xee, 0xf3, 0xc0, 0xf1, 0xbc, - 0xa4, 0xec, 0x32, 0x4a, 0xba, 0x1a, 0x7f, 0x9c, 0x07, 0x48, 0x8e, 0x60, 0xd7, 0x73, 0x65, 0xc8, - 0x24, 0x8a, 0x99, 0x3b, 0x44, 0x69, 0xee, 0xc4, 0x35, 0x15, 0x05, 0xf7, 0x63, 0xb4, 0x7b, 0x0f, - 0x6a, 0x53, 0x94, 0xd2, 0x99, 0x20, 0x13, 0x51, 0x63, 0xd6, 0x18, 0xea, 0xd9, 0x66, 0xc9, 0x33, - 0xa8, 0xa5, 0xa6, 0xd6, 0x3d, 0x44, 0xdb, 0xaf, 0x2e, 0x61, 0x4d, 0x7b, 0x0c, 0xf5, 0x6c, 0xdb, - 0xe6, 0x66, 0xcb, 0xb0, 0x8b, 0xb4, 0x86, 0xab, 0x8d, 0x5a, 0xbf, 0x0b, 0x60, 0xde, 0x96, 0x58, - 0x06, 0xdc, 0x97, 0x48, 0x0e, 0x01, 0x66, 0x8e, 0xe7, 0x8e, 0x58, 0x4a, 0xe9, 0x92, 0x46, 0x7a, - 0x4a, 0xee, 0xcf, 0x50, 0xe7, 0xc2, 0x9d, 0xb8, 0xbe, 0xe3, 0x2d, 0xfa, 0xd6, 0x34, 0xe5, 0xce, - 0x69, 0xae, 0x02, 0x39, 0x76, 0xa2, 0xb5, 0xc5, 0x4b, 0x8b, 0x61, 0xbf, 0x82, 0xa9, 0x75, 0x1e, - 0xa1, 0x1c, 0x0a, 0x37, 0x08, 0xb9, 0x60, 0x22, 0xee, 0x4b, 0x3b, 0xa4, 0xdc, 0x39, 0xc9, 0x25, - 0x51, 0x26, 0x7b, 0x9d, 0xd4, 0x2d, 0xc6, 0xe9, 0x6d, 0x50, 0x6d, 0xb9, 0xdb, 0x11, 0xf2, 0x1d, - 0x1e, 0xad, 0xd7, 0x3a, 0xa1, 0x2c, 0xfe, 0x67, 0xae, 0x8c, 0x01, 0x52, 0x9c, 0x0f, 0xd7, 0xd8, - 0x23, 0x21, 0x1e, 0x41, 0x63, 0xc5, 0x20, 0x4b, 0xc2, 0x6d, 0x4d, 0xf8, 0x22, 0x97, 0xf0, 0x62, - 0x69, 0xa0, 0x14, 0xd9, 0x7e, 0xda, 0x57, 0x09, 0xcb, 0x15, 0x54, 0x51, 0x88, 0xf4, 0x06, 0x77, - 0xf4, 0xeb, 0x4f, 0xf3, 0xc7, 0x51, 0xe9, 0xa9, 0x77, 0x77, 0x31, 0x0d, 0x74, 0x09, 0xd4, 0x97, - 0x86, 0x8d, 0x30, 0xeb, 0x02, 0x1a, 0xeb, 0xf7, 0x4e, 0x3a, 0x70, 0x3f, 0x2b, 0xa5, 0xfe, 0xf0, - 0x98, 0x46, 0x6b, 0xcb, 0xae, 0xd0, 0xbd, 0x55, 0x51, 0x3e, 0xa8, 0x90, 0xf5, 0x05, 0x9a, 0x39, - 0x2b, 0x25, 0x4f, 0xa0, 0x3a, 0x70, 0x24, 0xea, 0x03, 0x60, 0xfa, 0x1b, 0x13, 0x39, 0xb3, 0xa2, - 0x50, 0xe5, 0xff, 0x4b, 0xf5, 0x7d, 0x59, 0x7f, 0x03, 0x5b, 0xeb, 0x6e, 0xe0, 0x13, 0xec, 0xad, - 0xd9, 0x26, 0xe9, 0xc2, 0x4e, 0x2c, 0x8b, 0x6e, 0xb4, 0xdc, 0xb1, 0xff, 0xe9, 0xea, 0x54, 0x29, - 0x5d, 0x14, 0x5a, 0x47, 0x50, 0xcb, 0x3e, 0x4b, 0xa0, 0x90, 0x6a, 0x5a, 0xff, 0xb7, 0xfa, 0xb0, - 0xbb, 0xb2, 0x71, 0x75, 0x79, 0x91, 0x62, 0x43, 0x3e, 0x8a, 0x52, 0x8b, 0xb4, 0xa4, 0x91, 0x73, - 0x3e, 0x42, 0xf2, 0x18, 0x22, 0x41, 0x58, 0xac, 0x82, 0x3e, 0xbb, 0x12, 0xad, 0x68, 0xf0, 0x7d, - 0x84, 0x75, 0x7e, 0x19, 0x50, 0xcf, 0x9e, 0x1b, 0xf9, 0x09, 0xfb, 0x59, 0xec, 0x9d, 0x3f, 0xe6, - 0xe4, 0xce, 0x17, 0xfb, 0xe0, 0xec, 0x0e, 0x15, 0xd1, 0x54, 0xb6, 0x71, 0x6a, 0x0c, 0xb6, 0xb5, - 0xf4, 0x2f, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x85, 0x02, 0x09, 0x9d, 0x9f, 0x06, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto deleted file mode 100644 index c52ccc6ab..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Service exported by server reflection - -syntax = "proto3"; - -package grpc.reflection.v1alpha; - -service ServerReflection { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - rpc ServerReflectionInfo(stream ServerReflectionRequest) - returns (stream ServerReflectionResponse); -} - -// The message sent by the client when calling ServerReflectionInfo method. -message ServerReflectionRequest { - string host = 1; - // To use reflection service, the client should set one of the following - // fields in message_request. The server distinguishes requests by their - // defined field and then handles them using corresponding methods. - oneof message_request { - // Find a proto file by the file name. - string file_by_filename = 3; - - // Find the proto file that declares the given fully-qualified symbol name. - // This field should be a fully-qualified symbol name - // (e.g. <package>.<service>[.<method>] or <package>.<type>). - string file_containing_symbol = 4; - - // Find the proto file which defines an extension extending the given - // message type with the given field number. - ExtensionRequest file_containing_extension = 5; - - // Finds the tag numbers used by all known extensions of extendee_type, and - // appends them to ExtensionNumberResponse in an undefined order. - // Its corresponding method is best-effort: it's not guaranteed that the - // reflection service will implement this method, and it's not guaranteed - // that this method will provide all extensions. Returns - // StatusCode::UNIMPLEMENTED if it's not implemented. - // This field should be a fully-qualified type name. The format is - // <package>.<type> - string all_extension_numbers_of_type = 6; - - // List the full names of registered services. The content will not be - // checked. - string list_services = 7; - } -} - -// The type name and extension number sent by the client when requesting -// file_containing_extension. -message ExtensionRequest { - // Fully-qualified type name. The format should be <package>.<type> - string containing_type = 1; - int32 extension_number = 2; -} - -// The message sent by the server to answer ServerReflectionInfo method. -message ServerReflectionResponse { - string valid_host = 1; - ServerReflectionRequest original_request = 2; - // The server set one of the following fields according to the message_request - // in the request. - oneof message_response { - // This message is used to answer file_by_filename, file_containing_symbol, - // file_containing_extension requests with transitive dependencies. As - // the repeated label is not allowed in oneof fields, we use a - // FileDescriptorResponse message to encapsulate the repeated fields. - // The reflection service is allowed to avoid sending FileDescriptorProtos - // that were previously sent in response to earlier requests in the stream. - FileDescriptorResponse file_descriptor_response = 4; - - // This message is used to answer all_extension_numbers_of_type requst. - ExtensionNumberResponse all_extension_numbers_response = 5; - - // This message is used to answer list_services request. - ListServiceResponse list_services_response = 6; - - // This message is used when an error occurs. - ErrorResponse error_response = 7; - } -} - -// Serialized FileDescriptorProto messages sent by the server answering -// a file_by_filename, file_containing_symbol, or file_containing_extension -// request. -message FileDescriptorResponse { - // Serialized FileDescriptorProto messages. We avoid taking a dependency on - // descriptor.proto, which uses proto2 only features, by making them opaque - // bytes instead. - repeated bytes file_descriptor_proto = 1; -} - -// A list of extension numbers sent by the server answering -// all_extension_numbers_of_type request. -message ExtensionNumberResponse { - // Full name of the base type, including the package name. The format - // is <package>.<type> - string base_type_name = 1; - repeated int32 extension_number = 2; -} - -// A list of ServiceResponse sent by the server answering list_services request. -message ListServiceResponse { - // The information of each service may be expanded in the future, so we use - // ServiceResponse message to encapsulate it. - repeated ServiceResponse service = 1; -} - -// The information of a single service used by ListServiceResponse to answer -// list_services request. -message ServiceResponse { - // Full name of a registered service, including its package name. The format - // is <package>.<service> - string name = 1; -} - -// The error code and error message sent by the server when an error occurs. -message ErrorResponse { - // This field uses the error codes defined in grpc::StatusCode. - int32 error_code = 1; - string error_message = 2; -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2.pb.go deleted file mode 100644 index 5b0161885..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2.pb.go +++ /dev/null @@ -1,77 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto2.proto - -/* -Package grpc_testing is a generated protocol buffer package. - -It is generated from these files: - proto2.proto - proto2_ext.proto - proto2_ext2.proto - test.proto - -It has these top-level messages: - ToBeExtended - Extension - AnotherExtension - SearchResponse - SearchRequest -*/ -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ToBeExtended struct { - Foo *int32 `protobuf:"varint,1,req,name=foo" json:"foo,omitempty"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ToBeExtended) Reset() { *m = ToBeExtended{} } -func (m *ToBeExtended) String() string { return proto.CompactTextString(m) } -func (*ToBeExtended) ProtoMessage() {} -func (*ToBeExtended) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -var extRange_ToBeExtended = []proto.ExtensionRange{ - {10, 30}, -} - -func (*ToBeExtended) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ToBeExtended -} - -func (m *ToBeExtended) GetFoo() int32 { - if m != nil && m.Foo != nil { - return *m.Foo - } - return 0 -} - -func init() { - proto.RegisterType((*ToBeExtended)(nil), "grpc.testing.ToBeExtended") -} - -func init() { proto.RegisterFile("proto2.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 86 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0x28, 0xca, 0x2f, - 0xc9, 0x37, 0xd2, 0x03, 0x53, 0x42, 0x3c, 0xe9, 0x45, 0x05, 0xc9, 0x7a, 0x25, 0xa9, 0xc5, 0x25, - 0x99, 0x79, 0xe9, 0x4a, 0x6a, 0x5c, 0x3c, 0x21, 0xf9, 0x4e, 0xa9, 0xae, 0x15, 0x25, 0xa9, 0x79, - 0x29, 0xa9, 0x29, 0x42, 0x02, 0x5c, 0xcc, 0x69, 0xf9, 0xf9, 0x12, 0x8c, 0x0a, 0x4c, 0x1a, 0xac, - 0x41, 0x20, 0xa6, 0x16, 0x0b, 0x07, 0x97, 0x80, 0x3c, 0x20, 0x00, 0x00, 0xff, 0xff, 0x74, 0x86, - 0x9c, 0x08, 0x44, 0x00, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2.proto b/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2.proto deleted file mode 100644 index a675d143d..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2.proto +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; - -package grpc.testing; - -message ToBeExtended { - required int32 foo = 1; - extensions 10 to 30; -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.pb.go deleted file mode 100644 index 9ae4f07af..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.pb.go +++ /dev/null @@ -1,82 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto2_ext.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -type Extension struct { - Whatzit *int32 `protobuf:"varint,1,opt,name=whatzit" json:"whatzit,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Extension) Reset() { *m = Extension{} } -func (m *Extension) String() string { return proto.CompactTextString(m) } -func (*Extension) ProtoMessage() {} -func (*Extension) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} } - -func (m *Extension) GetWhatzit() int32 { - if m != nil && m.Whatzit != nil { - return *m.Whatzit - } - return 0 -} - -var E_Foo = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*int32)(nil), - Field: 13, - Name: "grpc.testing.foo", - Tag: "varint,13,opt,name=foo", - Filename: "proto2_ext.proto", -} - -var E_Bar = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*Extension)(nil), - Field: 17, - Name: "grpc.testing.bar", - Tag: "bytes,17,opt,name=bar", - Filename: "proto2_ext.proto", -} - -var E_Baz = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*SearchRequest)(nil), - Field: 19, - Name: "grpc.testing.baz", - Tag: "bytes,19,opt,name=baz", - Filename: "proto2_ext.proto", -} - -func init() { - proto.RegisterType((*Extension)(nil), "grpc.testing.Extension") - proto.RegisterExtension(E_Foo) - proto.RegisterExtension(E_Bar) - proto.RegisterExtension(E_Baz) -} - -func init() { proto.RegisterFile("proto2_ext.proto", fileDescriptor1) } - -var fileDescriptor1 = []byte{ - // 179 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x28, 0x28, 0xca, 0x2f, - 0xc9, 0x37, 0x8a, 0x4f, 0xad, 0x28, 0xd1, 0x03, 0x33, 0x85, 0x78, 0xd2, 0x8b, 0x0a, 0x92, 0xf5, - 0x4a, 0x52, 0x8b, 0x4b, 0x32, 0xf3, 0xd2, 0xa5, 0x78, 0x20, 0xf2, 0x10, 0x39, 0x29, 0x2e, 0x90, - 0x30, 0x84, 0xad, 0xa4, 0xca, 0xc5, 0xe9, 0x5a, 0x51, 0x92, 0x9a, 0x57, 0x9c, 0x99, 0x9f, 0x27, - 0x24, 0xc1, 0xc5, 0x5e, 0x9e, 0x91, 0x58, 0x52, 0x95, 0x59, 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, - 0x1a, 0x04, 0xe3, 0x5a, 0xe9, 0x70, 0x31, 0xa7, 0xe5, 0xe7, 0x0b, 0x49, 0xe9, 0x21, 0x1b, 0xab, - 0x17, 0x92, 0xef, 0x94, 0x0a, 0xd6, 0x9d, 0x92, 0x9a, 0x22, 0xc1, 0x0b, 0xd6, 0x01, 0x52, 0x66, - 0xe5, 0xca, 0xc5, 0x9c, 0x94, 0x58, 0x84, 0x57, 0xb5, 0xa0, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x38, - 0xaa, 0x0a, 0xb8, 0x4b, 0x82, 0x40, 0xfa, 0xad, 0x3c, 0x41, 0xc6, 0x54, 0xe1, 0x35, 0x46, 0x18, - 0x6c, 0x8c, 0x34, 0xaa, 0x8a, 0xe0, 0xd4, 0xc4, 0xa2, 0xe4, 0x8c, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, - 0xe2, 0x12, 0x90, 0x51, 0x55, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x71, 0x6b, 0x94, 0x9f, 0x21, - 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.proto b/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.proto deleted file mode 100644 index a4942e481..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.proto +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; - -package grpc.testing; - -import "proto2.proto"; -import "test.proto"; - -extend ToBeExtended { - optional int32 foo = 13; - optional Extension bar = 17; - optional SearchRequest baz = 19; -} - -message Extension { - optional int32 whatzit = 1; -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.pb.go deleted file mode 100644 index 26ec982aa..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.pb.go +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto2_ext2.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -type AnotherExtension struct { - Whatchamacallit *int32 `protobuf:"varint,1,opt,name=whatchamacallit" json:"whatchamacallit,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AnotherExtension) Reset() { *m = AnotherExtension{} } -func (m *AnotherExtension) String() string { return proto.CompactTextString(m) } -func (*AnotherExtension) ProtoMessage() {} -func (*AnotherExtension) Descriptor() ([]byte, []int) { return fileDescriptor2, []int{0} } - -func (m *AnotherExtension) GetWhatchamacallit() int32 { - if m != nil && m.Whatchamacallit != nil { - return *m.Whatchamacallit - } - return 0 -} - -var E_Frob = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*string)(nil), - Field: 23, - Name: "grpc.testing.frob", - Tag: "bytes,23,opt,name=frob", - Filename: "proto2_ext2.proto", -} - -var E_Nitz = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*AnotherExtension)(nil), - Field: 29, - Name: "grpc.testing.nitz", - Tag: "bytes,29,opt,name=nitz", - Filename: "proto2_ext2.proto", -} - -func init() { - proto.RegisterType((*AnotherExtension)(nil), "grpc.testing.AnotherExtension") - proto.RegisterExtension(E_Frob) - proto.RegisterExtension(E_Nitz) -} - -func init() { proto.RegisterFile("proto2_ext2.proto", fileDescriptor2) } - -var fileDescriptor2 = []byte{ - // 165 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2c, 0x28, 0xca, 0x2f, - 0xc9, 0x37, 0x8a, 0x4f, 0xad, 0x28, 0x31, 0xd2, 0x03, 0xb3, 0x85, 0x78, 0xd2, 0x8b, 0x0a, 0x92, - 0xf5, 0x4a, 0x52, 0x8b, 0x4b, 0x32, 0xf3, 0xd2, 0xa5, 0x78, 0x20, 0x0a, 0x20, 0x72, 0x4a, 0x36, - 0x5c, 0x02, 0x8e, 0x79, 0xf9, 0x25, 0x19, 0xa9, 0x45, 0xae, 0x15, 0x25, 0xa9, 0x79, 0xc5, 0x99, - 0xf9, 0x79, 0x42, 0x1a, 0x5c, 0xfc, 0xe5, 0x19, 0x89, 0x25, 0xc9, 0x19, 0x89, 0xb9, 0x89, 0xc9, - 0x89, 0x39, 0x39, 0x99, 0x25, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0xe8, 0xc2, 0x56, 0x7a, - 0x5c, 0x2c, 0x69, 0x45, 0xf9, 0x49, 0x42, 0x52, 0x7a, 0xc8, 0x56, 0xe8, 0x85, 0xe4, 0x3b, 0xa5, - 0x82, 0x8d, 0x4b, 0x49, 0x4d, 0x91, 0x10, 0x57, 0x60, 0xd4, 0xe0, 0x0c, 0x02, 0xab, 0xb3, 0xf2, - 0xe3, 0x62, 0xc9, 0xcb, 0x2c, 0xa9, 0xc2, 0xab, 0x5e, 0x56, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x0e, - 0x55, 0x05, 0xba, 0x1b, 0x83, 0xc0, 0xe6, 0x00, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf0, 0x7e, 0x0d, - 0x26, 0xed, 0x00, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.proto b/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.proto deleted file mode 100644 index d91ba0061..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.proto +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; - -package grpc.testing; - -import "proto2.proto"; - -extend ToBeExtended { - optional string frob = 23; - optional AnotherExtension nitz = 29; -} - -message AnotherExtension { - optional int32 whatchamacallit = 1; -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/test.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_testing/test.pb.go deleted file mode 100644 index 62f71ff15..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/test.pb.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: test.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -type SearchResponse struct { - Results []*SearchResponse_Result `protobuf:"bytes,1,rep,name=results" json:"results,omitempty"` -} - -func (m *SearchResponse) Reset() { *m = SearchResponse{} } -func (m *SearchResponse) String() string { return proto.CompactTextString(m) } -func (*SearchResponse) ProtoMessage() {} -func (*SearchResponse) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{0} } - -func (m *SearchResponse) GetResults() []*SearchResponse_Result { - if m != nil { - return m.Results - } - return nil -} - -type SearchResponse_Result struct { - Url string `protobuf:"bytes,1,opt,name=url" json:"url,omitempty"` - Title string `protobuf:"bytes,2,opt,name=title" json:"title,omitempty"` - Snippets []string `protobuf:"bytes,3,rep,name=snippets" json:"snippets,omitempty"` -} - -func (m *SearchResponse_Result) Reset() { *m = SearchResponse_Result{} } -func (m *SearchResponse_Result) String() string { return proto.CompactTextString(m) } -func (*SearchResponse_Result) ProtoMessage() {} -func (*SearchResponse_Result) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{0, 0} } - -func (m *SearchResponse_Result) GetUrl() string { - if m != nil { - return m.Url - } - return "" -} - -func (m *SearchResponse_Result) GetTitle() string { - if m != nil { - return m.Title - } - return "" -} - -func (m *SearchResponse_Result) GetSnippets() []string { - if m != nil { - return m.Snippets - } - return nil -} - -type SearchRequest struct { - Query string `protobuf:"bytes,1,opt,name=query" json:"query,omitempty"` -} - -func (m *SearchRequest) Reset() { *m = SearchRequest{} } -func (m *SearchRequest) String() string { return proto.CompactTextString(m) } -func (*SearchRequest) ProtoMessage() {} -func (*SearchRequest) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} } - -func (m *SearchRequest) GetQuery() string { - if m != nil { - return m.Query - } - return "" -} - -func init() { - proto.RegisterType((*SearchResponse)(nil), "grpc.testing.SearchResponse") - proto.RegisterType((*SearchResponse_Result)(nil), "grpc.testing.SearchResponse.Result") - proto.RegisterType((*SearchRequest)(nil), "grpc.testing.SearchRequest") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for SearchService service - -type SearchServiceClient interface { - Search(ctx context.Context, in *SearchRequest, opts ...grpc.CallOption) (*SearchResponse, error) - StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchService_StreamingSearchClient, error) -} - -type searchServiceClient struct { - cc *grpc.ClientConn -} - -func NewSearchServiceClient(cc *grpc.ClientConn) SearchServiceClient { - return &searchServiceClient{cc} -} - -func (c *searchServiceClient) Search(ctx context.Context, in *SearchRequest, opts ...grpc.CallOption) (*SearchResponse, error) { - out := new(SearchResponse) - err := grpc.Invoke(ctx, "/grpc.testing.SearchService/Search", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *searchServiceClient) StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchService_StreamingSearchClient, error) { - stream, err := grpc.NewClientStream(ctx, &_SearchService_serviceDesc.Streams[0], c.cc, "/grpc.testing.SearchService/StreamingSearch", opts...) - if err != nil { - return nil, err - } - x := &searchServiceStreamingSearchClient{stream} - return x, nil -} - -type SearchService_StreamingSearchClient interface { - Send(*SearchRequest) error - Recv() (*SearchResponse, error) - grpc.ClientStream -} - -type searchServiceStreamingSearchClient struct { - grpc.ClientStream -} - -func (x *searchServiceStreamingSearchClient) Send(m *SearchRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *searchServiceStreamingSearchClient) Recv() (*SearchResponse, error) { - m := new(SearchResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for SearchService service - -type SearchServiceServer interface { - Search(context.Context, *SearchRequest) (*SearchResponse, error) - StreamingSearch(SearchService_StreamingSearchServer) error -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SearchServiceServer).Search(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.SearchService/Search", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SearchServiceServer).Search(ctx, req.(*SearchRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _SearchService_StreamingSearch_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(SearchServiceServer).StreamingSearch(&searchServiceStreamingSearchServer{stream}) -} - -type SearchService_StreamingSearchServer interface { - Send(*SearchResponse) error - Recv() (*SearchRequest, error) - grpc.ServerStream -} - -type searchServiceStreamingSearchServer struct { - grpc.ServerStream -} - -func (x *searchServiceStreamingSearchServer) Send(m *SearchResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *searchServiceStreamingSearchServer) Recv() (*SearchRequest, error) { - m := new(SearchRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _SearchService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.SearchService", - HandlerType: (*SearchServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Search", - Handler: _SearchService_Search_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingSearch", - Handler: _SearchService_StreamingSearch_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "test.proto", -} - -func init() { proto.RegisterFile("test.proto", fileDescriptor3) } - -var fileDescriptor3 = []byte{ - // 231 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x91, 0xbd, 0x4a, 0xc5, 0x40, - 0x10, 0x85, 0x59, 0x83, 0xd1, 0x3b, 0xfe, 0x32, 0x58, 0x84, 0x68, 0x11, 0xae, 0x08, 0xa9, 0x16, - 0xb9, 0xd6, 0x56, 0xb6, 0x16, 0xb2, 0x79, 0x82, 0x6b, 0x18, 0xe2, 0x42, 0x4c, 0x36, 0x33, 0x13, - 0xc1, 0x87, 0xb1, 0xf5, 0x39, 0x25, 0x59, 0x23, 0x0a, 0x62, 0x63, 0xb7, 0xe7, 0xe3, 0xcc, 0xb7, - 0xbb, 0x0c, 0x80, 0x92, 0xa8, 0x0d, 0xdc, 0x6b, 0x8f, 0x87, 0x0d, 0x87, 0xda, 0x4e, 0xc0, 0x77, - 0xcd, 0xfa, 0xcd, 0xc0, 0x71, 0x45, 0x5b, 0xae, 0x9f, 0x1c, 0x49, 0xe8, 0x3b, 0x21, 0xbc, 0x85, - 0x3d, 0x26, 0x19, 0x5b, 0x95, 0xcc, 0x14, 0x49, 0x79, 0xb0, 0xb9, 0xb4, 0xdf, 0x47, 0xec, 0xcf, - 0xba, 0x75, 0x73, 0xd7, 0x2d, 0x33, 0xf9, 0x3d, 0xa4, 0x11, 0xe1, 0x29, 0x24, 0x23, 0xb7, 0x99, - 0x29, 0x4c, 0xb9, 0x72, 0xd3, 0x11, 0xcf, 0x60, 0x57, 0xbd, 0xb6, 0x94, 0xed, 0xcc, 0x2c, 0x06, - 0xcc, 0x61, 0x5f, 0x3a, 0x1f, 0x02, 0xa9, 0x64, 0x49, 0x91, 0x94, 0x2b, 0xf7, 0x95, 0xd7, 0x57, - 0x70, 0xb4, 0xdc, 0x37, 0x8c, 0x24, 0x3a, 0x29, 0x86, 0x91, 0xf8, 0xf5, 0x53, 0x1b, 0xc3, 0xe6, - 0xdd, 0x2c, 0xbd, 0x8a, 0xf8, 0xc5, 0xd7, 0x84, 0x77, 0x90, 0x46, 0x80, 0xe7, 0xbf, 0x3f, 0x7f, - 0xd6, 0xe5, 0x17, 0x7f, 0xfd, 0x0d, 0x1f, 0xe0, 0xa4, 0x52, 0xa6, 0xed, 0xb3, 0xef, 0x9a, 0x7f, - 0xdb, 0x4a, 0x73, 0x6d, 0x1e, 0xd3, 0x79, 0x09, 0x37, 0x1f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x20, - 0xd6, 0x09, 0xb8, 0x92, 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testing/test.proto b/vendor/google.golang.org/grpc/reflection/grpc_testing/test.proto deleted file mode 100644 index cae3f01a0..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testing/test.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - -message SearchResponse { - message Result { - string url = 1; - string title = 2; - repeated string snippets = 3; - } - repeated Result results = 1; -} - -message SearchRequest { - string query = 1; -} - -service SearchService { - rpc Search(SearchRequest) returns (SearchResponse); - rpc StreamingSearch(stream SearchRequest) returns (stream SearchResponse); -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testingv3/testv3.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_testingv3/testv3.pb.go deleted file mode 100644 index 78876aae7..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testingv3/testv3.pb.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by protoc-gen-go. -// source: testv3.proto -// DO NOT EDIT! - -/* -Package grpc_testingv3 is a generated protocol buffer package. - -It is generated from these files: - testv3.proto - -It has these top-level messages: - SearchResponseV3 - SearchRequestV3 -*/ -package grpc_testingv3 - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SearchResponseV3 struct { - Results []*SearchResponseV3_Result `protobuf:"bytes,1,rep,name=results" json:"results,omitempty"` -} - -func (m *SearchResponseV3) Reset() { *m = SearchResponseV3{} } -func (m *SearchResponseV3) String() string { return proto.CompactTextString(m) } -func (*SearchResponseV3) ProtoMessage() {} -func (*SearchResponseV3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *SearchResponseV3) GetResults() []*SearchResponseV3_Result { - if m != nil { - return m.Results - } - return nil -} - -type SearchResponseV3_Result struct { - Url string `protobuf:"bytes,1,opt,name=url" json:"url,omitempty"` - Title string `protobuf:"bytes,2,opt,name=title" json:"title,omitempty"` - Snippets []string `protobuf:"bytes,3,rep,name=snippets" json:"snippets,omitempty"` -} - -func (m *SearchResponseV3_Result) Reset() { *m = SearchResponseV3_Result{} } -func (m *SearchResponseV3_Result) String() string { return proto.CompactTextString(m) } -func (*SearchResponseV3_Result) ProtoMessage() {} -func (*SearchResponseV3_Result) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } - -type SearchRequestV3 struct { - Query string `protobuf:"bytes,1,opt,name=query" json:"query,omitempty"` -} - -func (m *SearchRequestV3) Reset() { *m = SearchRequestV3{} } -func (m *SearchRequestV3) String() string { return proto.CompactTextString(m) } -func (*SearchRequestV3) ProtoMessage() {} -func (*SearchRequestV3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func init() { - proto.RegisterType((*SearchResponseV3)(nil), "grpc.testingv3.SearchResponseV3") - proto.RegisterType((*SearchResponseV3_Result)(nil), "grpc.testingv3.SearchResponseV3.Result") - proto.RegisterType((*SearchRequestV3)(nil), "grpc.testingv3.SearchRequestV3") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion3 - -// Client API for SearchServiceV3 service - -type SearchServiceV3Client interface { - Search(ctx context.Context, in *SearchRequestV3, opts ...grpc.CallOption) (*SearchResponseV3, error) - StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchServiceV3_StreamingSearchClient, error) -} - -type searchServiceV3Client struct { - cc *grpc.ClientConn -} - -func NewSearchServiceV3Client(cc *grpc.ClientConn) SearchServiceV3Client { - return &searchServiceV3Client{cc} -} - -func (c *searchServiceV3Client) Search(ctx context.Context, in *SearchRequestV3, opts ...grpc.CallOption) (*SearchResponseV3, error) { - out := new(SearchResponseV3) - err := grpc.Invoke(ctx, "/grpc.testingv3.SearchServiceV3/Search", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *searchServiceV3Client) StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchServiceV3_StreamingSearchClient, error) { - stream, err := grpc.NewClientStream(ctx, &_SearchServiceV3_serviceDesc.Streams[0], c.cc, "/grpc.testingv3.SearchServiceV3/StreamingSearch", opts...) - if err != nil { - return nil, err - } - x := &searchServiceV3StreamingSearchClient{stream} - return x, nil -} - -type SearchServiceV3_StreamingSearchClient interface { - Send(*SearchRequestV3) error - Recv() (*SearchResponseV3, error) - grpc.ClientStream -} - -type searchServiceV3StreamingSearchClient struct { - grpc.ClientStream -} - -func (x *searchServiceV3StreamingSearchClient) Send(m *SearchRequestV3) error { - return x.ClientStream.SendMsg(m) -} - -func (x *searchServiceV3StreamingSearchClient) Recv() (*SearchResponseV3, error) { - m := new(SearchResponseV3) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for SearchServiceV3 service - -type SearchServiceV3Server interface { - Search(context.Context, *SearchRequestV3) (*SearchResponseV3, error) - StreamingSearch(SearchServiceV3_StreamingSearchServer) error -} - -func RegisterSearchServiceV3Server(s *grpc.Server, srv SearchServiceV3Server) { - s.RegisterService(&_SearchServiceV3_serviceDesc, srv) -} - -func _SearchServiceV3_Search_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SearchRequestV3) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SearchServiceV3Server).Search(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testingv3.SearchServiceV3/Search", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SearchServiceV3Server).Search(ctx, req.(*SearchRequestV3)) - } - return interceptor(ctx, in, info, handler) -} - -func _SearchServiceV3_StreamingSearch_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(SearchServiceV3Server).StreamingSearch(&searchServiceV3StreamingSearchServer{stream}) -} - -type SearchServiceV3_StreamingSearchServer interface { - Send(*SearchResponseV3) error - Recv() (*SearchRequestV3, error) - grpc.ServerStream -} - -type searchServiceV3StreamingSearchServer struct { - grpc.ServerStream -} - -func (x *searchServiceV3StreamingSearchServer) Send(m *SearchResponseV3) error { - return x.ServerStream.SendMsg(m) -} - -func (x *searchServiceV3StreamingSearchServer) Recv() (*SearchRequestV3, error) { - m := new(SearchRequestV3) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _SearchServiceV3_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testingv3.SearchServiceV3", - HandlerType: (*SearchServiceV3Server)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Search", - Handler: _SearchServiceV3_Search_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingSearch", - Handler: _SearchServiceV3_StreamingSearch_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: fileDescriptor0, -} - -func init() { proto.RegisterFile("testv3.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 240 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x91, 0x41, 0x4b, 0xc3, 0x40, - 0x10, 0x85, 0x59, 0x83, 0xd1, 0x8e, 0x62, 0xcb, 0xe2, 0x21, 0xe4, 0x62, 0xe8, 0xa5, 0x39, 0x2d, - 0xd2, 0xfd, 0x05, 0x9e, 0xf5, 0xb4, 0x81, 0xe2, 0xb5, 0x86, 0x21, 0x2e, 0xc4, 0x64, 0x3b, 0x33, - 0x09, 0xf8, 0x7b, 0xfc, 0x13, 0xfe, 0x3c, 0x49, 0xd2, 0x08, 0x0a, 0xe2, 0xa5, 0xb7, 0x7d, 0x8f, - 0xf7, 0xbe, 0xe5, 0x31, 0x70, 0x2d, 0xc8, 0xd2, 0x5b, 0x13, 0xa8, 0x95, 0x56, 0xdf, 0x54, 0x14, - 0x4a, 0x33, 0x58, 0xbe, 0xa9, 0x7a, 0xbb, 0xfe, 0x50, 0xb0, 0x2a, 0x70, 0x4f, 0xe5, 0xab, 0x43, - 0x0e, 0x6d, 0xc3, 0xb8, 0xb3, 0xfa, 0x01, 0x2e, 0x08, 0xb9, 0xab, 0x85, 0x13, 0x95, 0x45, 0xf9, - 0xd5, 0x76, 0x63, 0x7e, 0xd6, 0xcc, 0xef, 0x8a, 0x71, 0x63, 0xde, 0xcd, 0xbd, 0xf4, 0x09, 0xe2, - 0xc9, 0xd2, 0x2b, 0x88, 0x3a, 0xaa, 0x13, 0x95, 0xa9, 0x7c, 0xe1, 0x86, 0xa7, 0xbe, 0x85, 0x73, - 0xf1, 0x52, 0x63, 0x72, 0x36, 0x7a, 0x93, 0xd0, 0x29, 0x5c, 0x72, 0xe3, 0x43, 0x40, 0xe1, 0x24, - 0xca, 0xa2, 0x7c, 0xe1, 0xbe, 0xf5, 0x7a, 0x03, 0xcb, 0xf9, 0xc7, 0x43, 0x87, 0x2c, 0x3b, 0x3b, - 0x40, 0x0e, 0x1d, 0xd2, 0xfb, 0x11, 0x3c, 0x89, 0xed, 0xa7, 0x9a, 0x93, 0x05, 0x52, 0xef, 0xcb, - 0x61, 0xcd, 0x23, 0xc4, 0x93, 0xa5, 0xef, 0xfe, 0x9a, 0x71, 0x84, 0xa6, 0xd9, 0x7f, 0x3b, 0xf5, - 0x33, 0x2c, 0x0b, 0x21, 0xdc, 0xbf, 0xf9, 0xa6, 0x3a, 0x19, 0x35, 0x57, 0xf7, 0xea, 0x25, 0x1e, - 0x0f, 0x64, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0xd4, 0xe6, 0xa0, 0xf9, 0xb0, 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_testingv3/testv3.proto b/vendor/google.golang.org/grpc/reflection/grpc_testingv3/testv3.proto deleted file mode 100644 index 1e175193e..000000000 --- a/vendor/google.golang.org/grpc/reflection/grpc_testingv3/testv3.proto +++ /dev/null @@ -1,21 +0,0 @@ -syntax = "proto3"; - -package grpc.testingv3; - -message SearchResponseV3 { - message Result { - string url = 1; - string title = 2; - repeated string snippets = 3; - } - repeated Result results = 1; -} - -message SearchRequestV3 { - string query = 1; -} - -service SearchServiceV3 { - rpc Search(SearchRequestV3) returns (SearchResponseV3); - rpc StreamingSearch(stream SearchRequestV3) returns (stream SearchResponseV3); -} diff --git a/vendor/google.golang.org/grpc/reflection/serverreflection.go b/vendor/google.golang.org/grpc/reflection/serverreflection.go deleted file mode 100644 index 19bfc51e5..000000000 --- a/vendor/google.golang.org/grpc/reflection/serverreflection.go +++ /dev/null @@ -1,398 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_reflection_v1alpha/reflection.proto - -/* -Package reflection implements server reflection service. - -The service implemented is defined in: -https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. - -To register server reflection on a gRPC server: - import "google.golang.org/grpc/reflection" - - s := grpc.NewServer() - pb.RegisterYourOwnServer(s, &server{}) - - // Register reflection service on gRPC server. - reflection.Register(s) - - s.Serve(lis) - -*/ -package reflection // import "google.golang.org/grpc/reflection" - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" - "io/ioutil" - "reflect" - "strings" - - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" -) - -type serverReflectionServer struct { - s *grpc.Server - // TODO add more cache if necessary - serviceInfo map[string]grpc.ServiceInfo // cache for s.GetServiceInfo() -} - -// Register registers the server reflection service on the given gRPC server. -func Register(s *grpc.Server) { - rpb.RegisterServerReflectionServer(s, &serverReflectionServer{ - s: s, - }) -} - -// protoMessage is used for type assertion on proto messages. -// Generated proto message implements function Descriptor(), but Descriptor() -// is not part of interface proto.Message. This interface is needed to -// call Descriptor(). -type protoMessage interface { - Descriptor() ([]byte, []int) -} - -// fileDescForType gets the file descriptor for the given type. -// The given type should be a proto message. -func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(protoMessage) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - enc, _ := m.Descriptor() - - return s.decodeFileDesc(enc) -} - -// decodeFileDesc does decompression and unmarshalling on the given -// file descriptor byte slice. -func (s *serverReflectionServer) decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { - raw, err := decompress(enc) - if err != nil { - return nil, fmt.Errorf("failed to decompress enc: %v", err) - } - - fd := new(dpb.FileDescriptorProto) - if err := proto.Unmarshal(raw, fd); err != nil { - return nil, fmt.Errorf("bad descriptor: %v", err) - } - return fd, nil -} - -// decompress does gzip decompression. -func decompress(b []byte) ([]byte, error) { - r, err := gzip.NewReader(bytes.NewReader(b)) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - out, err := ioutil.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - return out, nil -} - -func (s *serverReflectionServer) typeForName(name string) (reflect.Type, error) { - pt := proto.MessageType(name) - if pt == nil { - return nil, fmt.Errorf("unknown type: %q", name) - } - st := pt.Elem() - - return st, nil -} - -func (s *serverReflectionServer) fileDescContainingExtension(st reflect.Type, ext int32) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - - var extDesc *proto.ExtensionDesc - for id, desc := range proto.RegisteredExtensions(m) { - if id == ext { - extDesc = desc - break - } - } - - if extDesc == nil { - return nil, fmt.Errorf("failed to find registered extension for extension number %v", ext) - } - - return s.decodeFileDesc(proto.FileDescriptor(extDesc.Filename)) -} - -func (s *serverReflectionServer) allExtensionNumbersForType(st reflect.Type) ([]int32, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - - exts := proto.RegisteredExtensions(m) - out := make([]int32, 0, len(exts)) - for id := range exts { - out = append(out, id) - } - return out, nil -} - -// fileDescEncodingByFilename finds the file descriptor for given filename, -// does marshalling on it and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingByFilename(name string) ([]byte, error) { - enc := proto.FileDescriptor(name) - if enc == nil { - return nil, fmt.Errorf("unknown file: %v", name) - } - fd, err := s.decodeFileDesc(enc) - if err != nil { - return nil, err - } - return proto.Marshal(fd) -} - -// serviceMetadataForSymbol finds the metadata for name in s.serviceInfo. -// name should be a service name or a method name. -func (s *serverReflectionServer) serviceMetadataForSymbol(name string) (interface{}, error) { - if s.serviceInfo == nil { - s.serviceInfo = s.s.GetServiceInfo() - } - - // Check if it's a service name. - if info, ok := s.serviceInfo[name]; ok { - return info.Metadata, nil - } - - // Check if it's a method name. - pos := strings.LastIndex(name, ".") - // Not a valid method name. - if pos == -1 { - return nil, fmt.Errorf("unknown symbol: %v", name) - } - - info, ok := s.serviceInfo[name[:pos]] - // Substring before last "." is not a service name. - if !ok { - return nil, fmt.Errorf("unknown symbol: %v", name) - } - - // Search the method name in info.Methods. - var found bool - for _, m := range info.Methods { - if m.Name == name[pos+1:] { - found = true - break - } - } - if found { - return info.Metadata, nil - } - - return nil, fmt.Errorf("unknown symbol: %v", name) -} - -// parseMetadata finds the file descriptor bytes specified meta. -// For SupportPackageIsVersion4, m is the name of the proto file, we -// call proto.FileDescriptor to get the byte slice. -// For SupportPackageIsVersion3, m is a byte slice itself. -func parseMetadata(meta interface{}) ([]byte, bool) { - // Check if meta is the file name. - if fileNameForMeta, ok := meta.(string); ok { - return proto.FileDescriptor(fileNameForMeta), true - } - - // Check if meta is the byte slice. - if enc, ok := meta.([]byte); ok { - return enc, true - } - - return nil, false -} - -// fileDescEncodingContainingSymbol finds the file descriptor containing the given symbol, -// does marshalling on it and returns the marshalled result. -// The given symbol can be a type, a service or a method. -func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string) ([]byte, error) { - var ( - fd *dpb.FileDescriptorProto - ) - // Check if it's a type name. - if st, err := s.typeForName(name); err == nil { - fd, err = s.fileDescForType(st) - if err != nil { - return nil, err - } - } else { // Check if it's a service name or a method name. - meta, err := s.serviceMetadataForSymbol(name) - - // Metadata not found. - if err != nil { - return nil, err - } - - // Metadata not valid. - enc, ok := parseMetadata(meta) - if !ok { - return nil, fmt.Errorf("invalid file descriptor for symbol: %v", name) - } - - fd, err = s.decodeFileDesc(enc) - if err != nil { - return nil, err - } - } - - return proto.Marshal(fd) -} - -// fileDescEncodingContainingExtension finds the file descriptor containing given extension, -// does marshalling on it and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32) ([]byte, error) { - st, err := s.typeForName(typeName) - if err != nil { - return nil, err - } - fd, err := s.fileDescContainingExtension(st, extNum) - if err != nil { - return nil, err - } - return proto.Marshal(fd) -} - -// allExtensionNumbersForTypeName returns all extension numbers for the given type. -func (s *serverReflectionServer) allExtensionNumbersForTypeName(name string) ([]int32, error) { - st, err := s.typeForName(name) - if err != nil { - return nil, err - } - extNums, err := s.allExtensionNumbersForType(st) - if err != nil { - return nil, err - } - return extNums, nil -} - -// ServerReflectionInfo is the reflection service handler. -func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflection_ServerReflectionInfoServer) error { - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - out := &rpb.ServerReflectionResponse{ - ValidHost: in.Host, - OriginalRequest: in, - } - switch req := in.MessageRequest.(type) { - case *rpb.ServerReflectionRequest_FileByFilename: - b, err := s.fileDescEncodingByFilename(req.FileByFilename) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_FileContainingSymbol: - b, err := s.fileDescEncodingContainingSymbol(req.FileContainingSymbol) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_FileContainingExtension: - typeName := req.FileContainingExtension.ContainingType - extNum := req.FileContainingExtension.ExtensionNumber - b, err := s.fileDescEncodingContainingExtension(typeName, extNum) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_AllExtensionNumbersOfType: - extNums, err := s.allExtensionNumbersForTypeName(req.AllExtensionNumbersOfType) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_AllExtensionNumbersResponse{ - AllExtensionNumbersResponse: &rpb.ExtensionNumberResponse{ - BaseTypeName: req.AllExtensionNumbersOfType, - ExtensionNumber: extNums, - }, - } - } - case *rpb.ServerReflectionRequest_ListServices: - if s.serviceInfo == nil { - s.serviceInfo = s.s.GetServiceInfo() - } - serviceResponses := make([]*rpb.ServiceResponse, 0, len(s.serviceInfo)) - for n := range s.serviceInfo { - serviceResponses = append(serviceResponses, &rpb.ServiceResponse{ - Name: n, - }) - } - out.MessageResponse = &rpb.ServerReflectionResponse_ListServicesResponse{ - ListServicesResponse: &rpb.ListServiceResponse{ - Service: serviceResponses, - }, - } - default: - return grpc.Errorf(codes.InvalidArgument, "invalid MessageRequest: %v", in.MessageRequest) - } - - if err := stream.Send(out); err != nil { - return err - } - } -} diff --git a/vendor/google.golang.org/grpc/reflection/serverreflection_test.go b/vendor/google.golang.org/grpc/reflection/serverreflection_test.go deleted file mode 100644 index 908589085..000000000 --- a/vendor/google.golang.org/grpc/reflection/serverreflection_test.go +++ /dev/null @@ -1,520 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc -I grpc_testing --go_out=plugins=grpc:grpc_testing/ grpc_testing/proto2.proto grpc_testing/proto2_ext.proto grpc_testing/proto2_ext2.proto grpc_testing/test.proto - -// Note: grpc_testingv3/testv3.pb.go is not re-generated because it was -// intentionally generated by an older version of protoc-gen-go. - -package reflection - -import ( - "fmt" - "net" - "reflect" - "sort" - "testing" - - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "golang.org/x/net/context" - "google.golang.org/grpc" - rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" - pb "google.golang.org/grpc/reflection/grpc_testing" - pbv3 "google.golang.org/grpc/reflection/grpc_testingv3" -) - -var ( - s = &serverReflectionServer{} - // fileDescriptor of each test proto file. - fdTest *dpb.FileDescriptorProto - fdTestv3 *dpb.FileDescriptorProto - fdProto2 *dpb.FileDescriptorProto - fdProto2Ext *dpb.FileDescriptorProto - fdProto2Ext2 *dpb.FileDescriptorProto - // fileDescriptor marshalled. - fdTestByte []byte - fdTestv3Byte []byte - fdProto2Byte []byte - fdProto2ExtByte []byte - fdProto2Ext2Byte []byte -) - -func loadFileDesc(filename string) (*dpb.FileDescriptorProto, []byte) { - enc := proto.FileDescriptor(filename) - if enc == nil { - panic(fmt.Sprintf("failed to find fd for file: %v", filename)) - } - fd, err := s.decodeFileDesc(enc) - if err != nil { - panic(fmt.Sprintf("failed to decode enc: %v", err)) - } - b, err := proto.Marshal(fd) - if err != nil { - panic(fmt.Sprintf("failed to marshal fd: %v", err)) - } - return fd, b -} - -func init() { - fdTest, fdTestByte = loadFileDesc("test.proto") - fdTestv3, fdTestv3Byte = loadFileDesc("testv3.proto") - fdProto2, fdProto2Byte = loadFileDesc("proto2.proto") - fdProto2Ext, fdProto2ExtByte = loadFileDesc("proto2_ext.proto") - fdProto2Ext2, fdProto2Ext2Byte = loadFileDesc("proto2_ext2.proto") -} - -func TestFileDescForType(t *testing.T) { - for _, test := range []struct { - st reflect.Type - wantFd *dpb.FileDescriptorProto - }{ - {reflect.TypeOf(pb.SearchResponse_Result{}), fdTest}, - {reflect.TypeOf(pb.ToBeExtended{}), fdProto2}, - } { - fd, err := s.fileDescForType(test.st) - if err != nil || !proto.Equal(fd, test.wantFd) { - t.Errorf("fileDescForType(%q) = %q, %v, want %q, <nil>", test.st, fd, err, test.wantFd) - } - } -} - -func TestTypeForName(t *testing.T) { - for _, test := range []struct { - name string - want reflect.Type - }{ - {"grpc.testing.SearchResponse", reflect.TypeOf(pb.SearchResponse{})}, - } { - r, err := s.typeForName(test.name) - if err != nil || r != test.want { - t.Errorf("typeForName(%q) = %q, %v, want %q, <nil>", test.name, r, err, test.want) - } - } -} - -func TestTypeForNameNotFound(t *testing.T) { - for _, test := range []string{ - "grpc.testing.not_exiting", - } { - _, err := s.typeForName(test) - if err == nil { - t.Errorf("typeForName(%q) = _, %v, want _, <non-nil>", test, err) - } - } -} - -func TestFileDescContainingExtension(t *testing.T) { - for _, test := range []struct { - st reflect.Type - extNum int32 - want *dpb.FileDescriptorProto - }{ - {reflect.TypeOf(pb.ToBeExtended{}), 13, fdProto2Ext}, - {reflect.TypeOf(pb.ToBeExtended{}), 17, fdProto2Ext}, - {reflect.TypeOf(pb.ToBeExtended{}), 19, fdProto2Ext}, - {reflect.TypeOf(pb.ToBeExtended{}), 23, fdProto2Ext2}, - {reflect.TypeOf(pb.ToBeExtended{}), 29, fdProto2Ext2}, - } { - fd, err := s.fileDescContainingExtension(test.st, test.extNum) - if err != nil || !proto.Equal(fd, test.want) { - t.Errorf("fileDescContainingExtension(%q) = %q, %v, want %q, <nil>", test.st, fd, err, test.want) - } - } -} - -// intArray is used to sort []int32 -type intArray []int32 - -func (s intArray) Len() int { return len(s) } -func (s intArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s intArray) Less(i, j int) bool { return s[i] < s[j] } - -func TestAllExtensionNumbersForType(t *testing.T) { - for _, test := range []struct { - st reflect.Type - want []int32 - }{ - {reflect.TypeOf(pb.ToBeExtended{}), []int32{13, 17, 19, 23, 29}}, - } { - r, err := s.allExtensionNumbersForType(test.st) - sort.Sort(intArray(r)) - if err != nil || !reflect.DeepEqual(r, test.want) { - t.Errorf("allExtensionNumbersForType(%q) = %v, %v, want %v, <nil>", test.st, r, err, test.want) - } - } -} - -// Do end2end tests. - -type server struct{} - -func (s *server) Search(ctx context.Context, in *pb.SearchRequest) (*pb.SearchResponse, error) { - return &pb.SearchResponse{}, nil -} - -func (s *server) StreamingSearch(stream pb.SearchService_StreamingSearchServer) error { - return nil -} - -type serverV3 struct{} - -func (s *serverV3) Search(ctx context.Context, in *pbv3.SearchRequestV3) (*pbv3.SearchResponseV3, error) { - return &pbv3.SearchResponseV3{}, nil -} - -func (s *serverV3) StreamingSearch(stream pbv3.SearchServiceV3_StreamingSearchServer) error { - return nil -} - -func TestReflectionEnd2end(t *testing.T) { - // Start server. - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - s := grpc.NewServer() - pb.RegisterSearchServiceServer(s, &server{}) - pbv3.RegisterSearchServiceV3Server(s, &serverV3{}) - // Register reflection service on s. - Register(s) - go s.Serve(lis) - - // Create client. - conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure()) - if err != nil { - t.Fatalf("cannot connect to server: %v", err) - } - defer conn.Close() - - c := rpb.NewServerReflectionClient(conn) - stream, err := c.ServerReflectionInfo(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("cannot get ServerReflectionInfo: %v", err) - } - - testFileByFilename(t, stream) - testFileByFilenameError(t, stream) - testFileContainingSymbol(t, stream) - testFileContainingSymbolError(t, stream) - testFileContainingExtension(t, stream) - testFileContainingExtensionError(t, stream) - testAllExtensionNumbersOfType(t, stream) - testAllExtensionNumbersOfTypeError(t, stream) - testListServices(t, stream) - - s.Stop() -} - -func testFileByFilename(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - filename string - want []byte - }{ - {"test.proto", fdTestByte}, - {"proto2.proto", fdProto2Byte}, - {"proto2_ext.proto", fdProto2ExtByte}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileByFilename{ - FileByFilename: test.filename, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_FileDescriptorResponse: - if !reflect.DeepEqual(r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) { - t.Errorf("FileByFilename(%v)\nreceived: %q,\nwant: %q", test.filename, r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) - } - default: - t.Errorf("FileByFilename(%v) = %v, want type <ServerReflectionResponse_FileDescriptorResponse>", test.filename, r.MessageResponse) - } - } -} - -func testFileByFilenameError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []string{ - "test.poto", - "proo2.proto", - "proto2_et.proto", - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileByFilename{ - FileByFilename: test, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("FileByFilename(%v) = %v, want type <ServerReflectionResponse_ErrorResponse>", test, r.MessageResponse) - } - } -} - -func testFileContainingSymbol(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - symbol string - want []byte - }{ - {"grpc.testing.SearchService", fdTestByte}, - {"grpc.testing.SearchService.Search", fdTestByte}, - {"grpc.testing.SearchService.StreamingSearch", fdTestByte}, - {"grpc.testing.SearchResponse", fdTestByte}, - {"grpc.testing.ToBeExtended", fdProto2Byte}, - // Test support package v3. - {"grpc.testingv3.SearchServiceV3", fdTestv3Byte}, - {"grpc.testingv3.SearchServiceV3.Search", fdTestv3Byte}, - {"grpc.testingv3.SearchServiceV3.StreamingSearch", fdTestv3Byte}, - {"grpc.testingv3.SearchResponseV3", fdTestv3Byte}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingSymbol{ - FileContainingSymbol: test.symbol, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_FileDescriptorResponse: - if !reflect.DeepEqual(r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) { - t.Errorf("FileContainingSymbol(%v)\nreceived: %q,\nwant: %q", test.symbol, r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) - } - default: - t.Errorf("FileContainingSymbol(%v) = %v, want type <ServerReflectionResponse_FileDescriptorResponse>", test.symbol, r.MessageResponse) - } - } -} - -func testFileContainingSymbolError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []string{ - "grpc.testing.SerchService", - "grpc.testing.SearchService.SearchE", - "grpc.tesing.SearchResponse", - "gpc.testing.ToBeExtended", - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingSymbol{ - FileContainingSymbol: test, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("FileContainingSymbol(%v) = %v, want type <ServerReflectionResponse_ErrorResponse>", test, r.MessageResponse) - } - } -} - -func testFileContainingExtension(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - typeName string - extNum int32 - want []byte - }{ - {"grpc.testing.ToBeExtended", 13, fdProto2ExtByte}, - {"grpc.testing.ToBeExtended", 17, fdProto2ExtByte}, - {"grpc.testing.ToBeExtended", 19, fdProto2ExtByte}, - {"grpc.testing.ToBeExtended", 23, fdProto2Ext2Byte}, - {"grpc.testing.ToBeExtended", 29, fdProto2Ext2Byte}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingExtension{ - FileContainingExtension: &rpb.ExtensionRequest{ - ContainingType: test.typeName, - ExtensionNumber: test.extNum, - }, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_FileDescriptorResponse: - if !reflect.DeepEqual(r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) { - t.Errorf("FileContainingExtension(%v, %v)\nreceived: %q,\nwant: %q", test.typeName, test.extNum, r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) - } - default: - t.Errorf("FileContainingExtension(%v, %v) = %v, want type <ServerReflectionResponse_FileDescriptorResponse>", test.typeName, test.extNum, r.MessageResponse) - } - } -} - -func testFileContainingExtensionError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - typeName string - extNum int32 - }{ - {"grpc.testing.ToBExtended", 17}, - {"grpc.testing.ToBeExtended", 15}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingExtension{ - FileContainingExtension: &rpb.ExtensionRequest{ - ContainingType: test.typeName, - ExtensionNumber: test.extNum, - }, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("FileContainingExtension(%v, %v) = %v, want type <ServerReflectionResponse_FileDescriptorResponse>", test.typeName, test.extNum, r.MessageResponse) - } - } -} - -func testAllExtensionNumbersOfType(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - typeName string - want []int32 - }{ - {"grpc.testing.ToBeExtended", []int32{13, 17, 19, 23, 29}}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_AllExtensionNumbersOfType{ - AllExtensionNumbersOfType: test.typeName, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_AllExtensionNumbersResponse: - extNum := r.GetAllExtensionNumbersResponse().ExtensionNumber - sort.Sort(intArray(extNum)) - if r.GetAllExtensionNumbersResponse().BaseTypeName != test.typeName || - !reflect.DeepEqual(extNum, test.want) { - t.Errorf("AllExtensionNumbersOfType(%v)\nreceived: %v,\nwant: {%q %v}", r.GetAllExtensionNumbersResponse(), test.typeName, test.typeName, test.want) - } - default: - t.Errorf("AllExtensionNumbersOfType(%v) = %v, want type <ServerReflectionResponse_AllExtensionNumbersResponse>", test.typeName, r.MessageResponse) - } - } -} - -func testAllExtensionNumbersOfTypeError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []string{ - "grpc.testing.ToBeExtendedE", - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_AllExtensionNumbersOfType{ - AllExtensionNumbersOfType: test, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("AllExtensionNumbersOfType(%v) = %v, want type <ServerReflectionResponse_ErrorResponse>", test, r.MessageResponse) - } - } -} - -func testListServices(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_ListServices{}, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ListServicesResponse: - services := r.GetListServicesResponse().Service - want := []string{ - "grpc.testingv3.SearchServiceV3", - "grpc.testing.SearchService", - "grpc.reflection.v1alpha.ServerReflection", - } - // Compare service names in response with want. - if len(services) != len(want) { - t.Errorf("= %v, want service names: %v", services, want) - } - m := make(map[string]int) - for _, e := range services { - m[e.Name]++ - } - for _, e := range want { - if m[e] > 0 { - m[e]-- - continue - } - t.Errorf("ListService\nreceived: %v,\nwant: %q", services, want) - } - default: - t.Errorf("ListServices = %v, want type <ServerReflectionResponse_ListServicesResponse>", r.MessageResponse) - } -} diff --git a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go index f31bbb60f..a543a709a 100644 --- a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go +++ b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go @@ -50,9 +50,7 @@ const ( txtAttribute = "grpc_config=" ) -var ( - errMissingAddr = errors.New("missing address") -) +var errMissingAddr = errors.New("missing address") // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. func NewBuilder() resolver.Builder { diff --git a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver_test.go b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver_test.go index 590791168..41a9ecb91 100644 --- a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver_test.go +++ b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver_test.go @@ -150,9 +150,8 @@ func div(b []byte) []string { // resolver functionality, with scfs as the input and scs used for validation of // the output. For scfs[3], it corresponds to empty service config, since there // isn't a matched choice. -var ( - scfs = []string{ - `[ +var scfs = []string{ + `[ { "clientLanguage": [ "CPP", @@ -242,7 +241,7 @@ var ( } } ]`, - `[ + `[ { "clientLanguage": [ "CPP", @@ -335,7 +334,7 @@ var ( } } ]`, - `[ + `[ { "clientLanguage": [ "CPP", @@ -434,7 +433,7 @@ var ( } } ]`, - `[ + `[ { "clientLanguage": [ "CPP", @@ -489,13 +488,11 @@ var ( } } ]`, - } -) +} // scs contains an array of service config string in JSON format. -var ( - scs = []string{ - `{ +var scs = []string{ + `{ "methodConfig": [ { "name": [ @@ -508,7 +505,7 @@ var ( } ] }`, - `{ + `{ "methodConfig": [ { "name": [ @@ -524,7 +521,7 @@ var ( } ] }`, - `{ + `{ "loadBalancingPolicy": "round_robin", "methodConfig": [ { @@ -546,8 +543,7 @@ var ( } ] }`, - } -) +} // scLookupTbl is a set, which contains targets that have service config. Target // not in this set should not have service config. diff --git a/vendor/google.golang.org/grpc/resolver/dns/go17_test.go b/vendor/google.golang.org/grpc/resolver/dns/go17_test.go index 07fdcb03f..21eaa8885 100644 --- a/vendor/google.golang.org/grpc/resolver/dns/go17_test.go +++ b/vendor/google.golang.org/grpc/resolver/dns/go17_test.go @@ -27,9 +27,7 @@ import ( "golang.org/x/net/context" ) -var ( - errForInvalidTarget = fmt.Errorf("invalid target address [2001:db8:a0b:12f0::1, error info: missing ']' in address [2001:db8:a0b:12f0::1:443") -) +var errForInvalidTarget = fmt.Errorf("invalid target address [2001:db8:a0b:12f0::1, error info: missing ']' in address [2001:db8:a0b:12f0::1:443") func replaceNetFunc() func() { oldLookupHost := lookupHost diff --git a/vendor/google.golang.org/grpc/resolver/dns/go18_test.go b/vendor/google.golang.org/grpc/resolver/dns/go18_test.go index 8e016709c..b0149c867 100644 --- a/vendor/google.golang.org/grpc/resolver/dns/go18_test.go +++ b/vendor/google.golang.org/grpc/resolver/dns/go18_test.go @@ -26,9 +26,7 @@ import ( "net" ) -var ( - errForInvalidTarget = fmt.Errorf("invalid target address [2001:db8:a0b:12f0::1, error info: address [2001:db8:a0b:12f0::1:443: missing ']' in address") -) +var errForInvalidTarget = fmt.Errorf("invalid target address [2001:db8:a0b:12f0::1, error info: address [2001:db8:a0b:12f0::1:443: missing ']' in address") func replaceNetFunc() func() { oldLookupHost := lookupHost diff --git a/vendor/google.golang.org/grpc/resolver/manual/manual.go b/vendor/google.golang.org/grpc/resolver/manual/manual.go deleted file mode 100644 index de2fb25b5..000000000 --- a/vendor/google.golang.org/grpc/resolver/manual/manual.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package manual contains a resolver for testing purpose only. -package manual - -import ( - "strconv" - "time" - - "google.golang.org/grpc/resolver" -) - -// NewBuilderWithScheme creates a new test resolver builder with the given scheme. -func NewBuilderWithScheme(scheme string) *Resolver { - return &Resolver{ - scheme: scheme, - } -} - -// Resolver is also a resolver builder. -// It's build() function always returns itself. -type Resolver struct { - scheme string - - // Fields actually belong to the resolver. - cc resolver.ClientConn -} - -// Build returns itself for Resolver, because it's both a builder and a resolver. -func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { - r.cc = cc - return r, nil -} - -// Scheme returns the test scheme. -func (r *Resolver) Scheme() string { - return r.scheme -} - -// ResolveNow is a noop for Resolver. -func (*Resolver) ResolveNow(o resolver.ResolveNowOption) {} - -// Close is a noop for Resolver. -func (*Resolver) Close() {} - -// NewAddress calls cc.NewAddress. -func (r *Resolver) NewAddress(addrs []resolver.Address) { - r.cc.NewAddress(addrs) -} - -// NewServiceConfig calls cc.NewServiceConfig. -func (r *Resolver) NewServiceConfig(sc string) { - r.cc.NewServiceConfig(sc) -} - -// GenerateAndRegisterManualResolver generates a random scheme and a Resolver -// with it. It also regieter this Resolver. -// It returns the Resolver and a cleanup function to unregister it. -func GenerateAndRegisterManualResolver() (*Resolver, func()) { - scheme := strconv.FormatInt(time.Now().UnixNano(), 36) - r := NewBuilderWithScheme(scheme) - resolver.Register(r) - return r, func() { resolver.UnregisterForTesting(scheme) } -} diff --git a/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go b/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go index 4d4420aa4..b76010d74 100644 --- a/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go +++ b/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go @@ -17,8 +17,7 @@ */ // Package passthrough implements a pass-through resolver. It sends the target -// name without scheme back to gRPC as resolved address. It's for gRPC internal -// test only. +// name without scheme back to gRPC as resolved address. package passthrough import "google.golang.org/grpc/resolver" diff --git a/vendor/google.golang.org/grpc/resolver/resolver.go b/vendor/google.golang.org/grpc/resolver/resolver.go index 49307e8fe..0dd887fa5 100644 --- a/vendor/google.golang.org/grpc/resolver/resolver.go +++ b/vendor/google.golang.org/grpc/resolver/resolver.go @@ -24,7 +24,7 @@ var ( // m is a map from scheme to resolver builder. m = make(map[string]Builder) // defaultScheme is the default scheme to use. - defaultScheme string + defaultScheme = "passthrough" ) // TODO(bar) install dns resolver in init(){}. diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go index 7d53964d0..c07e174a8 100644 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go +++ b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go @@ -19,6 +19,7 @@ package grpc import ( + "fmt" "strings" "google.golang.org/grpc/grpclog" @@ -36,39 +37,36 @@ type ccResolverWrapper struct { } // split2 returns the values from strings.SplitN(s, sep, 2). -// If sep is not found, it returns "", s instead. -func split2(s, sep string) (string, string) { +// If sep is not found, it returns ("", s, false) instead. +func split2(s, sep string) (string, string, bool) { spl := strings.SplitN(s, sep, 2) if len(spl) < 2 { - return "", s + return "", "", false } - return spl[0], spl[1] + return spl[0], spl[1], true } // parseTarget splits target into a struct containing scheme, authority and // endpoint. func parseTarget(target string) (ret resolver.Target) { - ret.Scheme, ret.Endpoint = split2(target, "://") - ret.Authority, ret.Endpoint = split2(ret.Endpoint, "/") + var ok bool + ret.Scheme, ret.Endpoint, ok = split2(target, "://") + if !ok { + return resolver.Target{Endpoint: target} + } + ret.Authority, ret.Endpoint, _ = split2(ret.Endpoint, "/") return ret } // newCCResolverWrapper parses cc.target for scheme and gets the resolver // builder for this scheme. It then builds the resolver and starts the // monitoring goroutine for it. -// -// This function could return nil, nil, in tests for old behaviors. -// TODO(bar) never return nil, nil when DNS becomes the default resolver. func newCCResolverWrapper(cc *ClientConn) (*ccResolverWrapper, error) { - target := parseTarget(cc.target) - grpclog.Infof("dialing to target with scheme: %q", target.Scheme) + grpclog.Infof("dialing to target with scheme: %q", cc.parsedTarget.Scheme) - rb := resolver.Get(target.Scheme) + rb := resolver.Get(cc.parsedTarget.Scheme) if rb == nil { - // TODO(bar) return error when DNS becomes the default (implemented and - // registered by DNS package). - grpclog.Infof("could not get resolver for scheme: %q", target.Scheme) - return nil, nil + return nil, fmt.Errorf("could not get resolver for scheme: %q", cc.parsedTarget.Scheme) } ccr := &ccResolverWrapper{ @@ -79,7 +77,7 @@ func newCCResolverWrapper(cc *ClientConn) (*ccResolverWrapper, error) { } var err error - ccr.resolver, err = rb.Build(target, ccr, resolver.BuildOption{}) + ccr.resolver, err = rb.Build(cc.parsedTarget, ccr, resolver.BuildOption{}) if err != nil { return nil, err } @@ -100,14 +98,21 @@ func (ccr *ccResolverWrapper) watcher() { select { case addrs := <-ccr.addrCh: - grpclog.Infof("ccResolverWrapper: sending new addresses to balancer wrapper: %v", addrs) - // TODO(bar switching) this should never be nil. Pickfirst should be default. - if ccr.cc.balancerWrapper != nil { - // TODO(bar switching) create balancer if it's nil? - ccr.cc.balancerWrapper.handleResolvedAddrs(addrs, nil) + select { + case <-ccr.done: + return + default: } + grpclog.Infof("ccResolverWrapper: sending new addresses to cc: %v", addrs) + ccr.cc.handleResolvedAddrs(addrs, nil) case sc := <-ccr.scCh: + select { + case <-ccr.done: + return + default: + } grpclog.Infof("ccResolverWrapper: got new service config: %v", sc) + ccr.cc.handleServiceConfig(sc) case <-ccr.done: return } diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go index 024942301..d857f4370 100644 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go +++ b/vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go @@ -34,14 +34,46 @@ func TestParseTarget(t *testing.T) { {"a", "", "b"}, {"", "a", "b"}, {"a", "b", "c"}, - {"dns", "a.server.com", "google.com"}, + {"dns", "", "google.com"}, {"dns", "a.server.com", "google.com"}, {"dns", "a.server.com", "google.com/?a=b"}, + {"", "", "/unix/socket/address"}, } { str := test.Scheme + "://" + test.Authority + "/" + test.Endpoint got := parseTarget(str) if got != test { - t.Errorf("parseTarget(%q) = %v, want %v", str, got, test) + t.Errorf("parseTarget(%q) = %+v, want %+v", str, got, test) + } + } +} + +func TestParseTargetString(t *testing.T) { + for _, test := range []struct { + targetStr string + want resolver.Target + }{ + {"", resolver.Target{"", "", ""}}, + {"://", resolver.Target{"", "", ""}}, + {":///", resolver.Target{"", "", ""}}, + {"a:///", resolver.Target{"a", "", ""}}, + {"://a/", resolver.Target{"", "a", ""}}, + {":///a", resolver.Target{"", "", "a"}}, + {"a://b/", resolver.Target{"a", "b", ""}}, + {"a:///b", resolver.Target{"a", "", "b"}}, + {"://a/b", resolver.Target{"", "a", "b"}}, + {"a://b/c", resolver.Target{"a", "b", "c"}}, + {"dns:///google.com", resolver.Target{"dns", "", "google.com"}}, + {"dns://a.server.com/google.com", resolver.Target{"dns", "a.server.com", "google.com"}}, + {"dns://a.server.com/google.com/?a=b", resolver.Target{"dns", "a.server.com", "google.com/?a=b"}}, + + {"/", resolver.Target{"", "", "/"}}, + {"google.com", resolver.Target{"", "", "google.com"}}, + {"google.com/?a=b", resolver.Target{"", "", "google.com/?a=b"}}, + {"/unix/socket/address", resolver.Target{"", "", "/unix/socket/address"}}, + } { + got := parseTarget(test.targetStr) + if got != test.want { + t.Errorf("parseTarget(%q) = %+v, want %+v", test.targetStr, got, test.want) } } } diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index e71c77bb6..1881d3dd6 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -21,18 +21,17 @@ package grpc import ( "bytes" "compress/gzip" - stdctx "context" "encoding/binary" "io" "io/ioutil" "math" - "os" "sync" "time" "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/encoding" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" @@ -124,6 +123,7 @@ func (d *gzipDecompressor) Type() string { // callInfo contains all related configuration and information about an RPC. type callInfo struct { + compressorType string failFast bool headerMD metadata.MD trailerMD metadata.MD @@ -195,12 +195,15 @@ func Peer(peer *peer.Peer) CallOption { } // FailFast configures the action to take when an RPC is attempted on broken -// connections or unreachable servers. If failfast is true, the RPC will fail +// connections or unreachable servers. If failFast is true, the RPC will fail // immediately. Otherwise, the RPC client will block the call until a -// connection is available (or the call is canceled or times out) and will retry -// the call if it fails due to a transient error. Please refer to +// connection is available (or the call is canceled or times out) and will +// retry the call if it fails due to a transient error. gRPC will not retry if +// data was written to the wire unless the server indicates it did not process +// the data. Please refer to // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md. -// Note: failFast is default to true. +// +// By default, RPCs are "Fail Fast". func FailFast(failFast bool) CallOption { return beforeCall(func(c *callInfo) error { c.failFast = failFast @@ -233,6 +236,18 @@ func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption { }) } +// UseCompressor returns a CallOption which sets the compressor used when +// sending the request. If WithCompressor is also set, UseCompressor has +// higher priority. +// +// This API is EXPERIMENTAL. +func UseCompressor(name string) CallOption { + return beforeCall(func(c *callInfo) error { + c.compressorType = name + return nil + }) +} + // The format of the payload: compressed or not? type payloadFormat uint8 @@ -277,7 +292,10 @@ func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byt if length == 0 { return pf, nil, nil } - if length > uint32(maxReceiveMessageSize) { + if int64(length) > int64(maxInt) { + return 0, nil, Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt) + } + if int(length) > maxReceiveMessageSize { return 0, nil, Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize) } // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead @@ -294,13 +312,16 @@ func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byt // encode serializes msg and returns a buffer of message header and a buffer of msg. // If msg is nil, it generates the message header and an empty msg buffer. -func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayload *stats.OutPayload) ([]byte, []byte, error) { - var b []byte +// TODO(ddyihai): eliminate extra Compressor parameter. +func encode(c Codec, msg interface{}, cp Compressor, outPayload *stats.OutPayload, compressor encoding.Compressor) ([]byte, []byte, error) { + var ( + b []byte + cbuf *bytes.Buffer + ) const ( payloadLen = 1 sizeLen = 4 ) - if msg != nil { var err error b, err = c.Marshal(msg) @@ -313,24 +334,35 @@ func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayl outPayload.Data = b outPayload.Length = len(b) } - if cp != nil { - if err := cp.Do(cbuf, b); err != nil { - return nil, nil, Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) + if compressor != nil || cp != nil { + cbuf = new(bytes.Buffer) + // Has compressor, check Compressor is set by UseCompressor first. + if compressor != nil { + z, _ := compressor.Compress(cbuf) + if _, err := z.Write(b); err != nil { + return nil, nil, Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) + } + z.Close() + } else { + // If Compressor is not set by UseCompressor, use default Compressor + if err := cp.Do(cbuf, b); err != nil { + return nil, nil, Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) + } } b = cbuf.Bytes() } } - if uint(len(b)) > math.MaxUint32 { return nil, nil, Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b)) } bufHeader := make([]byte, payloadLen+sizeLen) - if cp == nil { - bufHeader[0] = byte(compressionNone) - } else { + if compressor != nil || cp != nil { bufHeader[0] = byte(compressionMade) + } else { + bufHeader[0] = byte(compressionNone) } + // Write length of b into buf binary.BigEndian.PutUint32(bufHeader[payloadLen:], uint32(len(b))) if outPayload != nil { @@ -339,20 +371,26 @@ func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayl return bufHeader, b, nil } -func checkRecvPayload(pf payloadFormat, recvCompress string, dc Decompressor) error { +func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status { switch pf { case compressionNone: case compressionMade: - if dc == nil || recvCompress != dc.Type() { - return Errorf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) + if recvCompress == "" || recvCompress == encoding.Identity { + return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding") + } + if !haveCompressor { + return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) } default: - return Errorf(codes.Internal, "grpc: received unexpected payload format %d", pf) + return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf) } return nil } -func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload) error { +// For the two compressor parameters, both should not be set, but if they are, +// dc takes precedence over compressor. +// TODO(dfawley): wrap the old compressor/decompressor using the new API? +func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload, compressor encoding.Compressor) error { pf, d, err := p.recvMsg(maxReceiveMessageSize) if err != nil { return err @@ -360,13 +398,28 @@ func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{ if inPayload != nil { inPayload.WireLength = len(d) } - if err := checkRecvPayload(pf, s.RecvCompress(), dc); err != nil { - return err + + if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil { + return st.Err() } + if pf == compressionMade { - d, err = dc.Do(bytes.NewReader(d)) - if err != nil { - return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor, + // use this decompressor as the default. + if dc != nil { + d, err = dc.Do(bytes.NewReader(d)) + if err != nil { + return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } + } else { + dcReader, err := compressor.Decompress(bytes.NewReader(d)) + if err != nil { + return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } + d, err = ioutil.ReadAll(dcReader) + if err != nil { + return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } } } if len(d) > maxReceiveMessageSize { @@ -412,57 +465,6 @@ func updateRPCInfoInContext(ctx context.Context, s rpcInfo) { return } -// toRPCErr converts an error into an error from the status package. -func toRPCErr(err error) error { - if _, ok := status.FromError(err); ok { - return err - } - switch e := err.(type) { - case transport.StreamError: - return status.Error(e.Code, e.Desc) - case transport.ConnectionError: - return status.Error(codes.Unavailable, e.Desc) - default: - switch err { - case context.DeadlineExceeded, stdctx.DeadlineExceeded: - return status.Error(codes.DeadlineExceeded, err.Error()) - case context.Canceled, stdctx.Canceled: - return status.Error(codes.Canceled, err.Error()) - case ErrClientConnClosing: - return status.Error(codes.FailedPrecondition, err.Error()) - } - } - return status.Error(codes.Unknown, err.Error()) -} - -// convertCode converts a standard Go error into its canonical code. Note that -// this is only used to translate the error returned by the server applications. -func convertCode(err error) codes.Code { - switch err { - case nil: - return codes.OK - case io.EOF: - return codes.OutOfRange - case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF: - return codes.FailedPrecondition - case os.ErrInvalid: - return codes.InvalidArgument - case context.Canceled, stdctx.Canceled: - return codes.Canceled - case context.DeadlineExceeded, stdctx.DeadlineExceeded: - return codes.DeadlineExceeded - } - switch { - case os.IsExist(err): - return codes.AlreadyExists - case os.IsNotExist(err): - return codes.NotFound - case os.IsPermission(err): - return codes.PermissionDenied - } - return codes.Unknown -} - // Code returns the error code for err if it was produced by the rpc system. // Otherwise, it returns codes.Unknown. // @@ -493,80 +495,21 @@ func Errorf(c codes.Code, format string, a ...interface{}) error { return status.Errorf(c, format, a...) } -// MethodConfig defines the configuration recommended by the service providers for a -// particular method. -// This is EXPERIMENTAL and subject to change. -type MethodConfig struct { - // WaitForReady indicates whether RPCs sent to this method should wait until - // the connection is ready by default (!failfast). The value specified via the - // gRPC client API will override the value set here. - WaitForReady *bool - // Timeout is the default timeout for RPCs sent to this method. The actual - // deadline used will be the minimum of the value specified here and the value - // set by the application via the gRPC client API. If either one is not set, - // then the other will be used. If neither is set, then the RPC has no deadline. - Timeout *time.Duration - // MaxReqSize is the maximum allowed payload size for an individual request in a - // stream (client->server) in bytes. The size which is measured is the serialized - // payload after per-message compression (but before stream compression) in bytes. - // The actual value used is the minimum of the value specified here and the value set - // by the application via the gRPC client API. If either one is not set, then the other - // will be used. If neither is set, then the built-in default is used. - MaxReqSize *int - // MaxRespSize is the maximum allowed payload size for an individual response in a - // stream (server->client) in bytes. - MaxRespSize *int -} - -// ServiceConfig is provided by the service provider and contains parameters for how -// clients that connect to the service should behave. -// This is EXPERIMENTAL and subject to change. -type ServiceConfig struct { - // LB is the load balancer the service providers recommends. The balancer specified - // via grpc.WithBalancer will override this. - LB Balancer - // Methods contains a map for the methods in this service. - // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig. - // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists. - // Otherwise, the method has no MethodConfig to use. - Methods map[string]MethodConfig -} - -func min(a, b *int) *int { - if *a < *b { - return a - } - return b -} - -func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { - if mcMax == nil && doptMax == nil { - return &defaultVal - } - if mcMax != nil && doptMax != nil { - return min(mcMax, doptMax) - } - if mcMax != nil { - return mcMax - } - return doptMax -} - -// SupportPackageIsVersion3 is referenced from generated protocol buffer files. -// The latest support package version is 4. -// SupportPackageIsVersion3 is kept for compatibility. It will be removed in the -// next support package version update. -const SupportPackageIsVersion3 = true - -// SupportPackageIsVersion4 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the grpc package. +// The SupportPackageIsVersion variables are referenced from generated protocol +// buffer files to ensure compatibility with the gRPC version used. The latest +// support package version is 5. // -// This constant may be renamed in the future if a change in the generated code -// requires a synchronised update of grpc-go and protoc-gen-go. This constant -// should not be referenced from any other code. -const SupportPackageIsVersion4 = true +// Older versions are kept for compatibility. They may be removed if +// compatibility cannot be maintained. +// +// These constants should not be referenced from any other code. +const ( + SupportPackageIsVersion3 = true + SupportPackageIsVersion4 = true + SupportPackageIsVersion5 = true +) // Version is the current grpc version. -const Version = "1.7.2" +const Version = "1.8.2" const grpcUA = "grpc-go/" + Version diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index 7c882dbe6..e9737fc49 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -32,11 +32,14 @@ import ( "sync" "time" + "io/ioutil" + "golang.org/x/net/context" "golang.org/x/net/http2" "golang.org/x/net/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/encoding" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal" "google.golang.org/grpc/keepalive" @@ -96,6 +99,11 @@ type Server struct { cv *sync.Cond m map[string]*service // service name -> service info events trace.EventLog + + quit chan struct{} + done chan struct{} + quitOnce sync.Once + doneOnce sync.Once } type options struct { @@ -118,11 +126,13 @@ type options struct { initialConnWindowSize int32 writeBufferSize int readBufferSize int + connectionTimeout time.Duration } var defaultServerOptions = options{ maxReceiveMessageSize: defaultServerMaxReceiveMessageSize, maxSendMessageSize: defaultServerMaxSendMessageSize, + connectionTimeout: 120 * time.Second, } // A ServerOption sets options such as credentials, codec and keepalive parameters, etc. @@ -181,14 +191,24 @@ func CustomCodec(codec Codec) ServerOption { } } -// RPCCompressor returns a ServerOption that sets a compressor for outbound messages. +// RPCCompressor returns a ServerOption that sets a compressor for outbound +// messages. For backward compatibility, all outbound messages will be sent +// using this compressor, regardless of incoming message compression. By +// default, server messages will be sent using the same compressor with which +// request messages were sent. +// +// Deprecated: use encoding.RegisterCompressor instead. func RPCCompressor(cp Compressor) ServerOption { return func(o *options) { o.cp = cp } } -// RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages. +// RPCDecompressor returns a ServerOption that sets a decompressor for inbound +// messages. It has higher priority than decompressors registered via +// encoding.RegisterCompressor. +// +// Deprecated: use encoding.RegisterCompressor instead. func RPCDecompressor(dc Decompressor) ServerOption { return func(o *options) { o.dc = dc @@ -291,6 +311,18 @@ func UnknownServiceHandler(streamHandler StreamHandler) ServerOption { } } +// ConnectionTimeout returns a ServerOption that sets the timeout for +// connection establishment (up to and including HTTP/2 handshaking) for all +// new connections. If this is not set, the default is 120 seconds. A zero or +// negative value will result in an immediate timeout. +// +// This API is EXPERIMENTAL. +func ConnectionTimeout(d time.Duration) ServerOption { + return func(o *options) { + o.connectionTimeout = d + } +} + // NewServer creates a gRPC server which has no service registered and has not // started to accept requests yet. func NewServer(opt ...ServerOption) *Server { @@ -307,6 +339,8 @@ func NewServer(opt ...ServerOption) *Server { opts: opts, conns: make(map[io.Closer]bool), m: make(map[string]*service), + quit: make(chan struct{}), + done: make(chan struct{}), } s.cv = sync.NewCond(&s.mu) s.ctx, s.cancel = context.WithCancel(context.Background()) @@ -418,11 +452,9 @@ func (s *Server) GetServiceInfo() map[string]ServiceInfo { return ret } -var ( - // ErrServerStopped indicates that the operation is now illegal because of - // the server being stopped. - ErrServerStopped = errors.New("grpc: the server has been stopped") -) +// ErrServerStopped indicates that the operation is now illegal because of +// the server being stopped. +var ErrServerStopped = errors.New("grpc: the server has been stopped") func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { if s.opts.creds == nil { @@ -436,7 +468,7 @@ func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credenti // read gRPC requests and then call the registered handlers to reply to them. // Serve returns when lis.Accept fails with fatal errors. lis will be closed when // this method returns. -// Serve always returns non-nil error. +// Serve will return a non-nil error unless Stop or GracefulStop is called. func (s *Server) Serve(lis net.Listener) error { s.mu.Lock() s.printf("serving") @@ -487,6 +519,14 @@ func (s *Server) Serve(lis net.Listener) error { s.mu.Lock() s.printf("done serving; Accept = %v", err) s.mu.Unlock() + + // If Stop or GracefulStop is called, block until they are done and return nil + select { + case <-s.quit: + <-s.done + return nil + default: + } return err } tempDelay = 0 @@ -499,16 +539,18 @@ func (s *Server) Serve(lis net.Listener) error { // handleRawConn is run in its own goroutine and handles a just-accepted // connection that has not had any I/O performed on it yet. func (s *Server) handleRawConn(rawConn net.Conn) { + rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout)) conn, authInfo, err := s.useTransportAuthenticator(rawConn) if err != nil { s.mu.Lock() s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) s.mu.Unlock() grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) - // If serverHandShake returns ErrConnDispatched, keep rawConn open. + // If serverHandshake returns ErrConnDispatched, keep rawConn open. if err != credentials.ErrConnDispatched { rawConn.Close() } + rawConn.SetDeadline(time.Time{}) return } @@ -521,18 +563,21 @@ func (s *Server) handleRawConn(rawConn net.Conn) { s.mu.Unlock() if s.opts.useHandlerImpl { + rawConn.SetDeadline(time.Time{}) s.serveUsingHandler(conn) } else { - s.serveHTTP2Transport(conn, authInfo) + st := s.newHTTP2Transport(conn, authInfo) + if st == nil { + return + } + rawConn.SetDeadline(time.Time{}) + s.serveStreams(st) } } -// serveHTTP2Transport sets up a http/2 transport (using the -// gRPC http2 server transport in transport/http2_server.go) and -// serves streams on it. -// This is run in its own goroutine (it does network I/O in -// transport.NewServerTransport). -func (s *Server) serveHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) { +// newHTTP2Transport sets up a http/2 transport (using the +// gRPC http2 server transport in transport/http2_server.go). +func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) transport.ServerTransport { config := &transport.ServerConfig{ MaxStreams: s.opts.maxConcurrentStreams, AuthInfo: authInfo, @@ -552,13 +597,13 @@ func (s *Server) serveHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) s.mu.Unlock() c.Close() grpclog.Warningln("grpc: Server.Serve failed to create ServerTransport: ", err) - return + return nil } if !s.addConn(st) { st.Close() - return + return nil } - s.serveStreams(st) + return st } func (s *Server) serveStreams(st transport.ServerTransport) { @@ -686,18 +731,14 @@ func (s *Server) removeConn(c io.Closer) { } } -func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error { +func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { var ( - cbuf *bytes.Buffer outPayload *stats.OutPayload ) - if cp != nil { - cbuf = new(bytes.Buffer) - } if s.opts.statsHandler != nil { outPayload = &stats.OutPayload{} } - hdr, data, err := encode(s.opts.codec, msg, cp, cbuf, outPayload) + hdr, data, err := encode(s.opts.codec, msg, cp, outPayload, comp) if err != nil { grpclog.Errorln("grpc: server failed to encode response: ", err) return err @@ -741,10 +782,43 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } }() } + + // comp and cp are used for compression. decomp and dc are used for + // decompression. If comp and decomp are both set, they are the same; + // however they are kept separate to ensure that at most one of the + // compressor/decompressor variable pairs are set for use later. + var comp, decomp encoding.Compressor + var cp Compressor + var dc Decompressor + + // If dc is set and matches the stream's compression, use it. Otherwise, try + // to find a matching registered compressor for decomp. + if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { + dc = s.opts.dc + } else if rc != "" && rc != encoding.Identity { + decomp = encoding.GetCompressor(rc) + if decomp == nil { + st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) + t.WriteStatus(stream, st) + return st.Err() + } + } + + // If cp is set, use it. Otherwise, attempt to compress the response using + // the incoming message compression method. + // + // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. if s.opts.cp != nil { - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - stream.SetSendCompress(s.opts.cp.Type()) + cp = s.opts.cp + stream.SetSendCompress(cp.Type()) + } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { + // Legacy compressor not specified; attempt to respond with same encoding. + comp = encoding.GetCompressor(rc) + if comp != nil { + stream.SetSendCompress(rc) + } } + p := &parser{r: stream} pf, req, err := p.recvMsg(s.opts.maxReceiveMessageSize) if err == io.EOF { @@ -773,19 +847,11 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } return err } - - if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil { - if st, ok := status.FromError(err); ok { - if e := t.WriteStatus(stream, st); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - return err - } - if e := t.WriteStatus(stream, status.New(codes.Internal, err.Error())); e != nil { + if st := checkRecvPayload(pf, stream.RecvCompress(), dc != nil || decomp != nil); st != nil { + if e := t.WriteStatus(stream, st); e != nil { grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) } - - // TODO checkRecvPayload always return RPC error. Add a return here if necessary. + return st.Err() } var inPayload *stats.InPayload if sh != nil { @@ -799,9 +865,17 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } if pf == compressionMade { var err error - req, err = s.opts.dc.Do(bytes.NewReader(req)) - if err != nil { - return Errorf(codes.Internal, err.Error()) + if dc != nil { + req, err = dc.Do(bytes.NewReader(req)) + if err != nil { + return Errorf(codes.Internal, err.Error()) + } + } else { + tmp, _ := decomp.Decompress(bytes.NewReader(req)) + req, err = ioutil.ReadAll(tmp) + if err != nil { + return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } } } if len(req) > s.opts.maxReceiveMessageSize { @@ -847,7 +921,8 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. Last: true, Delay: false, } - if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil { + + if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil { if err == io.EOF { // The entire stream is done (for unary RPC only). return err @@ -896,21 +971,45 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp sh.HandleRPC(stream.Context(), end) }() } - if s.opts.cp != nil { - stream.SetSendCompress(s.opts.cp.Type()) - } ss := &serverStream{ t: t, s: stream, p: &parser{r: stream}, codec: s.opts.codec, - cp: s.opts.cp, - dc: s.opts.dc, maxReceiveMessageSize: s.opts.maxReceiveMessageSize, maxSendMessageSize: s.opts.maxSendMessageSize, trInfo: trInfo, statsHandler: sh, } + + // If dc is set and matches the stream's compression, use it. Otherwise, try + // to find a matching registered compressor for decomp. + if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { + ss.dc = s.opts.dc + } else if rc != "" && rc != encoding.Identity { + ss.decomp = encoding.GetCompressor(rc) + if ss.decomp == nil { + st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) + t.WriteStatus(ss.s, st) + return st.Err() + } + } + + // If cp is set, use it. Otherwise, attempt to compress the response using + // the incoming message compression method. + // + // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. + if s.opts.cp != nil { + ss.cp = s.opts.cp + stream.SetSendCompress(s.opts.cp.Type()) + } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { + // Legacy compressor not specified; attempt to respond with same encoding. + ss.comp = encoding.GetCompressor(rc) + if ss.comp != nil { + stream.SetSendCompress(rc) + } + } + if trInfo != nil { trInfo.tr.LazyLog(&trInfo.firstLine, false) defer func() { @@ -1054,6 +1153,16 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Str // pending RPCs on the client side will get notified by connection // errors. func (s *Server) Stop() { + s.quitOnce.Do(func() { + close(s.quit) + }) + + defer func() { + s.doneOnce.Do(func() { + close(s.done) + }) + }() + s.mu.Lock() listeners := s.lis s.lis = nil @@ -1083,6 +1192,16 @@ func (s *Server) Stop() { // accepting new connections and RPCs and blocks until all the pending RPCs are // finished. func (s *Server) GracefulStop() { + s.quitOnce.Do(func() { + close(s.quit) + }) + + defer func() { + s.doneOnce.Do(func() { + close(s.done) + }) + }() + s.mu.Lock() defer s.mu.Unlock() if s.conns == nil { @@ -1110,25 +1229,11 @@ func (s *Server) GracefulStop() { } func init() { - internal.TestingCloseConns = func(arg interface{}) { - arg.(*Server).testingCloseConns() - } internal.TestingUseHandlerImpl = func(arg interface{}) { arg.(*Server).opts.useHandlerImpl = true } } -// testingCloseConns closes all existing transports but keeps s.lis -// accepting new connections. -func (s *Server) testingCloseConns() { - s.mu.Lock() - for c := range s.conns { - c.Close() - delete(s.conns, c) - } - s.mu.Unlock() -} - // SetHeader sets the header metadata. // When called multiple times, all the provided metadata will be merged. // All the metadata will be sent out when one of the following happens: diff --git a/vendor/google.golang.org/grpc/server_test.go b/vendor/google.golang.org/grpc/server_test.go index 6438b5f8a..cd2f2c083 100644 --- a/vendor/google.golang.org/grpc/server_test.go +++ b/vendor/google.golang.org/grpc/server_test.go @@ -23,6 +23,7 @@ import ( "reflect" "strings" "testing" + "time" "google.golang.org/grpc/test/leakcheck" ) @@ -53,6 +54,27 @@ func TestStopBeforeServe(t *testing.T) { } } +func TestGracefulStop(t *testing.T) { + defer leakcheck.Check(t) + + lis, err := net.Listen("tcp", "localhost:0") + if err != nil { + t.Fatalf("failed to create listener: %v", err) + } + + server := NewServer() + go func() { + // make sure Serve() is called + time.Sleep(time.Millisecond * 500) + server.GracefulStop() + }() + + err = server.Serve(lis) + if err != nil { + t.Fatalf("Serve() returned non-nil error on GracefulStop: %v", err) + } +} + func TestGetServiceInfo(t *testing.T) { defer leakcheck.Check(t) testSd := ServiceDesc{ diff --git a/vendor/google.golang.org/grpc/service_config.go b/vendor/google.golang.org/grpc/service_config.go new file mode 100644 index 000000000..cde648334 --- /dev/null +++ b/vendor/google.golang.org/grpc/service_config.go @@ -0,0 +1,199 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "encoding/json" + "time" + + "google.golang.org/grpc/grpclog" +) + +const maxInt = int(^uint(0) >> 1) + +// MethodConfig defines the configuration recommended by the service providers for a +// particular method. +// DEPRECATED: Users should not use this struct. Service config should be received +// through name resolver, as specified here +// https://github.com/grpc/grpc/blob/master/doc/service_config.md +type MethodConfig struct { + // WaitForReady indicates whether RPCs sent to this method should wait until + // the connection is ready by default (!failfast). The value specified via the + // gRPC client API will override the value set here. + WaitForReady *bool + // Timeout is the default timeout for RPCs sent to this method. The actual + // deadline used will be the minimum of the value specified here and the value + // set by the application via the gRPC client API. If either one is not set, + // then the other will be used. If neither is set, then the RPC has no deadline. + Timeout *time.Duration + // MaxReqSize is the maximum allowed payload size for an individual request in a + // stream (client->server) in bytes. The size which is measured is the serialized + // payload after per-message compression (but before stream compression) in bytes. + // The actual value used is the minimum of the value specified here and the value set + // by the application via the gRPC client API. If either one is not set, then the other + // will be used. If neither is set, then the built-in default is used. + MaxReqSize *int + // MaxRespSize is the maximum allowed payload size for an individual response in a + // stream (server->client) in bytes. + MaxRespSize *int +} + +// ServiceConfig is provided by the service provider and contains parameters for how +// clients that connect to the service should behave. +// DEPRECATED: Users should not use this struct. Service config should be received +// through name resolver, as specified here +// https://github.com/grpc/grpc/blob/master/doc/service_config.md +type ServiceConfig struct { + // LB is the load balancer the service providers recommends. The balancer specified + // via grpc.WithBalancer will override this. + LB *string + // Methods contains a map for the methods in this service. + // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig. + // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists. + // Otherwise, the method has no MethodConfig to use. + Methods map[string]MethodConfig +} + +func parseTimeout(t *string) (*time.Duration, error) { + if t == nil { + return nil, nil + } + d, err := time.ParseDuration(*t) + return &d, err +} + +type jsonName struct { + Service *string + Method *string +} + +func (j jsonName) generatePath() (string, bool) { + if j.Service == nil { + return "", false + } + res := "/" + *j.Service + "/" + if j.Method != nil { + res += *j.Method + } + return res, true +} + +// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. +type jsonMC struct { + Name *[]jsonName + WaitForReady *bool + Timeout *string + MaxRequestMessageBytes *int64 + MaxResponseMessageBytes *int64 +} + +// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. +type jsonSC struct { + LoadBalancingPolicy *string + MethodConfig *[]jsonMC +} + +func parseServiceConfig(js string) (ServiceConfig, error) { + var rsc jsonSC + err := json.Unmarshal([]byte(js), &rsc) + if err != nil { + grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) + return ServiceConfig{}, err + } + sc := ServiceConfig{ + LB: rsc.LoadBalancingPolicy, + Methods: make(map[string]MethodConfig), + } + if rsc.MethodConfig == nil { + return sc, nil + } + + for _, m := range *rsc.MethodConfig { + if m.Name == nil { + continue + } + d, err := parseTimeout(m.Timeout) + if err != nil { + grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) + return ServiceConfig{}, err + } + + mc := MethodConfig{ + WaitForReady: m.WaitForReady, + Timeout: d, + } + if m.MaxRequestMessageBytes != nil { + if *m.MaxRequestMessageBytes > int64(maxInt) { + mc.MaxReqSize = newInt(maxInt) + } else { + mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes)) + } + } + if m.MaxResponseMessageBytes != nil { + if *m.MaxResponseMessageBytes > int64(maxInt) { + mc.MaxRespSize = newInt(maxInt) + } else { + mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes)) + } + } + for _, n := range *m.Name { + if path, valid := n.generatePath(); valid { + sc.Methods[path] = mc + } + } + } + + return sc, nil +} + +func min(a, b *int) *int { + if *a < *b { + return a + } + return b +} + +func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { + if mcMax == nil && doptMax == nil { + return &defaultVal + } + if mcMax != nil && doptMax != nil { + return min(mcMax, doptMax) + } + if mcMax != nil { + return mcMax + } + return doptMax +} + +func newBool(b bool) *bool { + return &b +} + +func newInt(b int) *int { + return &b +} + +func newDuration(b time.Duration) *time.Duration { + return &b +} + +func newString(b string) *string { + return &b +} diff --git a/vendor/google.golang.org/grpc/service_config_test.go b/vendor/google.golang.org/grpc/service_config_test.go new file mode 100644 index 000000000..7e985457e --- /dev/null +++ b/vendor/google.golang.org/grpc/service_config_test.go @@ -0,0 +1,323 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package grpc + +import ( + "reflect" + "testing" + "time" +) + +func TestParseLoadBalancer(t *testing.T) { + testcases := []struct { + scjs string + wantSC ServiceConfig + wantErr bool + }{ + { + `{ + "loadBalancingPolicy": "round_robin", + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "waitForReady": true + } + ] +}`, + ServiceConfig{ + LB: newString("round_robin"), + Methods: map[string]MethodConfig{ + "/foo/Bar": { + WaitForReady: newBool(true), + }, + }, + }, + false, + }, + { + `{ + "loadBalancingPolicy": 1, + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "waitForReady": false + } + ] +}`, + ServiceConfig{}, + true, + }, + } + + for _, c := range testcases { + sc, err := parseServiceConfig(c.scjs) + if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { + t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) + } + } +} + +func TestParseWaitForReady(t *testing.T) { + testcases := []struct { + scjs string + wantSC ServiceConfig + wantErr bool + }{ + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "waitForReady": true + } + ] +}`, + ServiceConfig{ + Methods: map[string]MethodConfig{ + "/foo/Bar": { + WaitForReady: newBool(true), + }, + }, + }, + false, + }, + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "waitForReady": false + } + ] +}`, + ServiceConfig{ + Methods: map[string]MethodConfig{ + "/foo/Bar": { + WaitForReady: newBool(false), + }, + }, + }, + false, + }, + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "waitForReady": fall + }, + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "waitForReady": true + } + ] +}`, + ServiceConfig{}, + true, + }, + } + + for _, c := range testcases { + sc, err := parseServiceConfig(c.scjs) + if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { + t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) + } + } +} + +func TestPraseTimeOut(t *testing.T) { + testcases := []struct { + scjs string + wantSC ServiceConfig + wantErr bool + }{ + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "timeout": "1s" + } + ] +}`, + ServiceConfig{ + Methods: map[string]MethodConfig{ + "/foo/Bar": { + Timeout: newDuration(time.Second), + }, + }, + }, + false, + }, + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "timeout": "3c" + } + ] +}`, + ServiceConfig{}, + true, + }, + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "timeout": "3c" + }, + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "timeout": "1s" + } + ] +}`, + ServiceConfig{}, + true, + }, + } + + for _, c := range testcases { + sc, err := parseServiceConfig(c.scjs) + if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { + t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) + } + } +} + +func TestPraseMsgSize(t *testing.T) { + testcases := []struct { + scjs string + wantSC ServiceConfig + wantErr bool + }{ + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "maxRequestMessageBytes": 1024, + "maxResponseMessageBytes": 2048 + } + ] +}`, + ServiceConfig{ + Methods: map[string]MethodConfig{ + "/foo/Bar": { + MaxReqSize: newInt(1024), + MaxRespSize: newInt(2048), + }, + }, + }, + false, + }, + { + `{ + "methodConfig": [ + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "maxRequestMessageBytes": "1024", + "maxResponseMessageBytes": "2048" + }, + { + "name": [ + { + "service": "foo", + "method": "Bar" + } + ], + "maxRequestMessageBytes": 1024, + "maxResponseMessageBytes": 2048 + } + ] +}`, + ServiceConfig{}, + true, + }, + } + + for _, c := range testcases { + sc, err := parseServiceConfig(c.scjs) + if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { + t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) + } + } +} diff --git a/vendor/google.golang.org/grpc/stats/grpc_testing/test.pb.go b/vendor/google.golang.org/grpc/stats/grpc_testing/test.pb.go deleted file mode 100644 index c0c14a24b..000000000 --- a/vendor/google.golang.org/grpc/stats/grpc_testing/test.pb.go +++ /dev/null @@ -1,369 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_testing/test.proto - -/* -Package grpc_testing is a generated protocol buffer package. - -It is generated from these files: - grpc_testing/test.proto - -It has these top-level messages: - SimpleRequest - SimpleResponse -*/ -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SimpleRequest struct { - Id int32 `protobuf:"varint,2,opt,name=id" json:"id,omitempty"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *SimpleRequest) GetId() int32 { - if m != nil { - return m.Id - } - return 0 -} - -type SimpleResponse struct { - Id int32 `protobuf:"varint,3,opt,name=id" json:"id,omitempty"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *SimpleResponse) GetId() int32 { - if m != nil { - return m.Id - } - return 0 -} - -func init() { - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for TestService service - -type TestServiceClient interface { - // One request followed by one response. - // The server returns the client id as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) - // Client stream - ClientStreamCall(ctx context.Context, opts ...grpc.CallOption) (TestService_ClientStreamCallClient, error) - // Server stream - ServerStreamCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (TestService_ServerStreamCallClient, error) -} - -type testServiceClient struct { - cc *grpc.ClientConn -} - -func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient { - return &testServiceClient{cc} -} - -func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := grpc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[0], c.cc, "/grpc.testing.TestService/FullDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceFullDuplexCallClient{stream} - return x, nil -} - -type TestService_FullDuplexCallClient interface { - Send(*SimpleRequest) error - Recv() (*SimpleResponse, error) - grpc.ClientStream -} - -type testServiceFullDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceFullDuplexCallClient) Send(m *SimpleRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallClient) Recv() (*SimpleResponse, error) { - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) ClientStreamCall(ctx context.Context, opts ...grpc.CallOption) (TestService_ClientStreamCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[1], c.cc, "/grpc.testing.TestService/ClientStreamCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceClientStreamCallClient{stream} - return x, nil -} - -type TestService_ClientStreamCallClient interface { - Send(*SimpleRequest) error - CloseAndRecv() (*SimpleResponse, error) - grpc.ClientStream -} - -type testServiceClientStreamCallClient struct { - grpc.ClientStream -} - -func (x *testServiceClientStreamCallClient) Send(m *SimpleRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceClientStreamCallClient) CloseAndRecv() (*SimpleResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) ServerStreamCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (TestService_ServerStreamCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[2], c.cc, "/grpc.testing.TestService/ServerStreamCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceServerStreamCallClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type TestService_ServerStreamCallClient interface { - Recv() (*SimpleResponse, error) - grpc.ClientStream -} - -type testServiceServerStreamCallClient struct { - grpc.ClientStream -} - -func (x *testServiceServerStreamCallClient) Recv() (*SimpleResponse, error) { - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for TestService service - -type TestServiceServer interface { - // One request followed by one response. - // The server returns the client id as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(TestService_FullDuplexCallServer) error - // Client stream - ClientStreamCall(TestService_ClientStreamCallServer) error - // Server stream - ServerStreamCall(*SimpleRequest, TestService_ServerStreamCallServer) error -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} - -type TestService_FullDuplexCallServer interface { - Send(*SimpleResponse) error - Recv() (*SimpleRequest, error) - grpc.ServerStream -} - -type testServiceFullDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceFullDuplexCallServer) Send(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallServer) Recv() (*SimpleRequest, error) { - m := new(SimpleRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_ClientStreamCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).ClientStreamCall(&testServiceClientStreamCallServer{stream}) -} - -type TestService_ClientStreamCallServer interface { - SendAndClose(*SimpleResponse) error - Recv() (*SimpleRequest, error) - grpc.ServerStream -} - -type testServiceClientStreamCallServer struct { - grpc.ServerStream -} - -func (x *testServiceClientStreamCallServer) SendAndClose(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceClientStreamCallServer) Recv() (*SimpleRequest, error) { - m := new(SimpleRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - 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 { - Send(*SimpleResponse) error - grpc.ServerStream -} - -type testServiceServerStreamCallServer struct { - grpc.ServerStream -} - -func (x *testServiceServerStreamCallServer) Send(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -var _TestService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - HandlerType: (*TestServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryCall", - Handler: _TestService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "FullDuplexCall", - Handler: _TestService_FullDuplexCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "ClientStreamCall", - Handler: _TestService_ClientStreamCall_Handler, - ClientStreams: true, - }, - { - StreamName: "ServerStreamCall", - Handler: _TestService_ServerStreamCall_Handler, - ServerStreams: true, - }, - }, - Metadata: "grpc_testing/test.proto", -} - -func init() { proto.RegisterFile("grpc_testing/test.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 202 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0x2f, 0x2a, 0x48, - 0x8e, 0x2f, 0x49, 0x2d, 0x2e, 0xc9, 0xcc, 0x4b, 0xd7, 0x07, 0xd1, 0x7a, 0x05, 0x45, 0xf9, 0x25, - 0xf9, 0x42, 0x3c, 0x20, 0x09, 0x3d, 0xa8, 0x84, 0x92, 0x3c, 0x17, 0x6f, 0x70, 0x66, 0x6e, 0x41, - 0x4e, 0x6a, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x10, 0x1f, 0x17, 0x53, 0x66, 0x8a, 0x04, - 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x53, 0x66, 0x8a, 0x92, 0x02, 0x17, 0x1f, 0x4c, 0x41, 0x71, - 0x41, 0x7e, 0x5e, 0x71, 0x2a, 0x54, 0x05, 0x33, 0x4c, 0x85, 0xd1, 0x09, 0x26, 0x2e, 0xee, 0x90, - 0xd4, 0xe2, 0x92, 0xe0, 0xd4, 0xa2, 0xb2, 0xcc, 0xe4, 0x54, 0x21, 0x37, 0x2e, 0xce, 0xd0, 0xbc, - 0xc4, 0xa2, 0x4a, 0xe7, 0xc4, 0x9c, 0x1c, 0x21, 0x69, 0x3d, 0x64, 0xeb, 0xf4, 0x50, 0xec, 0x92, - 0x92, 0xc1, 0x2e, 0x09, 0xb5, 0xc7, 0x9f, 0x8b, 0xcf, 0xad, 0x34, 0x27, 0xc7, 0xa5, 0xb4, 0x20, - 0x27, 0xb5, 0x82, 0x42, 0xc3, 0x34, 0x18, 0x0d, 0x18, 0x85, 0xfc, 0xb9, 0x04, 0x9c, 0x73, 0x32, - 0x53, 0xf3, 0x4a, 0x82, 0x4b, 0x8a, 0x52, 0x13, 0x73, 0x29, 0x36, 0x12, 0x64, 0x20, 0xc8, 0xd3, - 0xa9, 0x45, 0x54, 0x31, 0xd0, 0x80, 0x31, 0x89, 0x0d, 0x1c, 0x45, 0xc6, 0x80, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x4c, 0x43, 0x27, 0x67, 0xbd, 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/stats/grpc_testing/test.proto b/vendor/google.golang.org/grpc/stats/grpc_testing/test.proto deleted file mode 100644 index b49a0d5a7..000000000 --- a/vendor/google.golang.org/grpc/stats/grpc_testing/test.proto +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - -message SimpleRequest { - int32 id = 2; -} - -message SimpleResponse { - int32 id = 3; -} - -// A simple test service. -service TestService { - // One request followed by one response. - // The server returns the client id as-is. - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - rpc FullDuplexCall(stream SimpleRequest) returns (stream SimpleResponse); - - // Client stream - rpc ClientStreamCall(stream SimpleRequest) returns (SimpleResponse); - - // Server stream - rpc ServerStreamCall(SimpleRequest) returns (stream SimpleResponse); -} diff --git a/vendor/google.golang.org/grpc/stats/stats_test.go b/vendor/google.golang.org/grpc/stats/stats_test.go index 141324c0d..0df23f3dc 100644 --- a/vendor/google.golang.org/grpc/stats/stats_test.go +++ b/vendor/google.golang.org/grpc/stats/stats_test.go @@ -33,6 +33,7 @@ import ( "google.golang.org/grpc/metadata" "google.golang.org/grpc/stats" testpb "google.golang.org/grpc/stats/grpc_testing" + "google.golang.org/grpc/status" ) func init() { @@ -63,10 +64,10 @@ func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (* md, ok := metadata.FromIncomingContext(ctx) if ok { if err := grpc.SendHeader(ctx, md); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SendHeader(_, %v) = %v, want <nil>", md, err) + return nil, status.Errorf(grpc.Code(err), "grpc.SendHeader(_, %v) = %v, want <nil>", md, err) } if err := grpc.SetTrailer(ctx, testTrailerMetadata); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SetTrailer(_, %v) = %v, want <nil>", testTrailerMetadata, err) + return nil, status.Errorf(grpc.Code(err), "grpc.SetTrailer(_, %v) = %v, want <nil>", testTrailerMetadata, err) } } @@ -81,7 +82,7 @@ func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServ md, ok := metadata.FromIncomingContext(stream.Context()) if ok { if err := stream.SendHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) + return status.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) } stream.SetTrailer(testTrailerMetadata) } @@ -109,7 +110,7 @@ func (s *testServer) ClientStreamCall(stream testpb.TestService_ClientStreamCall md, ok := metadata.FromIncomingContext(stream.Context()) if ok { if err := stream.SendHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) + return status.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) } stream.SetTrailer(testTrailerMetadata) } @@ -133,7 +134,7 @@ func (s *testServer) ServerStreamCall(in *testpb.SimpleRequest, stream testpb.Te md, ok := metadata.FromIncomingContext(stream.Context()) if ok { if err := stream.SendHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) + return status.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) } stream.SetTrailer(testTrailerMetadata) } diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 75eab40b1..9eeaafef8 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -19,7 +19,6 @@ package grpc import ( - "bytes" "errors" "io" "sync" @@ -29,6 +28,7 @@ import ( "golang.org/x/net/trace" "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" + "google.golang.org/grpc/encoding" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" @@ -94,15 +94,23 @@ type ClientStream interface { Stream } -// NewClientStream creates a new Stream for the client side. This is called -// by generated code. -func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { +// NewStream creates a new Stream for the client side. This is typically +// called by generated code. +func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { if cc.dopts.streamInt != nil { return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...) } return newClientStream(ctx, desc, cc, method, opts...) } +// NewClientStream creates a new Stream for the client side. This is typically +// called by generated code. +// +// DEPRECATED: Use ClientConn.NewStream instead. +func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { + return cc.NewStream(ctx, desc, method, opts...) +} + func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { var ( t transport.ClientTransport @@ -116,7 +124,7 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth c.failFast = !*mc.WaitForReady } - if mc.Timeout != nil { + if mc.Timeout != nil && *mc.Timeout >= 0 { ctx, cancel = context.WithTimeout(ctx, *mc.Timeout) defer func() { if err != nil { @@ -143,8 +151,24 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth // time soon, so we ask the transport to flush the header. Flush: desc.ClientStreams, } - if cc.dopts.cp != nil { + + // Set our outgoing compression according to the UseCompressor CallOption, if + // set. In that case, also find the compressor from the encoding package. + // Otherwise, use the compressor configured by the WithCompressor DialOption, + // if set. + var cp Compressor + var comp encoding.Compressor + if ct := c.compressorType; ct != "" { + callHdr.SendCompress = ct + if ct != encoding.Identity { + comp = encoding.GetCompressor(ct) + if comp == nil { + return nil, Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct) + } + } + } else if cc.dopts.cp != nil { callHdr.SendCompress = cc.dopts.cp.Type() + cp = cc.dopts.cp } if c.creds != nil { callHdr.Creds = c.creds @@ -189,42 +213,39 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } }() } + for { + // Check to make sure the context has expired. This will prevent us from + // looping forever if an error occurs for wait-for-ready RPCs where no data + // is sent on the wire. + select { + case <-ctx.Done(): + return nil, toRPCErr(ctx.Err()) + default: + } + t, done, err = cc.getTransport(ctx, c.failFast) if err != nil { - // TODO(zhaoq): Probably revisit the error handling. - if _, ok := status.FromError(err); ok { - return nil, err - } - if err == errConnClosing || err == errConnUnavailable { - if c.failFast { - return nil, Errorf(codes.Unavailable, "%v", err) - } - continue - } - // All the other errors are treated as Internal errors. - return nil, Errorf(codes.Internal, "%v", err) + return nil, err } s, err = t.NewStream(ctx, callHdr) if err != nil { - if _, ok := err.(transport.ConnectionError); ok && done != nil { - // If error is connection error, transport was sending data on wire, - // and we are not sure if anything has been sent on wire. - // If error is not connection error, we are sure nothing has been sent. - updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false}) - } if done != nil { done(balancer.DoneInfo{Err: err}) done = nil } - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { + // In the event of any error from NewStream, we never attempted to write + // anything to the wire, so we can retry indefinitely for non-fail-fast + // RPCs. + if !c.failFast { continue } return nil, toRPCErr(err) } break } + // Set callInfo.peer object from stream's context. if peer, ok := peer.FromContext(s.Context()); ok { c.peer = peer @@ -234,8 +255,9 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth c: c, desc: desc, codec: cc.dopts.codec, - cp: cc.dopts.cp, + cp: cp, dc: cc.dopts.dc, + comp: comp, cancel: cancel, done: done, @@ -249,8 +271,8 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth statsCtx: ctx, statsHandler: cc.dopts.copts.StatsHandler, } - // Listen on ctx.Done() to detect cancellation and s.Done() to detect normal termination - // when there is no pending I/O operations on this stream. + // Listen on s.Context().Done() to detect cancellation and s.Done() to detect + // normal termination when there is no pending I/O operations on this stream. go func() { select { case <-t.Error(): @@ -277,15 +299,20 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth // clientStream implements a client side Stream. type clientStream struct { - opts []CallOption - c *callInfo - t transport.ClientTransport - s *transport.Stream - p *parser - desc *StreamDesc - codec Codec - cp Compressor - dc Decompressor + opts []CallOption + c *callInfo + t transport.ClientTransport + s *transport.Stream + p *parser + desc *StreamDesc + + codec Codec + cp Compressor + dc Decompressor + comp encoding.Compressor + decomp encoding.Compressor + decompSet bool + cancel context.CancelFunc tracing bool // set to EnableTracing when the clientStream is created. @@ -361,7 +388,7 @@ func (cs *clientStream) SendMsg(m interface{}) (err error) { Client: true, } } - hdr, data, err := encode(cs.codec, m, cs.cp, bytes.NewBuffer([]byte{}), outPayload) + hdr, data, err := encode(cs.codec, m, cs.cp, outPayload, cs.comp) if err != nil { return err } @@ -389,7 +416,23 @@ func (cs *clientStream) RecvMsg(m interface{}) (err error) { if cs.c.maxReceiveMessageSize == nil { return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)") } - err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, inPayload) + if !cs.decompSet { + // Block until we receive headers containing received message encoding. + if ct := cs.s.RecvCompress(); ct != "" && ct != encoding.Identity { + if cs.dc == nil || cs.dc.Type() != ct { + // No configured decompressor, or it does not match the incoming + // message encoding; attempt to find a registered compressor that does. + cs.dc = nil + cs.decomp = encoding.GetCompressor(ct) + } + } else { + // No compression is used; disable our decompressor. + cs.dc = nil + } + // Only initialize this state once per stream. + cs.decompSet = true + } + err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, inPayload, cs.decomp) defer func() { // err != nil indicates the termination of the stream. if err != nil { @@ -415,7 +458,7 @@ func (cs *clientStream) RecvMsg(m interface{}) (err error) { if cs.c.maxReceiveMessageSize == nil { return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)") } - err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, nil) + err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, nil, cs.decomp) cs.closeTransportStream(err) if err == nil { return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>")) @@ -487,7 +530,7 @@ func (cs *clientStream) finish(err error) { } if cs.done != nil { updateRPCInfoInContext(cs.s.Context(), rpcInfo{ - bytesSent: cs.s.BytesSent(), + bytesSent: true, bytesReceived: cs.s.BytesReceived(), }) cs.done(balancer.DoneInfo{Err: err}) @@ -540,12 +583,16 @@ type ServerStream interface { // serverStream implements a server side Stream. type serverStream struct { - t transport.ServerTransport - s *transport.Stream - p *parser - codec Codec - cp Compressor - dc Decompressor + t transport.ServerTransport + s *transport.Stream + p *parser + codec Codec + + cp Compressor + dc Decompressor + comp encoding.Compressor + decomp encoding.Compressor + maxReceiveMessageSize int maxSendMessageSize int trInfo *traceInfo @@ -601,7 +648,7 @@ func (ss *serverStream) SendMsg(m interface{}) (err error) { if ss.statsHandler != nil { outPayload = &stats.OutPayload{} } - hdr, data, err := encode(ss.codec, m, ss.cp, bytes.NewBuffer([]byte{}), outPayload) + hdr, data, err := encode(ss.codec, m, ss.cp, outPayload, ss.comp) if err != nil { return err } @@ -641,7 +688,7 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { if ss.statsHandler != nil { inPayload = &stats.InPayload{} } - if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload); err != nil { + if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload, ss.decomp); err != nil { if err == io.EOF { return err } @@ -655,3 +702,13 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { } return nil } + +// MethodFromServerStream returns the method string for the input stream. +// The returned string is in the format of "/service/method". +func MethodFromServerStream(stream ServerStream) (string, bool) { + s, ok := transport.StreamFromContext(stream.Context()) + if !ok { + return "", ok + } + return s.Method(), ok +} diff --git a/vendor/google.golang.org/grpc/stress/client/main.go b/vendor/google.golang.org/grpc/stress/client/main.go deleted file mode 100644 index 635f1ad38..000000000 --- a/vendor/google.golang.org/grpc/stress/client/main.go +++ /dev/null @@ -1,336 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc -I ../grpc_testing --go_out=plugins=grpc:../grpc_testing ../grpc_testing/metrics.proto - -// client starts an interop client to do stress test and a metrics server to report qps. -package main - -import ( - "flag" - "fmt" - "math/rand" - "net" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" - metricspb "google.golang.org/grpc/stress/grpc_testing" - "google.golang.org/grpc/testdata" -) - -var ( - serverAddresses = flag.String("server_addresses", "localhost:8080", "a list of server addresses") - testCases = flag.String("test_cases", "", "a list of test cases along with the relative weights") - testDurationSecs = flag.Int("test_duration_secs", -1, "test duration in seconds") - numChannelsPerServer = flag.Int("num_channels_per_server", 1, "Number of channels (i.e connections) to each server") - numStubsPerChannel = flag.Int("num_stubs_per_channel", 1, "Number of client stubs per each connection to server") - metricsPort = flag.Int("metrics_port", 8081, "The port at which the stress client exposes QPS metrics") - useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP") - testCA = flag.Bool("use_test_ca", false, "Whether to replace platform root CAs with test CA as the CA root") - tlsServerName = flag.String("server_host_override", "foo.test.google.fr", "The server name use to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.") - caFile = flag.String("ca_file", "", "The file containning the CA root cert file") -) - -// testCaseWithWeight contains the test case type and its weight. -type testCaseWithWeight struct { - name string - weight int -} - -// parseTestCases converts test case string to a list of struct testCaseWithWeight. -func parseTestCases(testCaseString string) []testCaseWithWeight { - testCaseStrings := strings.Split(testCaseString, ",") - testCases := make([]testCaseWithWeight, len(testCaseStrings)) - for i, str := range testCaseStrings { - testCase := strings.Split(str, ":") - if len(testCase) != 2 { - panic(fmt.Sprintf("invalid test case with weight: %s", str)) - } - // Check if test case is supported. - switch testCase[0] { - case - "empty_unary", - "large_unary", - "client_streaming", - "server_streaming", - "ping_pong", - "empty_stream", - "timeout_on_sleeping_server", - "cancel_after_begin", - "cancel_after_first_response", - "status_code_and_message", - "custom_metadata": - default: - panic(fmt.Sprintf("unknown test type: %s", testCase[0])) - } - testCases[i].name = testCase[0] - w, err := strconv.Atoi(testCase[1]) - if err != nil { - panic(fmt.Sprintf("%v", err)) - } - testCases[i].weight = w - } - return testCases -} - -// weightedRandomTestSelector defines a weighted random selector for test case types. -type weightedRandomTestSelector struct { - tests []testCaseWithWeight - totalWeight int -} - -// newWeightedRandomTestSelector constructs a weightedRandomTestSelector with the given list of testCaseWithWeight. -func newWeightedRandomTestSelector(tests []testCaseWithWeight) *weightedRandomTestSelector { - var totalWeight int - for _, t := range tests { - totalWeight += t.weight - } - rand.Seed(time.Now().UnixNano()) - return &weightedRandomTestSelector{tests, totalWeight} -} - -func (selector weightedRandomTestSelector) getNextTest() string { - random := rand.Intn(selector.totalWeight) - var weightSofar int - for _, test := range selector.tests { - weightSofar += test.weight - if random < weightSofar { - return test.name - } - } - panic("no test case selected by weightedRandomTestSelector") -} - -// gauge stores the qps of one interop client (one stub). -type gauge struct { - mutex sync.RWMutex - val int64 -} - -func (g *gauge) set(v int64) { - g.mutex.Lock() - defer g.mutex.Unlock() - g.val = v -} - -func (g *gauge) get() int64 { - g.mutex.RLock() - defer g.mutex.RUnlock() - return g.val -} - -// server implements metrics server functions. -type server struct { - mutex sync.RWMutex - // gauges is a map from /stress_test/server_<n>/channel_<n>/stub_<n>/qps to its qps gauge. - gauges map[string]*gauge -} - -// newMetricsServer returns a new metrics server. -func newMetricsServer() *server { - return &server{gauges: make(map[string]*gauge)} -} - -// GetAllGauges returns all gauges. -func (s *server) GetAllGauges(in *metricspb.EmptyMessage, stream metricspb.MetricsService_GetAllGaugesServer) error { - s.mutex.RLock() - defer s.mutex.RUnlock() - - for name, gauge := range s.gauges { - if err := stream.Send(&metricspb.GaugeResponse{Name: name, Value: &metricspb.GaugeResponse_LongValue{LongValue: gauge.get()}}); err != nil { - return err - } - } - return nil -} - -// GetGauge returns the gauge for the given name. -func (s *server) GetGauge(ctx context.Context, in *metricspb.GaugeRequest) (*metricspb.GaugeResponse, error) { - s.mutex.RLock() - defer s.mutex.RUnlock() - - if g, ok := s.gauges[in.Name]; ok { - return &metricspb.GaugeResponse{Name: in.Name, Value: &metricspb.GaugeResponse_LongValue{LongValue: g.get()}}, nil - } - return nil, grpc.Errorf(codes.InvalidArgument, "gauge with name %s not found", in.Name) -} - -// createGauge creates a gauge using the given name in metrics server. -func (s *server) createGauge(name string) *gauge { - s.mutex.Lock() - defer s.mutex.Unlock() - - if _, ok := s.gauges[name]; ok { - // gauge already exists. - panic(fmt.Sprintf("gauge %s already exists", name)) - } - var g gauge - s.gauges[name] = &g - return &g -} - -func startServer(server *server, port int) { - lis, err := net.Listen("tcp", ":"+strconv.Itoa(port)) - if err != nil { - grpclog.Fatalf("failed to listen: %v", err) - } - - s := grpc.NewServer() - metricspb.RegisterMetricsServiceServer(s, server) - s.Serve(lis) - -} - -// performRPCs uses weightedRandomTestSelector to select test case and runs the tests. -func performRPCs(gauge *gauge, conn *grpc.ClientConn, selector *weightedRandomTestSelector, stop <-chan bool) { - client := testpb.NewTestServiceClient(conn) - var numCalls int64 - startTime := time.Now() - for { - test := selector.getNextTest() - switch test { - case "empty_unary": - interop.DoEmptyUnaryCall(client, grpc.FailFast(false)) - case "large_unary": - interop.DoLargeUnaryCall(client, grpc.FailFast(false)) - case "client_streaming": - interop.DoClientStreaming(client, grpc.FailFast(false)) - case "server_streaming": - interop.DoServerStreaming(client, grpc.FailFast(false)) - case "ping_pong": - interop.DoPingPong(client, grpc.FailFast(false)) - case "empty_stream": - interop.DoEmptyStream(client, grpc.FailFast(false)) - case "timeout_on_sleeping_server": - interop.DoTimeoutOnSleepingServer(client, grpc.FailFast(false)) - case "cancel_after_begin": - interop.DoCancelAfterBegin(client, grpc.FailFast(false)) - case "cancel_after_first_response": - interop.DoCancelAfterFirstResponse(client, grpc.FailFast(false)) - case "status_code_and_message": - interop.DoStatusCodeAndMessage(client, grpc.FailFast(false)) - case "custom_metadata": - interop.DoCustomMetadata(client, grpc.FailFast(false)) - } - numCalls++ - gauge.set(int64(float64(numCalls) / time.Since(startTime).Seconds())) - - select { - case <-stop: - return - default: - } - } -} - -func logParameterInfo(addresses []string, tests []testCaseWithWeight) { - grpclog.Printf("server_addresses: %s", *serverAddresses) - grpclog.Printf("test_cases: %s", *testCases) - grpclog.Printf("test_duration_secs: %d", *testDurationSecs) - grpclog.Printf("num_channels_per_server: %d", *numChannelsPerServer) - grpclog.Printf("num_stubs_per_channel: %d", *numStubsPerChannel) - grpclog.Printf("metrics_port: %d", *metricsPort) - grpclog.Printf("use_tls: %t", *useTLS) - grpclog.Printf("use_test_ca: %t", *testCA) - grpclog.Printf("server_host_override: %s", *tlsServerName) - - grpclog.Println("addresses:") - for i, addr := range addresses { - grpclog.Printf("%d. %s\n", i+1, addr) - } - grpclog.Println("tests:") - for i, test := range tests { - grpclog.Printf("%d. %v\n", i+1, test) - } -} - -func newConn(address string, useTLS, testCA bool, tlsServerName string) (*grpc.ClientConn, error) { - var opts []grpc.DialOption - if useTLS { - var sn string - if tlsServerName != "" { - sn = tlsServerName - } - var creds credentials.TransportCredentials - if testCA { - var err error - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err = credentials.NewClientTLSFromFile(*caFile, sn) - if err != nil { - grpclog.Fatalf("Failed to create TLS credentials %v", err) - } - } else { - creds = credentials.NewClientTLSFromCert(nil, sn) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - } else { - opts = append(opts, grpc.WithInsecure()) - } - return grpc.Dial(address, opts...) -} - -func main() { - flag.Parse() - addresses := strings.Split(*serverAddresses, ",") - tests := parseTestCases(*testCases) - logParameterInfo(addresses, tests) - testSelector := newWeightedRandomTestSelector(tests) - metricsServer := newMetricsServer() - - var wg sync.WaitGroup - wg.Add(len(addresses) * *numChannelsPerServer * *numStubsPerChannel) - stop := make(chan bool) - - for serverIndex, address := range addresses { - for connIndex := 0; connIndex < *numChannelsPerServer; connIndex++ { - conn, err := newConn(address, *useTLS, *testCA, *tlsServerName) - if err != nil { - grpclog.Fatalf("Fail to dial: %v", err) - } - defer conn.Close() - for clientIndex := 0; clientIndex < *numStubsPerChannel; clientIndex++ { - name := fmt.Sprintf("/stress_test/server_%d/channel_%d/stub_%d/qps", serverIndex+1, connIndex+1, clientIndex+1) - go func() { - defer wg.Done() - g := metricsServer.createGauge(name) - performRPCs(g, conn, testSelector, stop) - }() - } - - } - } - go startServer(metricsServer, *metricsPort) - if *testDurationSecs > 0 { - time.Sleep(time.Duration(*testDurationSecs) * time.Second) - close(stop) - } - wg.Wait() - grpclog.Printf(" ===== ALL DONE ===== ") - -} diff --git a/vendor/google.golang.org/grpc/stress/grpc_testing/metrics.pb.go b/vendor/google.golang.org/grpc/stress/grpc_testing/metrics.pb.go deleted file mode 100644 index 466668a4d..000000000 --- a/vendor/google.golang.org/grpc/stress/grpc_testing/metrics.pb.go +++ /dev/null @@ -1,374 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: metrics.proto - -/* -Package grpc_testing is a generated protocol buffer package. - -It is generated from these files: - metrics.proto - -It has these top-level messages: - GaugeResponse - GaugeRequest - EmptyMessage -*/ -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Response message containing the gauge name and value -type GaugeResponse struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Types that are valid to be assigned to Value: - // *GaugeResponse_LongValue - // *GaugeResponse_DoubleValue - // *GaugeResponse_StringValue - Value isGaugeResponse_Value `protobuf_oneof:"value"` -} - -func (m *GaugeResponse) Reset() { *m = GaugeResponse{} } -func (m *GaugeResponse) String() string { return proto.CompactTextString(m) } -func (*GaugeResponse) ProtoMessage() {} -func (*GaugeResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -type isGaugeResponse_Value interface { - isGaugeResponse_Value() -} - -type GaugeResponse_LongValue struct { - LongValue int64 `protobuf:"varint,2,opt,name=long_value,json=longValue,oneof"` -} -type GaugeResponse_DoubleValue struct { - DoubleValue float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue,oneof"` -} -type GaugeResponse_StringValue struct { - StringValue string `protobuf:"bytes,4,opt,name=string_value,json=stringValue,oneof"` -} - -func (*GaugeResponse_LongValue) isGaugeResponse_Value() {} -func (*GaugeResponse_DoubleValue) isGaugeResponse_Value() {} -func (*GaugeResponse_StringValue) isGaugeResponse_Value() {} - -func (m *GaugeResponse) GetValue() isGaugeResponse_Value { - if m != nil { - return m.Value - } - return nil -} - -func (m *GaugeResponse) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *GaugeResponse) GetLongValue() int64 { - if x, ok := m.GetValue().(*GaugeResponse_LongValue); ok { - return x.LongValue - } - return 0 -} - -func (m *GaugeResponse) GetDoubleValue() float64 { - if x, ok := m.GetValue().(*GaugeResponse_DoubleValue); ok { - return x.DoubleValue - } - return 0 -} - -func (m *GaugeResponse) GetStringValue() string { - if x, ok := m.GetValue().(*GaugeResponse_StringValue); ok { - return x.StringValue - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*GaugeResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _GaugeResponse_OneofMarshaler, _GaugeResponse_OneofUnmarshaler, _GaugeResponse_OneofSizer, []interface{}{ - (*GaugeResponse_LongValue)(nil), - (*GaugeResponse_DoubleValue)(nil), - (*GaugeResponse_StringValue)(nil), - } -} - -func _GaugeResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*GaugeResponse) - // value - switch x := m.Value.(type) { - case *GaugeResponse_LongValue: - b.EncodeVarint(2<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.LongValue)) - case *GaugeResponse_DoubleValue: - b.EncodeVarint(3<<3 | proto.WireFixed64) - b.EncodeFixed64(math.Float64bits(x.DoubleValue)) - case *GaugeResponse_StringValue: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.StringValue) - case nil: - default: - return fmt.Errorf("GaugeResponse.Value has unexpected type %T", x) - } - return nil -} - -func _GaugeResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*GaugeResponse) - switch tag { - case 2: // value.long_value - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Value = &GaugeResponse_LongValue{int64(x)} - return true, err - case 3: // value.double_value - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Value = &GaugeResponse_DoubleValue{math.Float64frombits(x)} - return true, err - case 4: // value.string_value - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Value = &GaugeResponse_StringValue{x} - return true, err - default: - return false, nil - } -} - -func _GaugeResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*GaugeResponse) - // value - switch x := m.Value.(type) { - case *GaugeResponse_LongValue: - n += proto.SizeVarint(2<<3 | proto.WireVarint) - n += proto.SizeVarint(uint64(x.LongValue)) - case *GaugeResponse_DoubleValue: - n += proto.SizeVarint(3<<3 | proto.WireFixed64) - n += 8 - case *GaugeResponse_StringValue: - n += proto.SizeVarint(4<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.StringValue))) - n += len(x.StringValue) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// Request message containing the gauge name -type GaugeRequest struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` -} - -func (m *GaugeRequest) Reset() { *m = GaugeRequest{} } -func (m *GaugeRequest) String() string { return proto.CompactTextString(m) } -func (*GaugeRequest) ProtoMessage() {} -func (*GaugeRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *GaugeRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -type EmptyMessage struct { -} - -func (m *EmptyMessage) Reset() { *m = EmptyMessage{} } -func (m *EmptyMessage) String() string { return proto.CompactTextString(m) } -func (*EmptyMessage) ProtoMessage() {} -func (*EmptyMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func init() { - proto.RegisterType((*GaugeResponse)(nil), "grpc.testing.GaugeResponse") - proto.RegisterType((*GaugeRequest)(nil), "grpc.testing.GaugeRequest") - proto.RegisterType((*EmptyMessage)(nil), "grpc.testing.EmptyMessage") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for MetricsService service - -type MetricsServiceClient interface { - // Returns the values of all the gauges that are currently being maintained by - // the service - GetAllGauges(ctx context.Context, in *EmptyMessage, opts ...grpc.CallOption) (MetricsService_GetAllGaugesClient, error) - // Returns the value of one gauge - GetGauge(ctx context.Context, in *GaugeRequest, opts ...grpc.CallOption) (*GaugeResponse, error) -} - -type metricsServiceClient struct { - cc *grpc.ClientConn -} - -func NewMetricsServiceClient(cc *grpc.ClientConn) MetricsServiceClient { - return &metricsServiceClient{cc} -} - -func (c *metricsServiceClient) GetAllGauges(ctx context.Context, in *EmptyMessage, opts ...grpc.CallOption) (MetricsService_GetAllGaugesClient, error) { - stream, err := grpc.NewClientStream(ctx, &_MetricsService_serviceDesc.Streams[0], c.cc, "/grpc.testing.MetricsService/GetAllGauges", opts...) - if err != nil { - return nil, err - } - x := &metricsServiceGetAllGaugesClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type MetricsService_GetAllGaugesClient interface { - Recv() (*GaugeResponse, error) - grpc.ClientStream -} - -type metricsServiceGetAllGaugesClient struct { - grpc.ClientStream -} - -func (x *metricsServiceGetAllGaugesClient) Recv() (*GaugeResponse, error) { - m := new(GaugeResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *metricsServiceClient) GetGauge(ctx context.Context, in *GaugeRequest, opts ...grpc.CallOption) (*GaugeResponse, error) { - out := new(GaugeResponse) - err := grpc.Invoke(ctx, "/grpc.testing.MetricsService/GetGauge", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for MetricsService service - -type MetricsServiceServer interface { - // Returns the values of all the gauges that are currently being maintained by - // the service - GetAllGauges(*EmptyMessage, MetricsService_GetAllGaugesServer) error - // Returns the value of one gauge - GetGauge(context.Context, *GaugeRequest) (*GaugeResponse, error) -} - -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) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(MetricsServiceServer).GetAllGauges(m, &metricsServiceGetAllGaugesServer{stream}) -} - -type MetricsService_GetAllGaugesServer interface { - Send(*GaugeResponse) error - grpc.ServerStream -} - -type metricsServiceGetAllGaugesServer struct { - grpc.ServerStream -} - -func (x *metricsServiceGetAllGaugesServer) Send(m *GaugeResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _MetricsService_GetGauge_Handler(srv 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 srv.(MetricsServiceServer).GetGauge(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.MetricsService/GetGauge", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - 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: "metrics.proto", -} - -func init() { proto.RegisterFile("metrics.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 256 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x3f, 0x4f, 0xc3, 0x30, - 0x10, 0xc5, 0x6b, 0x5a, 0xfe, 0xf4, 0x70, 0x3b, 0x78, 0xaa, 0xca, 0x40, 0x14, 0x96, 0x4c, 0x11, - 0x82, 0x4f, 0x00, 0x08, 0xa5, 0x0c, 0x5d, 0x82, 0xc4, 0x8a, 0xd2, 0x70, 0xb2, 0x22, 0x39, 0x71, - 0xf0, 0x5d, 0x2a, 0xf1, 0x49, 0x58, 0xf9, 0xa8, 0xc8, 0x4e, 0x55, 0xa5, 0x08, 0x75, 0xb3, 0x7e, - 0xf7, 0xfc, 0xfc, 0x9e, 0x0f, 0x66, 0x35, 0xb2, 0xab, 0x4a, 0x4a, 0x5b, 0x67, 0xd9, 0x2a, 0xa9, - 0x5d, 0x5b, 0xa6, 0x8c, 0xc4, 0x55, 0xa3, 0xe3, 0x6f, 0x01, 0xb3, 0xac, 0xe8, 0x34, 0xe6, 0x48, - 0xad, 0x6d, 0x08, 0x95, 0x82, 0x49, 0x53, 0xd4, 0xb8, 0x10, 0x91, 0x48, 0xa6, 0x79, 0x38, 0xab, - 0x6b, 0x00, 0x63, 0x1b, 0xfd, 0xbe, 0x2d, 0x4c, 0x87, 0x8b, 0x93, 0x48, 0x24, 0xe3, 0xd5, 0x28, - 0x9f, 0x7a, 0xf6, 0xe6, 0x91, 0xba, 0x01, 0xf9, 0x61, 0xbb, 0x8d, 0xc1, 0x9d, 0x64, 0x1c, 0x89, - 0x44, 0xac, 0x46, 0xf9, 0x65, 0x4f, 0xf7, 0x22, 0x62, 0x57, 0xed, 0x7d, 0x26, 0xfe, 0x05, 0x2f, - 0xea, 0x69, 0x10, 0x3d, 0x9e, 0xc3, 0x69, 0x98, 0xc6, 0x31, 0xc8, 0x5d, 0xb0, 0xcf, 0x0e, 0x89, - 0xff, 0xcb, 0x15, 0xcf, 0x41, 0x3e, 0xd7, 0x2d, 0x7f, 0xad, 0x91, 0xa8, 0xd0, 0x78, 0xf7, 0x23, - 0x60, 0xbe, 0xee, 0xdb, 0xbe, 0xa2, 0xdb, 0x56, 0x25, 0xaa, 0x17, 0x90, 0x19, 0xf2, 0x83, 0x31, - 0xc1, 0x8c, 0xd4, 0x32, 0x1d, 0xf6, 0x4f, 0x87, 0xd7, 0x97, 0x57, 0x87, 0xb3, 0x83, 0x7f, 0xb9, - 0x15, 0xea, 0x09, 0x2e, 0x32, 0xe4, 0x40, 0xff, 0xda, 0x0c, 0x93, 0x1e, 0xb5, 0xd9, 0x9c, 0x85, - 0x2d, 0xdc, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x5e, 0x7d, 0xb2, 0xc9, 0x96, 0x01, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/stress/grpc_testing/metrics.proto b/vendor/google.golang.org/grpc/stress/grpc_testing/metrics.proto deleted file mode 100644 index 695040064..000000000 --- a/vendor/google.golang.org/grpc/stress/grpc_testing/metrics.proto +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2015-2016 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Contains the definitions for a metrics service and the type of metrics -// exposed by the service. -// -// Currently, 'Gauge' (i.e a metric that represents the measured value of -// something at an instant of time) is the only metric type supported by the -// service. -syntax = "proto3"; - -package grpc.testing; - -// Response message containing the gauge name and value -message GaugeResponse { - string name = 1; - oneof value { - int64 long_value = 2; - double double_value = 3; - string string_value = 4; - } -} - -// Request message containing the gauge name -message GaugeRequest { - string name = 1; -} - -message EmptyMessage {} - -service MetricsService { - // Returns the values of all the gauges that are currently being maintained by - // the service - rpc GetAllGauges(EmptyMessage) returns (stream GaugeResponse); - - // Returns the value of one gauge - rpc GetGauge(GaugeRequest) returns (GaugeResponse); -} diff --git a/vendor/google.golang.org/grpc/stress/metrics_client/main.go b/vendor/google.golang.org/grpc/stress/metrics_client/main.go deleted file mode 100644 index 6405ec85e..000000000 --- a/vendor/google.golang.org/grpc/stress/metrics_client/main.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "fmt" - "io" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/grpclog" - metricspb "google.golang.org/grpc/stress/grpc_testing" -) - -var ( - metricsServerAddress = flag.String("metrics_server_address", "", "The metrics server addresses in the fomrat <hostname>:<port>") - totalOnly = flag.Bool("total_only", false, "If true, this prints only the total value of all gauges") -) - -func printMetrics(client metricspb.MetricsServiceClient, totalOnly bool) { - stream, err := client.GetAllGauges(context.Background(), &metricspb.EmptyMessage{}) - if err != nil { - grpclog.Fatalf("failed to call GetAllGuages: %v", err) - } - - var ( - overallQPS int64 - rpcStatus error - ) - for { - gaugeResponse, err := stream.Recv() - if err != nil { - rpcStatus = err - break - } - if _, ok := gaugeResponse.GetValue().(*metricspb.GaugeResponse_LongValue); !ok { - panic(fmt.Sprintf("gauge %s is not a long value", gaugeResponse.Name)) - } - v := gaugeResponse.GetLongValue() - if !totalOnly { - grpclog.Printf("%s: %d", gaugeResponse.Name, v) - } - overallQPS += v - } - if rpcStatus != io.EOF { - grpclog.Fatalf("failed to finish server streaming: %v", rpcStatus) - } - grpclog.Printf("overall qps: %d", overallQPS) -} - -func main() { - flag.Parse() - if *metricsServerAddress == "" { - grpclog.Fatalf("Metrics server address is empty.") - } - - conn, err := grpc.Dial(*metricsServerAddress, grpc.WithInsecure()) - if err != nil { - grpclog.Fatalf("cannot connect to metrics server: %v", err) - } - defer conn.Close() - - c := metricspb.NewMetricsServiceClient(conn) - printMetrics(c, *totalOnly) -} diff --git a/vendor/google.golang.org/grpc/test/bufconn/bufconn.go b/vendor/google.golang.org/grpc/test/bufconn/bufconn.go deleted file mode 100644 index bc0ab839f..000000000 --- a/vendor/google.golang.org/grpc/test/bufconn/bufconn.go +++ /dev/null @@ -1,229 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package bufconn provides a net.Conn implemented by a buffer and related -// dialing and listening functionality. -package bufconn - -import ( - "fmt" - "io" - "net" - "sync" - "time" -) - -// Listener implements a net.Listener that creates local, buffered net.Conns -// via its Accept and Dial method. -type Listener struct { - mu sync.Mutex - sz int - ch chan net.Conn - done chan struct{} -} - -var errClosed = fmt.Errorf("Closed") - -// Listen returns a Listener that can only be contacted by its own Dialers and -// creates buffered connections between the two. -func Listen(sz int) *Listener { - return &Listener{sz: sz, ch: make(chan net.Conn), done: make(chan struct{})} -} - -// Accept blocks until Dial is called, then returns a net.Conn for the server -// half of the connection. -func (l *Listener) Accept() (net.Conn, error) { - select { - case <-l.done: - return nil, errClosed - case c := <-l.ch: - return c, nil - } -} - -// Close stops the listener. -func (l *Listener) Close() error { - l.mu.Lock() - defer l.mu.Unlock() - select { - case <-l.done: - // Already closed. - break - default: - close(l.done) - } - return nil -} - -// Addr reports the address of the listener. -func (l *Listener) Addr() net.Addr { return addr{} } - -// Dial creates an in-memory full-duplex network connection, unblocks Accept by -// providing it the server half of the connection, and returns the client half -// of the connection. -func (l *Listener) Dial() (net.Conn, error) { - p1, p2 := newPipe(l.sz), newPipe(l.sz) - select { - case <-l.done: - return nil, errClosed - case l.ch <- &conn{p1, p2}: - return &conn{p2, p1}, nil - } -} - -type pipe struct { - mu sync.Mutex - - // buf contains the data in the pipe. It is a ring buffer of fixed capacity, - // with r and w pointing to the offset to read and write, respsectively. - // - // Data is read between [r, w) and written to [w, r), wrapping around the end - // of the slice if necessary. - // - // The buffer is empty if r == len(buf), otherwise if r == w, it is full. - // - // w and r are always in the range [0, cap(buf)) and [0, len(buf)]. - buf []byte - w, r int - - wwait sync.Cond - rwait sync.Cond - closed bool -} - -func newPipe(sz int) *pipe { - p := &pipe{buf: make([]byte, 0, sz)} - p.wwait.L = &p.mu - p.rwait.L = &p.mu - return p -} - -func (p *pipe) empty() bool { - return p.r == len(p.buf) -} - -func (p *pipe) full() bool { - return p.r < len(p.buf) && p.r == p.w -} - -func (p *pipe) Read(b []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - // Block until p has data. - for { - if p.closed { - return 0, io.ErrClosedPipe - } - if !p.empty() { - break - } - p.rwait.Wait() - } - wasFull := p.full() - - n = copy(b, p.buf[p.r:len(p.buf)]) - p.r += n - if p.r == cap(p.buf) { - p.r = 0 - p.buf = p.buf[:p.w] - } - - // Signal a blocked writer, if any - if wasFull { - p.wwait.Signal() - } - - return n, nil -} - -func (p *pipe) Write(b []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - if p.closed { - return 0, io.ErrClosedPipe - } - for len(b) > 0 { - // Block until p is not full. - for { - if p.closed { - return 0, io.ErrClosedPipe - } - if !p.full() { - break - } - p.wwait.Wait() - } - wasEmpty := p.empty() - - end := cap(p.buf) - if p.w < p.r { - end = p.r - } - x := copy(p.buf[p.w:end], b) - b = b[x:] - n += x - p.w += x - if p.w > len(p.buf) { - p.buf = p.buf[:p.w] - } - if p.w == cap(p.buf) { - p.w = 0 - } - - // Signal a blocked reader, if any. - if wasEmpty { - p.rwait.Signal() - } - } - return n, nil -} - -func (p *pipe) Close() error { - p.mu.Lock() - defer p.mu.Unlock() - p.closed = true - // Signal all blocked readers and writers to return an error. - p.rwait.Broadcast() - p.wwait.Broadcast() - return nil -} - -type conn struct { - io.ReadCloser - io.WriteCloser -} - -func (c *conn) Close() error { - err1 := c.ReadCloser.Close() - err2 := c.WriteCloser.Close() - if err1 != nil { - return err1 - } - return err2 -} - -func (*conn) LocalAddr() net.Addr { return addr{} } -func (*conn) RemoteAddr() net.Addr { return addr{} } -func (c *conn) SetDeadline(t time.Time) error { return fmt.Errorf("unsupported") } -func (c *conn) SetReadDeadline(t time.Time) error { return fmt.Errorf("unsupported") } -func (c *conn) SetWriteDeadline(t time.Time) error { return fmt.Errorf("unsupported") } - -type addr struct{} - -func (addr) Network() string { return "bufconn" } -func (addr) String() string { return "bufconn" } diff --git a/vendor/google.golang.org/grpc/test/bufconn/bufconn_test.go b/vendor/google.golang.org/grpc/test/bufconn/bufconn_test.go deleted file mode 100644 index 0f7bc2227..000000000 --- a/vendor/google.golang.org/grpc/test/bufconn/bufconn_test.go +++ /dev/null @@ -1,149 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package bufconn - -import ( - "fmt" - "io" - "net" - "reflect" - "testing" - "time" -) - -func testRW(r io.Reader, w io.Writer) error { - for i := 0; i < 20; i++ { - d := make([]byte, i) - for j := 0; j < i; j++ { - d[j] = byte(i - j) - } - var rn int - var rerr error - b := make([]byte, i) - done := make(chan struct{}) - go func() { - for rn < len(b) && rerr == nil { - var x int - x, rerr = r.Read(b[rn:]) - rn += x - } - close(done) - }() - wn, werr := w.Write(d) - if wn != i || werr != nil { - return fmt.Errorf("%v: w.Write(%v) = %v, %v; want %v, nil", i, d, wn, werr, i) - } - select { - case <-done: - case <-time.After(500 * time.Millisecond): - return fmt.Errorf("%v: r.Read never returned", i) - } - if rn != i || rerr != nil { - return fmt.Errorf("%v: r.Read = %v, %v; want %v, nil", i, rn, rerr, i) - } - if !reflect.DeepEqual(b, d) { - return fmt.Errorf("%v: r.Read read %v; want %v", i, b, d) - } - } - return nil -} - -func TestPipe(t *testing.T) { - p := newPipe(10) - if err := testRW(p, p); err != nil { - t.Fatalf(err.Error()) - } -} - -func TestPipeClose(t *testing.T) { - p := newPipe(10) - p.Close() - if _, err := p.Write(nil); err != io.ErrClosedPipe { - t.Fatalf("p.Write = _, %v; want _, %v", err, io.ErrClosedPipe) - } - if _, err := p.Read(nil); err != io.ErrClosedPipe { - t.Fatalf("p.Read = _, %v; want _, %v", err, io.ErrClosedPipe) - } -} - -func TestConn(t *testing.T) { - p1, p2 := newPipe(10), newPipe(10) - c1, c2 := &conn{p1, p2}, &conn{p2, p1} - - if err := testRW(c1, c2); err != nil { - t.Fatalf(err.Error()) - } - if err := testRW(c2, c1); err != nil { - t.Fatalf(err.Error()) - } -} - -func TestListener(t *testing.T) { - l := Listen(7) - var s net.Conn - var serr error - done := make(chan struct{}) - go func() { - s, serr = l.Accept() - close(done) - }() - c, cerr := l.Dial() - <-done - if cerr != nil || serr != nil { - t.Fatalf("cerr = %v, serr = %v; want nil, nil", cerr, serr) - } - if err := testRW(c, s); err != nil { - t.Fatalf(err.Error()) - } - if err := testRW(s, c); err != nil { - t.Fatalf(err.Error()) - } -} - -func TestCloseWhileDialing(t *testing.T) { - l := Listen(7) - var c net.Conn - var err error - done := make(chan struct{}) - go func() { - c, err = l.Dial() - close(done) - }() - l.Close() - <-done - if c != nil || err != errClosed { - t.Fatalf("c, err = %v, %v; want nil, %v", c, err, errClosed) - } -} - -func TestCloseWhileAccepting(t *testing.T) { - l := Listen(7) - var c net.Conn - var err error - done := make(chan struct{}) - go func() { - c, err = l.Accept() - close(done) - }() - l.Close() - <-done - if c != nil || err != errClosed { - t.Fatalf("c, err = %v, %v; want nil, %v", c, err, errClosed) - } -} diff --git a/vendor/google.golang.org/grpc/test/codec_perf/perf.pb.go b/vendor/google.golang.org/grpc/test/codec_perf/perf.pb.go deleted file mode 100644 index 9401b1dd8..000000000 --- a/vendor/google.golang.org/grpc/test/codec_perf/perf.pb.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: codec_perf/perf.proto - -/* -Package codec_perf is a generated protocol buffer package. - -It is generated from these files: - codec_perf/perf.proto - -It has these top-level messages: - Buffer -*/ -package codec_perf - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Buffer is a message that contains a body of bytes that is used to exercise -// encoding and decoding overheads. -type Buffer struct { - Body []byte `protobuf:"bytes,1,opt,name=body" json:"body,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Buffer) Reset() { *m = Buffer{} } -func (m *Buffer) String() string { return proto.CompactTextString(m) } -func (*Buffer) ProtoMessage() {} -func (*Buffer) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *Buffer) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -func init() { - proto.RegisterType((*Buffer)(nil), "codec.perf.Buffer") -} - -func init() { proto.RegisterFile("codec_perf/perf.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 78 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0xce, 0x4f, 0x49, - 0x4d, 0x8e, 0x2f, 0x48, 0x2d, 0x4a, 0xd3, 0x07, 0x11, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, - 0x5c, 0x60, 0x61, 0x3d, 0x90, 0x88, 0x92, 0x0c, 0x17, 0x9b, 0x53, 0x69, 0x5a, 0x5a, 0x6a, 0x91, - 0x90, 0x10, 0x17, 0x4b, 0x52, 0x7e, 0x4a, 0xa5, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x4f, 0x10, 0x98, - 0x0d, 0x08, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x93, 0x4c, 0x5f, 0x41, 0x00, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/test/codec_perf/perf.proto b/vendor/google.golang.org/grpc/test/codec_perf/perf.proto deleted file mode 100644 index f42dbcafe..000000000 --- a/vendor/google.golang.org/grpc/test/codec_perf/perf.proto +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Messages used for performance tests that may not reference grpc directly for -// reasons of import cycles. -syntax = "proto2"; - -package codec.perf; - -// Buffer is a message that contains a body of bytes that is used to exercise -// encoding and decoding overheads. -message Buffer { - optional bytes body = 1; -} diff --git a/vendor/google.golang.org/grpc/test/end2end_test.go b/vendor/google.golang.org/grpc/test/end2end_test.go deleted file mode 100644 index 62ebf905c..000000000 --- a/vendor/google.golang.org/grpc/test/end2end_test.go +++ /dev/null @@ -1,5030 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. codec_perf/perf.proto -//go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto - -package test - -import ( - "bytes" - "crypto/tls" - "errors" - "flag" - "fmt" - "io" - "math" - "net" - "os" - "reflect" - "runtime" - "strings" - "sync" - "sync/atomic" - "syscall" - "testing" - "time" - - "github.com/golang/protobuf/proto" - anypb "github.com/golang/protobuf/ptypes/any" - "golang.org/x/net/context" - "golang.org/x/net/http2" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc" - "google.golang.org/grpc/balancer" - _ "google.golang.org/grpc/balancer/roundrobin" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/health" - healthpb "google.golang.org/grpc/health/grpc_health_v1" - "google.golang.org/grpc/internal" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - _ "google.golang.org/grpc/resolver/passthrough" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" - testpb "google.golang.org/grpc/test/grpc_testing" - "google.golang.org/grpc/test/leakcheck" - "google.golang.org/grpc/testdata" -) - -var ( - // For headers: - testMetadata = metadata.MD{ - "key1": []string{"value1"}, - "key2": []string{"value2"}, - "key3-bin": []string{"binvalue1", string([]byte{1, 2, 3})}, - } - testMetadata2 = metadata.MD{ - "key1": []string{"value12"}, - "key2": []string{"value22"}, - } - // For trailers: - testTrailerMetadata = metadata.MD{ - "tkey1": []string{"trailerValue1"}, - "tkey2": []string{"trailerValue2"}, - "tkey3-bin": []string{"trailerbinvalue1", string([]byte{3, 2, 1})}, - } - testTrailerMetadata2 = metadata.MD{ - "tkey1": []string{"trailerValue12"}, - "tkey2": []string{"trailerValue22"}, - } - // capital "Key" is illegal in HTTP/2. - malformedHTTP2Metadata = metadata.MD{ - "Key": []string{"foo"}, - } - testAppUA = "myApp1/1.0 myApp2/0.9" - failAppUA = "fail-this-RPC" - detailedError = status.ErrorProto(&spb.Status{ - Code: int32(codes.DataLoss), - Message: "error for testing: " + failAppUA, - Details: []*anypb.Any{{ - TypeUrl: "url", - Value: []byte{6, 0, 0, 6, 1, 3}, - }}, - }) -) - -var raceMode bool // set by race.go in race mode - -type testServer struct { - security string // indicate the authentication protocol used by this server. - earlyFail bool // whether to error out the execution of a service handler prematurely. - setAndSendHeader bool // whether to call setHeader and sendHeader. - setHeaderOnly bool // whether to only call setHeader, not sendHeader. - multipleSetTrailer bool // whether to call setTrailer multiple times. - unaryCallSleepTime time.Duration -} - -func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - if md, ok := metadata.FromIncomingContext(ctx); ok { - // For testing purpose, returns an error if user-agent is failAppUA. - // To test that client gets the correct error. - if ua, ok := md["user-agent"]; !ok || strings.HasPrefix(ua[0], failAppUA) { - return nil, detailedError - } - var str []string - for _, entry := range md["user-agent"] { - str = append(str, "ua", entry) - } - grpc.SendHeader(ctx, metadata.Pairs(str...)) - } - return new(testpb.Empty), nil -} - -func newPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) { - if size < 0 { - return nil, fmt.Errorf("Requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - return nil, fmt.Errorf("PayloadType UNCOMPRESSABLE is not supported") - default: - return nil, fmt.Errorf("Unsupported payload type: %d", t) - } - return &testpb.Payload{ - Type: t.Enum(), - Body: body, - }, nil -} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - md, ok := metadata.FromIncomingContext(ctx) - if ok { - if _, exists := md[":authority"]; !exists { - return nil, grpc.Errorf(codes.DataLoss, "expected an :authority metadata: %v", md) - } - if s.setAndSendHeader { - if err := grpc.SetHeader(ctx, md); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SetHeader(_, %v) = %v, want <nil>", md, err) - } - if err := grpc.SendHeader(ctx, testMetadata2); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SendHeader(_, %v) = %v, want <nil>", testMetadata2, err) - } - } else if s.setHeaderOnly { - if err := grpc.SetHeader(ctx, md); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SetHeader(_, %v) = %v, want <nil>", md, err) - } - if err := grpc.SetHeader(ctx, testMetadata2); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SetHeader(_, %v) = %v, want <nil>", testMetadata2, err) - } - } else { - if err := grpc.SendHeader(ctx, md); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SendHeader(_, %v) = %v, want <nil>", md, err) - } - } - if err := grpc.SetTrailer(ctx, testTrailerMetadata); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SetTrailer(_, %v) = %v, want <nil>", testTrailerMetadata, err) - } - if s.multipleSetTrailer { - if err := grpc.SetTrailer(ctx, testTrailerMetadata2); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SetTrailer(_, %v) = %v, want <nil>", testTrailerMetadata2, err) - } - } - } - pr, ok := peer.FromContext(ctx) - if !ok { - return nil, grpc.Errorf(codes.DataLoss, "failed to get peer from ctx") - } - if pr.Addr == net.Addr(nil) { - return nil, grpc.Errorf(codes.DataLoss, "failed to get peer address") - } - if s.security != "" { - // Check Auth info - var authType, serverName string - switch info := pr.AuthInfo.(type) { - case credentials.TLSInfo: - authType = info.AuthType() - serverName = info.State.ServerName - default: - return nil, grpc.Errorf(codes.Unauthenticated, "Unknown AuthInfo type") - } - if authType != s.security { - return nil, grpc.Errorf(codes.Unauthenticated, "Wrong auth type: got %q, want %q", authType, s.security) - } - if serverName != "x.test.youtube.com" { - return nil, grpc.Errorf(codes.Unauthenticated, "Unknown server name %q", serverName) - } - } - // Simulate some service delay. - time.Sleep(s.unaryCallSleepTime) - - payload, err := newPayload(in.GetResponseType(), in.GetResponseSize()) - if err != nil { - return nil, err - } - - return &testpb.SimpleResponse{ - Payload: payload, - }, nil -} - -func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { - if md, ok := metadata.FromIncomingContext(stream.Context()); ok { - if _, exists := md[":authority"]; !exists { - return grpc.Errorf(codes.DataLoss, "expected an :authority metadata: %v", md) - } - // For testing purpose, returns an error if user-agent is failAppUA. - // To test that client gets the correct error. - if ua, ok := md["user-agent"]; !ok || strings.HasPrefix(ua[0], failAppUA) { - return grpc.Errorf(codes.DataLoss, "error for testing: "+failAppUA) - } - } - cs := args.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - - payload, err := newPayload(args.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: payload, - }); err != nil { - return err - } - } - return nil -} - -func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { - var sum int - for { - in, err := stream.Recv() - if err == io.EOF { - return stream.SendAndClose(&testpb.StreamingInputCallResponse{ - AggregatedPayloadSize: proto.Int32(int32(sum)), - }) - } - if err != nil { - return err - } - p := in.GetPayload().GetBody() - sum += len(p) - if s.earlyFail { - return grpc.Errorf(codes.NotFound, "not found") - } - } -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if s.setAndSendHeader { - if err := stream.SetHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SetHeader(_, %v) = %v, want <nil>", stream, md, err) - } - if err := stream.SendHeader(testMetadata2); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(_, %v) = %v, want <nil>", stream, testMetadata2, err) - } - } else if s.setHeaderOnly { - if err := stream.SetHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SetHeader(_, %v) = %v, want <nil>", stream, md, err) - } - if err := stream.SetHeader(testMetadata2); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SetHeader(_, %v) = %v, want <nil>", stream, testMetadata2, err) - } - } else { - if err := stream.SendHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - } - stream.SetTrailer(testTrailerMetadata) - if s.multipleSetTrailer { - stream.SetTrailer(testTrailerMetadata2) - } - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return nil - } - if err != nil { - // to facilitate testSvrWriteStatusEarlyWrite - if grpc.Code(err) == codes.ResourceExhausted { - return grpc.Errorf(codes.Internal, "fake error for test testSvrWriteStatusEarlyWrite. true error: %s", err.Error()) - } - return err - } - cs := in.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - - payload, err := newPayload(in.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: payload, - }); err != nil { - // to facilitate testSvrWriteStatusEarlyWrite - if grpc.Code(err) == codes.ResourceExhausted { - return grpc.Errorf(codes.Internal, "fake error for test testSvrWriteStatusEarlyWrite. true error: %s", err.Error()) - } - return err - } - } - } -} - -func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error { - var msgBuf []*testpb.StreamingOutputCallRequest - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - break - } - if err != nil { - return err - } - msgBuf = append(msgBuf, in) - } - for _, m := range msgBuf { - cs := m.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - - payload, err := newPayload(m.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: payload, - }); err != nil { - return err - } - } - } - return nil -} - -type env struct { - name string - network string // The type of network such as tcp, unix, etc. - security string // The security protocol such as TLS, SSH, etc. - httpHandler bool // whether to use the http.Handler ServerTransport; requires TLS - balancer string // One of "roundrobin", "pickfirst", "v1", or "". - customDialer func(string, string, time.Duration) (net.Conn, error) -} - -func (e env) runnable() bool { - if runtime.GOOS == "windows" && e.network == "unix" { - return false - } - return true -} - -func (e env) dialer(addr string, timeout time.Duration) (net.Conn, error) { - if e.customDialer != nil { - return e.customDialer(e.network, addr, timeout) - } - return net.DialTimeout(e.network, addr, timeout) -} - -var ( - tcpClearEnv = env{name: "tcp-clear-v1-balancer", network: "tcp", balancer: "v1"} - tcpTLSEnv = env{name: "tcp-tls-v1-balancer", network: "tcp", security: "tls", balancer: "v1"} - tcpClearRREnv = env{name: "tcp-clear", network: "tcp", balancer: "roundrobin"} - tcpTLSRREnv = env{name: "tcp-tls", network: "tcp", security: "tls", balancer: "roundrobin"} - handlerEnv = env{name: "handler-tls", network: "tcp", security: "tls", httpHandler: true, balancer: "roundrobin"} - noBalancerEnv = env{name: "no-balancer", network: "tcp", security: "tls"} - allEnv = []env{tcpClearEnv, tcpTLSEnv, tcpClearRREnv, tcpTLSRREnv, handlerEnv, noBalancerEnv} -) - -var onlyEnv = flag.String("only_env", "", "If non-empty, one of 'tcp-clear', 'tcp-tls', 'unix-clear', 'unix-tls', or 'handler-tls' to only run the tests for that environment. Empty means all.") - -func listTestEnv() (envs []env) { - if *onlyEnv != "" { - for _, e := range allEnv { - if e.name == *onlyEnv { - if !e.runnable() { - panic(fmt.Sprintf("--only_env environment %q does not run on %s", *onlyEnv, runtime.GOOS)) - } - return []env{e} - } - } - panic(fmt.Sprintf("invalid --only_env value %q", *onlyEnv)) - } - for _, e := range allEnv { - if e.runnable() { - envs = append(envs, e) - } - } - return envs -} - -// test is an end-to-end test. It should be created with the newTest -// func, modified as needed, and then started with its startServer method. -// It should be cleaned up with the tearDown method. -type test struct { - t *testing.T - e env - - ctx context.Context // valid for life of test, before tearDown - cancel context.CancelFunc - - // Configurable knobs, after newTest returns: - testServer testpb.TestServiceServer // nil means none - healthServer *health.Server // nil means disabled - maxStream uint32 - tapHandle tap.ServerInHandle - maxMsgSize *int - maxClientReceiveMsgSize *int - maxClientSendMsgSize *int - maxServerReceiveMsgSize *int - maxServerSendMsgSize *int - userAgent string - clientCompression bool - serverCompression bool - unaryClientInt grpc.UnaryClientInterceptor - streamClientInt grpc.StreamClientInterceptor - unaryServerInt grpc.UnaryServerInterceptor - streamServerInt grpc.StreamServerInterceptor - unknownHandler grpc.StreamHandler - sc <-chan grpc.ServiceConfig - customCodec grpc.Codec - serverInitialWindowSize int32 - serverInitialConnWindowSize int32 - clientInitialWindowSize int32 - clientInitialConnWindowSize int32 - perRPCCreds credentials.PerRPCCredentials - - // All test dialing is blocking by default. Set this to true if dial - // should be non-blocking. - nonBlockingDial bool - - // srv and srvAddr are set once startServer is called. - srv *grpc.Server - srvAddr string - - cc *grpc.ClientConn // nil until requested via clientConn - restoreLogs func() // nil unless declareLogNoise is used -} - -func (te *test) tearDown() { - if te.cancel != nil { - te.cancel() - te.cancel = nil - } - if te.cc != nil { - te.cc.Close() - te.cc = nil - } - if te.restoreLogs != nil { - te.restoreLogs() - te.restoreLogs = nil - } - if te.srv != nil { - te.srv.Stop() - } -} - -// newTest returns a new test using the provided testing.T and -// environment. It is returned with default values. Tests should -// modify it before calling its startServer and clientConn methods. -func newTest(t *testing.T, e env) *test { - te := &test{ - t: t, - e: e, - maxStream: math.MaxUint32, - } - te.ctx, te.cancel = context.WithCancel(context.Background()) - return te -} - -// startServer starts a gRPC server listening. Callers should defer a -// call to te.tearDown to clean up. -func (te *test) startServer(ts testpb.TestServiceServer) { - te.testServer = ts - te.t.Logf("Running test in %s environment...", te.e.name) - sopts := []grpc.ServerOption{grpc.MaxConcurrentStreams(te.maxStream)} - if te.maxMsgSize != nil { - sopts = append(sopts, grpc.MaxMsgSize(*te.maxMsgSize)) - } - if te.maxServerReceiveMsgSize != nil { - sopts = append(sopts, grpc.MaxRecvMsgSize(*te.maxServerReceiveMsgSize)) - } - if te.maxServerSendMsgSize != nil { - sopts = append(sopts, grpc.MaxSendMsgSize(*te.maxServerSendMsgSize)) - } - if te.tapHandle != nil { - sopts = append(sopts, grpc.InTapHandle(te.tapHandle)) - } - if te.serverCompression { - sopts = append(sopts, - grpc.RPCCompressor(grpc.NewGZIPCompressor()), - grpc.RPCDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.unaryServerInt != nil { - sopts = append(sopts, grpc.UnaryInterceptor(te.unaryServerInt)) - } - if te.streamServerInt != nil { - sopts = append(sopts, grpc.StreamInterceptor(te.streamServerInt)) - } - if te.unknownHandler != nil { - sopts = append(sopts, grpc.UnknownServiceHandler(te.unknownHandler)) - } - if te.serverInitialWindowSize > 0 { - sopts = append(sopts, grpc.InitialWindowSize(te.serverInitialWindowSize)) - } - if te.serverInitialConnWindowSize > 0 { - sopts = append(sopts, grpc.InitialConnWindowSize(te.serverInitialConnWindowSize)) - } - la := "localhost:0" - switch te.e.network { - case "unix": - la = "/tmp/testsock" + fmt.Sprintf("%d", time.Now().UnixNano()) - syscall.Unlink(la) - } - lis, err := net.Listen(te.e.network, la) - if err != nil { - te.t.Fatalf("Failed to listen: %v", err) - } - switch te.e.security { - case "tls": - creds, err := credentials.NewServerTLSFromFile(testdata.Path("server1.pem"), testdata.Path("server1.key")) - if err != nil { - te.t.Fatalf("Failed to generate credentials %v", err) - } - sopts = append(sopts, grpc.Creds(creds)) - case "clientAlwaysFailCred": - sopts = append(sopts, grpc.Creds(clientAlwaysFailCred{})) - case "clientTimeoutCreds": - sopts = append(sopts, grpc.Creds(&clientTimeoutCreds{})) - } - if te.customCodec != nil { - sopts = append(sopts, grpc.CustomCodec(te.customCodec)) - } - s := grpc.NewServer(sopts...) - te.srv = s - if te.e.httpHandler { - internal.TestingUseHandlerImpl(s) - } - if te.healthServer != nil { - healthpb.RegisterHealthServer(s, te.healthServer) - } - if te.testServer != nil { - testpb.RegisterTestServiceServer(s, te.testServer) - } - addr := la - switch te.e.network { - case "unix": - default: - _, port, err := net.SplitHostPort(lis.Addr().String()) - if err != nil { - te.t.Fatalf("Failed to parse listener address: %v", err) - } - addr = "localhost:" + port - } - - go s.Serve(lis) - te.srvAddr = addr -} - -func (te *test) clientConn() *grpc.ClientConn { - if te.cc != nil { - return te.cc - } - opts := []grpc.DialOption{ - grpc.WithDialer(te.e.dialer), - grpc.WithUserAgent(te.userAgent), - } - - if te.sc != nil { - opts = append(opts, grpc.WithServiceConfig(te.sc)) - } - - if te.clientCompression { - opts = append(opts, - grpc.WithCompressor(grpc.NewGZIPCompressor()), - grpc.WithDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.unaryClientInt != nil { - opts = append(opts, grpc.WithUnaryInterceptor(te.unaryClientInt)) - } - if te.streamClientInt != nil { - opts = append(opts, grpc.WithStreamInterceptor(te.streamClientInt)) - } - if te.maxMsgSize != nil { - opts = append(opts, grpc.WithMaxMsgSize(*te.maxMsgSize)) - } - if te.maxClientReceiveMsgSize != nil { - opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(*te.maxClientReceiveMsgSize))) - } - if te.maxClientSendMsgSize != nil { - opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(*te.maxClientSendMsgSize))) - } - switch te.e.security { - case "tls": - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") - if err != nil { - te.t.Fatalf("Failed to load credentials: %v", err) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - case "clientAlwaysFailCred": - opts = append(opts, grpc.WithTransportCredentials(clientAlwaysFailCred{})) - case "clientTimeoutCreds": - opts = append(opts, grpc.WithTransportCredentials(&clientTimeoutCreds{})) - default: - opts = append(opts, grpc.WithInsecure()) - } - // TODO(bar) switch balancer case "pickfirst". - var scheme string - switch te.e.balancer { - case "v1": - opts = append(opts, grpc.WithBalancer(grpc.RoundRobin(nil))) - case "roundrobin": - rr := balancer.Get("roundrobin") - if rr == nil { - te.t.Fatalf("got nil when trying to get roundrobin balancer builder") - } - opts = append(opts, grpc.WithBalancerBuilder(rr)) - scheme = "passthrough:///" - } - if te.clientInitialWindowSize > 0 { - opts = append(opts, grpc.WithInitialWindowSize(te.clientInitialWindowSize)) - } - if te.clientInitialConnWindowSize > 0 { - opts = append(opts, grpc.WithInitialConnWindowSize(te.clientInitialConnWindowSize)) - } - if te.perRPCCreds != nil { - opts = append(opts, grpc.WithPerRPCCredentials(te.perRPCCreds)) - } - if te.customCodec != nil { - opts = append(opts, grpc.WithCodec(te.customCodec)) - } - if !te.nonBlockingDial && te.srvAddr != "" { - // Only do a blocking dial if server is up. - opts = append(opts, grpc.WithBlock()) - } - var err error - te.cc, err = grpc.Dial(scheme+te.srvAddr, opts...) - if err != nil { - te.t.Fatalf("Dial(%q) = %v", scheme+te.srvAddr, err) - } - return te.cc -} - -func (te *test) declareLogNoise(phrases ...string) { - te.restoreLogs = declareLogNoise(te.t, phrases...) -} - -func (te *test) withServerTester(fn func(st *serverTester)) { - c, err := te.e.dialer(te.srvAddr, 10*time.Second) - if err != nil { - te.t.Fatal(err) - } - defer c.Close() - if te.e.security == "tls" { - c = tls.Client(c, &tls.Config{ - InsecureSkipVerify: true, - NextProtos: []string{http2.NextProtoTLS}, - }) - } - st := newServerTesterFromConn(te.t, c) - st.greet() - fn(st) -} - -type lazyConn struct { - net.Conn - beLazy int32 -} - -func (l *lazyConn) Write(b []byte) (int, error) { - if atomic.LoadInt32(&(l.beLazy)) == 1 { - // The sleep duration here needs to less than the leakCheck deadline. - time.Sleep(time.Second) - } - return l.Conn.Write(b) -} - -func TestContextDeadlineNotIgnored(t *testing.T) { - defer leakcheck.Check(t) - e := noBalancerEnv - var lc *lazyConn - e.customDialer = func(network, addr string, timeout time.Duration) (net.Conn, error) { - conn, err := net.DialTimeout(network, addr, timeout) - if err != nil { - return nil, err - } - lc = &lazyConn{Conn: conn} - return lc, nil - } - - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err) - } - atomic.StoreInt32(&(lc.beLazy), 1) - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - t1 := time.Now() - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, context.DeadlineExceeded", err) - } - if time.Since(t1) > 2*time.Second { - t.Fatalf("TestService/EmptyCall(_, _) ran over the deadline") - } -} - -func TestTimeoutOnDeadServer(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testTimeoutOnDeadServer(t, e) - } -} - -func testTimeoutOnDeadServer(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err) - } - te.srv.Stop() - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)) - cancel() - if e.balancer != "" && grpc.Code(err) != codes.DeadlineExceeded { - // If e.balancer == nil, the ac will stop reconnecting because the dialer returns non-temp error, - // the error will be an internal error. - t.Fatalf("TestService/EmptyCall(%v, _) = _, %v, want _, error code: %s", ctx, err, codes.DeadlineExceeded) - } - awaitNewConnLogOutput() -} - -func TestServerGracefulStopIdempotent(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerGracefulStopIdempotent(t, e) - } -} - -func testServerGracefulStopIdempotent(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - for i := 0; i < 3; i++ { - te.srv.GracefulStop() - } -} - -func TestServerGoAway(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerGoAway(t, e) - } -} - -func testServerGoAway(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err) - } - ch := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch) - }() - // Loop until the server side GoAway signal is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil && grpc.Code(err) != codes.DeadlineExceeded { - cancel() - break - } - cancel() - } - // A new RPC should fail. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.Unavailable && grpc.Code(err) != codes.Internal { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s or %s", err, codes.Unavailable, codes.Internal) - } - <-ch - awaitNewConnLogOutput() -} - -func TestServerGoAwayPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerGoAwayPendingRPC(t, e) - } -} - -func testServerGoAwayPendingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithCancel(context.Background()) - stream, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err) - } - ch := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch) - }() - // Loop until the server side GoAway signal is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); err != nil { - cancel() - break - } - cancel() - } - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(1), - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - // The existing RPC should be still good to proceed. - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, <nil>", stream, err) - } - cancel() - <-ch - awaitNewConnLogOutput() -} - -func TestServerMultipleGoAwayPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerMultipleGoAwayPendingRPC(t, e) - } -} - -func testServerMultipleGoAwayPendingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithCancel(context.Background()) - stream, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err) - } - ch1 := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch1) - }() - ch2 := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch2) - }() - // Loop until the server side GoAway signal is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); err != nil { - cancel() - break - } - cancel() - } - select { - case <-ch1: - t.Fatal("GracefulStop() terminated early") - case <-ch2: - t.Fatal("GracefulStop() terminated early") - default: - } - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(1), - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - // The existing RPC should be still good to proceed. - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, <nil>", stream, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() = %v, want <nil>", stream, err) - } - <-ch1 - <-ch2 - cancel() - awaitNewConnLogOutput() -} - -func TestConcurrentClientConnCloseAndServerGoAway(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testConcurrentClientConnCloseAndServerGoAway(t, e) - } -} - -func testConcurrentClientConnCloseAndServerGoAway(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err) - } - ch := make(chan struct{}) - // Close ClientConn and Server concurrently. - go func() { - te.srv.GracefulStop() - close(ch) - }() - go func() { - cc.Close() - }() - <-ch -} - -func TestConcurrentServerStopAndGoAway(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testConcurrentServerStopAndGoAway(t, e) - } -} - -func testConcurrentServerStopAndGoAway(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - stream, err := tc.FullDuplexCall(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, <nil>", tc, err) - } - ch := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch) - }() - // Loop until the server side GoAway signal is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); err != nil { - cancel() - break - } - cancel() - } - // Stop the server and close all the connections. - te.srv.Stop() - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(1), - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(req); err == nil { - if _, err := stream.Recv(); err == nil { - t.Fatalf("%v.Recv() = _, %v, want _, <nil>", stream, err) - } - } - <-ch - awaitNewConnLogOutput() -} - -func TestClientConnCloseAfterGoAwayWithActiveStream(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testClientConnCloseAfterGoAwayWithActiveStream(t, e) - } -} - -func testClientConnCloseAfterGoAwayWithActiveStream(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - if _, err := tc.FullDuplexCall(context.Background()); err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want _, <nil>", tc, err) - } - done := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(done) - }() - time.Sleep(50 * time.Millisecond) - cc.Close() - timeout := time.NewTimer(time.Second) - select { - case <-done: - case <-timeout.C: - t.Fatalf("Test timed-out.") - } -} - -func TestFailFast(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testFailFast(t, e) - } -} - -func testFailFast(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err) - } - // Stop the server and tear down all the exisiting connections. - te.srv.Stop() - // Loop until the server teardown is propagated to the client. - for { - _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}) - if grpc.Code(err) == codes.Unavailable { - break - } - fmt.Printf("%v.EmptyCall(_, _) = _, %v", tc, err) - time.Sleep(10 * time.Millisecond) - } - // The client keeps reconnecting and ongoing fail-fast RPCs should fail with code.Unavailable. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.Unavailable { - t.Fatalf("TestService/EmptyCall(_, _, _) = _, %v, want _, error code: %s", err, codes.Unavailable) - } - if _, err := tc.StreamingInputCall(context.Background()); grpc.Code(err) != codes.Unavailable { - t.Fatalf("TestService/StreamingInputCall(_) = _, %v, want _, error code: %s", err, codes.Unavailable) - } - - awaitNewConnLogOutput() -} - -func testServiceConfigSetup(t *testing.T, e env) (*test, chan grpc.ServiceConfig) { - te := newTest(t, e) - // We write before read. - ch := make(chan grpc.ServiceConfig, 1) - te.sc = ch - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - return te, ch -} - -func newBool(b bool) (a *bool) { - return &b -} - -func newInt(b int) (a *int) { - return &b -} - -func newDuration(b time.Duration) (a *time.Duration) { - a = new(time.Duration) - *a = b - return -} - -func TestServiceConfigGetMethodConfig(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testGetMethodConfig(t, e) - } -} - -func testGetMethodConfig(t *testing.T, e env) { - te, ch := testServiceConfigSetup(t, e) - defer te.tearDown() - - mc1 := grpc.MethodConfig{ - WaitForReady: newBool(true), - Timeout: newDuration(time.Millisecond), - } - mc2 := grpc.MethodConfig{WaitForReady: newBool(false)} - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc1 - m["/grpc.testing.TestService/"] = mc2 - sc := grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - - m = make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/UnaryCall"] = mc1 - m["/grpc.testing.TestService/"] = mc2 - sc = grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - // Wait for the new service config to propagate. - for { - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) == codes.DeadlineExceeded { - continue - } - break - } - // The following RPCs are expected to become fail-fast. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.Unavailable { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.Unavailable) - } -} - -func TestServiceConfigWaitForReady(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServiceConfigWaitForReady(t, e) - } -} - -func testServiceConfigWaitForReady(t *testing.T, e env) { - te, ch := testServiceConfigSetup(t, e) - defer te.tearDown() - - // Case1: Client API set failfast to be false, and service config set wait_for_ready to be false, Client API should win, and the rpc will wait until deadline exceeds. - mc := grpc.MethodConfig{ - WaitForReady: newBool(false), - Timeout: newDuration(time.Millisecond), - } - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc := grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - if _, err := tc.FullDuplexCall(context.Background(), grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - - // Generate a service config update. - // Case2: Client API does not set failfast, and service config set wait_for_ready to be true, and the rpc will wait until deadline exceeds. - mc.WaitForReady = newBool(true) - m = make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc = grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - // Wait for the new service config to take effect. - mc = cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall") - for { - if !*mc.WaitForReady { - time.Sleep(100 * time.Millisecond) - mc = cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall") - continue - } - break - } - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - if _, err := tc.FullDuplexCall(context.Background()); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } -} - -func TestServiceConfigTimeout(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServiceConfigTimeout(t, e) - } -} - -func testServiceConfigTimeout(t *testing.T, e env) { - te, ch := testServiceConfigSetup(t, e) - defer te.tearDown() - - // Case1: Client API sets timeout to be 1ns and ServiceConfig sets timeout to be 1hr. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds. - mc := grpc.MethodConfig{ - Timeout: newDuration(time.Hour), - } - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc := grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // The following RPCs are expected to become non-fail-fast ones with 1ns deadline. - ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - cancel() - ctx, cancel = context.WithTimeout(context.Background(), time.Nanosecond) - if _, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - cancel() - - // Generate a service config update. - // Case2: Client API sets timeout to be 1hr and ServiceConfig sets timeout to be 1ns. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds. - mc.Timeout = newDuration(time.Nanosecond) - m = make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc = grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - // Wait for the new service config to take effect. - mc = cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall") - for { - if *mc.Timeout != time.Nanosecond { - time.Sleep(100 * time.Millisecond) - mc = cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall") - continue - } - break - } - - ctx, cancel = context.WithTimeout(context.Background(), time.Hour) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - cancel() - - ctx, cancel = context.WithTimeout(context.Background(), time.Hour) - if _, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - cancel() -} - -func TestServiceConfigMaxMsgSize(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServiceConfigMaxMsgSize(t, e) - } -} - -func testServiceConfigMaxMsgSize(t *testing.T, e env) { - // Setting up values and objects shared across all test cases. - const smallSize = 1 - const largeSize = 1024 - const extraLargeSize = 2048 - - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize) - if err != nil { - t.Fatal(err) - } - - mc := grpc.MethodConfig{ - MaxReqSize: newInt(extraLargeSize), - MaxRespSize: newInt(extraLargeSize), - } - - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/UnaryCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc := grpc.ServiceConfig{ - Methods: m, - } - // Case1: sc set maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te1, ch1 := testServiceConfigSetup(t, e) - te1.startServer(&testServer{security: e.security}) - defer te1.tearDown() - - ch1 <- sc - tc := testpb.NewTestServiceClient(te1.clientConn()) - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(extraLargeSize)), - Payload: smallPayload, - } - // Test for unary RPC recv. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = extraLargePayload - req.ResponseSize = proto.Int32(int32(smallSize)) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(extraLargeSize)), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: smallPayload, - } - stream, err := tc.FullDuplexCall(te1.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = proto.Int32(int32(smallSize)) - sreq.Payload = extraLargePayload - stream, err = tc.FullDuplexCall(te1.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } - - // Case2: Client API set maxReqSize to 1024 (send), maxRespSize to 1024 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te2, ch2 := testServiceConfigSetup(t, e) - te2.maxClientReceiveMsgSize = newInt(1024) - te2.maxClientSendMsgSize = newInt(1024) - te2.startServer(&testServer{security: e.security}) - defer te2.tearDown() - ch2 <- sc - tc = testpb.NewTestServiceClient(te2.clientConn()) - - // Test for unary RPC recv. - req.Payload = smallPayload - req.ResponseSize = proto.Int32(int32(largeSize)) - - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = proto.Int32(int32(smallSize)) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - stream, err = tc.FullDuplexCall(te2.ctx) - respParam[0].Size = proto.Int32(int32(largeSize)) - sreq.Payload = smallPayload - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = proto.Int32(int32(smallSize)) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te2.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } - - // Case3: Client API set maxReqSize to 4096 (send), maxRespSize to 4096 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te3, ch3 := testServiceConfigSetup(t, e) - te3.maxClientReceiveMsgSize = newInt(4096) - te3.maxClientSendMsgSize = newInt(4096) - te3.startServer(&testServer{security: e.security}) - defer te3.tearDown() - ch3 <- sc - tc = testpb.NewTestServiceClient(te3.clientConn()) - - // Test for unary RPC recv. - req.Payload = smallPayload - req.ResponseSize = proto.Int32(int32(largeSize)) - - if _, err := tc.UnaryCall(context.Background(), req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want <nil>", err) - } - - req.ResponseSize = proto.Int32(int32(extraLargeSize)) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = proto.Int32(int32(smallSize)) - if _, err := tc.UnaryCall(context.Background(), req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want <nil>", err) - } - - req.Payload = extraLargePayload - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - stream, err = tc.FullDuplexCall(te3.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - respParam[0].Size = proto.Int32(int32(largeSize)) - sreq.Payload = smallPayload - - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want <nil>", stream, err) - } - - respParam[0].Size = proto.Int32(int32(extraLargeSize)) - - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = proto.Int32(int32(smallSize)) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te3.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - sreq.Payload = extraLargePayload - if err := stream.Send(sreq); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } -} - -func TestMaxMsgSizeClientDefault(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMaxMsgSizeClientDefault(t, e) - } -} - -func testMaxMsgSizeClientDefault(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const smallSize = 1 - const largeSize = 4 * 1024 * 1024 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeSize)), - Payload: smallPayload, - } - // Test for unary RPC recv. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(largeSize)), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: smallPayload, - } - - // Test for streaming RPC recv. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } -} - -func TestMaxMsgSizeClientAPI(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMaxMsgSizeClientAPI(t, e) - } -} - -func testMaxMsgSizeClientAPI(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - // To avoid error on server side. - te.maxServerSendMsgSize = newInt(5 * 1024 * 1024) - te.maxClientReceiveMsgSize = newInt(1024) - te.maxClientSendMsgSize = newInt(1024) - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const smallSize = 1 - const largeSize = 1024 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeSize)), - Payload: smallPayload, - } - // Test for unary RPC recv. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = proto.Int32(int32(smallSize)) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(largeSize)), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: smallPayload, - } - - // Test for streaming RPC recv. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = proto.Int32(int32(smallSize)) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } -} - -func TestMaxMsgSizeServerAPI(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMaxMsgSizeServerAPI(t, e) - } -} - -func testMaxMsgSizeServerAPI(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.maxServerReceiveMsgSize = newInt(1024) - te.maxServerSendMsgSize = newInt(1024) - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const smallSize = 1 - const largeSize = 1024 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(int32(largeSize)), - Payload: smallPayload, - } - // Test for unary RPC send. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC recv. - req.Payload = largePayload - req.ResponseSize = proto.Int32(int32(smallSize)) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(largeSize)), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: smallPayload, - } - - // Test for streaming RPC send. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - respParam[0].Size = proto.Int32(int32(smallSize)) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } -} - -func TestTap(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testTap(t, e) - } -} - -type myTap struct { - cnt int -} - -func (t *myTap) handle(ctx context.Context, info *tap.Info) (context.Context, error) { - if info != nil { - if info.FullMethodName == "/grpc.testing.TestService/EmptyCall" { - t.cnt++ - } else if info.FullMethodName == "/grpc.testing.TestService/UnaryCall" { - return nil, fmt.Errorf("tap error") - } - } - return ctx, nil -} - -func testTap(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - ttap := &myTap{} - te.tapHandle = ttap.handle - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err) - } - if ttap.cnt != 1 { - t.Fatalf("Get the count in ttap %d, want 1", ttap.cnt) - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 31) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(45), - Payload: payload, - } - if _, err := tc.UnaryCall(context.Background(), req); grpc.Code(err) != codes.Unavailable { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, %s", err, codes.Unavailable) - } -} - -func healthCheck(d time.Duration, cc *grpc.ClientConn, serviceName string) (*healthpb.HealthCheckResponse, error) { - ctx, cancel := context.WithTimeout(context.Background(), d) - defer cancel() - hc := healthpb.NewHealthClient(cc) - req := &healthpb.HealthCheckRequest{ - Service: serviceName, - } - return hc.Check(ctx, req) -} - -func TestHealthCheckOnSuccess(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testHealthCheckOnSuccess(t, e) - } -} - -func testHealthCheckOnSuccess(t *testing.T, e env) { - te := newTest(t, e) - hs := health.NewServer() - hs.SetServingStatus("grpc.health.v1.Health", 1) - te.healthServer = hs - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - if _, err := healthCheck(1*time.Second, cc, "grpc.health.v1.Health"); err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err) - } -} - -func TestHealthCheckOnFailure(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testHealthCheckOnFailure(t, e) - } -} - -func testHealthCheckOnFailure(t *testing.T, e env) { - defer leakcheck.Check(t) - te := newTest(t, e) - te.declareLogNoise( - "Failed to dial ", - "grpc: the client connection is closing; please retry", - ) - hs := health.NewServer() - hs.SetServingStatus("grpc.health.v1.HealthCheck", 1) - te.healthServer = hs - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - wantErr := grpc.Errorf(codes.DeadlineExceeded, "context deadline exceeded") - if _, err := healthCheck(0*time.Second, cc, "grpc.health.v1.Health"); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, error code %s", err, codes.DeadlineExceeded) - } - awaitNewConnLogOutput() -} - -func TestHealthCheckOff(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - // TODO(bradfitz): Temporarily skip this env due to #619. - if e.name == "handler-tls" { - continue - } - testHealthCheckOff(t, e) - } -} - -func testHealthCheckOff(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - want := grpc.Errorf(codes.Unimplemented, "unknown service grpc.health.v1.Health") - if _, err := healthCheck(1*time.Second, te.clientConn(), ""); !reflect.DeepEqual(err, want) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, %v", err, want) - } -} - -func TestUnknownHandler(t *testing.T) { - defer leakcheck.Check(t) - // An example unknownHandler that returns a different code and a different method, making sure that we do not - // expose what methods are implemented to a client that is not authenticated. - unknownHandler := func(srv interface{}, stream grpc.ServerStream) error { - return grpc.Errorf(codes.Unauthenticated, "user unauthenticated") - } - for _, e := range listTestEnv() { - // TODO(bradfitz): Temporarily skip this env due to #619. - if e.name == "handler-tls" { - continue - } - testUnknownHandler(t, e, unknownHandler) - } -} - -func testUnknownHandler(t *testing.T, e env, unknownHandler grpc.StreamHandler) { - te := newTest(t, e) - te.unknownHandler = unknownHandler - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - want := grpc.Errorf(codes.Unauthenticated, "user unauthenticated") - if _, err := healthCheck(1*time.Second, te.clientConn(), ""); !reflect.DeepEqual(err, want) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, %v", err, want) - } -} - -func TestHealthCheckServingStatus(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testHealthCheckServingStatus(t, e) - } -} - -func testHealthCheckServingStatus(t *testing.T, e env) { - te := newTest(t, e) - hs := health.NewServer() - te.healthServer = hs - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - out, err := healthCheck(1*time.Second, cc, "") - if err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err) - } - if out.Status != healthpb.HealthCheckResponse_SERVING { - t.Fatalf("Got the serving status %v, want SERVING", out.Status) - } - wantErr := grpc.Errorf(codes.NotFound, "unknown service") - if _, err := healthCheck(1*time.Second, cc, "grpc.health.v1.Health"); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, error code %s", err, codes.NotFound) - } - hs.SetServingStatus("grpc.health.v1.Health", healthpb.HealthCheckResponse_SERVING) - out, err = healthCheck(1*time.Second, cc, "grpc.health.v1.Health") - if err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err) - } - if out.Status != healthpb.HealthCheckResponse_SERVING { - t.Fatalf("Got the serving status %v, want SERVING", out.Status) - } - hs.SetServingStatus("grpc.health.v1.Health", healthpb.HealthCheckResponse_NOT_SERVING) - out, err = healthCheck(1*time.Second, cc, "grpc.health.v1.Health") - if err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, <nil>", err) - } - if out.Status != healthpb.HealthCheckResponse_NOT_SERVING { - t.Fatalf("Got the serving status %v, want NOT_SERVING", out.Status) - } - -} - -func TestErrorChanNoIO(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testErrorChanNoIO(t, e) - } -} - -func testErrorChanNoIO(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - if _, err := tc.FullDuplexCall(context.Background()); err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } -} - -func TestEmptyUnaryWithUserAgent(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testEmptyUnaryWithUserAgent(t, e) - } -} - -func testEmptyUnaryWithUserAgent(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - var header metadata.MD - reply, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Header(&header)) - if err != nil || !proto.Equal(&testpb.Empty{}, reply) { - t.Fatalf("TestService/EmptyCall(_, _) = %v, %v, want %v, <nil>", reply, err, &testpb.Empty{}) - } - if v, ok := header["ua"]; !ok || !strings.HasPrefix(v[0], testAppUA) { - t.Fatalf("header[\"ua\"] = %q, %t, want string with prefix %q, true", v, ok, testAppUA) - } - - te.srv.Stop() -} - -func TestFailedEmptyUnary(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - // This test covers status details, but - // Grpc-Status-Details-Bin is not support in handler_server. - continue - } - testFailedEmptyUnary(t, e) - } -} - -func testFailedEmptyUnary(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = failAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - wantErr := detailedError - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %v", err, wantErr) - } -} - -func TestLargeUnary(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testLargeUnary(t, e) - } -} - -func testLargeUnary(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const argSize = 271828 - const respSize = 314159 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, <nil>", err) - } - pt := reply.GetPayload().GetType() - ps := len(reply.GetPayload().GetBody()) - if pt != testpb.PayloadType_COMPRESSABLE || ps != respSize { - t.Fatalf("Got the reply with type %d len %d; want %d, %d", pt, ps, testpb.PayloadType_COMPRESSABLE, respSize) - } -} - -// Test backward-compatibility API for setting msg size limit. -func TestExceedMsgLimit(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testExceedMsgLimit(t, e) - } -} - -func testExceedMsgLimit(t *testing.T, e env) { - te := newTest(t, e) - te.maxMsgSize = newInt(1024) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - argSize := int32(*te.maxMsgSize + 1) - const smallSize = 1 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - // Test on server side for unary RPC. - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(smallSize), - Payload: payload, - } - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - // Test on client side for unary RPC. - req.ResponseSize = proto.Int32(int32(*te.maxMsgSize) + 1) - req.Payload = smallPayload - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test on server side for streaming RPC. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(1), - }, - } - - spayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(*te.maxMsgSize+1)) - if err != nil { - t.Fatal(err) - } - - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: spayload, - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test on client side for streaming RPC. - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - respParam[0].Size = proto.Int32(int32(*te.maxMsgSize) + 1) - sreq.Payload = smallPayload - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - -} - -func TestPeerClientSide(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPeerClientSide(t, e) - } -} - -func testPeerClientSide(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - peer := new(peer.Peer) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(peer), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err) - } - pa := peer.Addr.String() - if e.network == "unix" { - if pa != te.srvAddr { - t.Fatalf("peer.Addr = %v, want %v", pa, te.srvAddr) - } - return - } - _, pp, err := net.SplitHostPort(pa) - if err != nil { - t.Fatalf("Failed to parse address from peer.") - } - _, sp, err := net.SplitHostPort(te.srvAddr) - if err != nil { - t.Fatalf("Failed to parse address of test server.") - } - if pp != sp { - t.Fatalf("peer.Addr = localhost:%v, want localhost:%v", pp, sp) - } -} - -// TestPeerNegative tests that if call fails setting peer -// doesn't cause a segmentation fault. -// issue#1141 https://github.com/grpc/grpc-go/issues/1141 -func TestPeerNegative(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPeerNegative(t, e) - } -} - -func testPeerNegative(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - peer := new(peer.Peer) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - tc.EmptyCall(ctx, &testpb.Empty{}, grpc.Peer(peer)) -} - -func TestPeerFailedRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPeerFailedRPC(t, e) - } -} - -func testPeerFailedRPC(t *testing.T, e env) { - te := newTest(t, e) - te.maxServerReceiveMsgSize = newInt(1 * 1024) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - // first make a successful request to the server - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, <nil>", err) - } - - // make a second request that will be rejected by the server - const largeSize = 5 * 1024 - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - Payload: largePayload, - } - - peer := new(peer.Peer) - if _, err := tc.UnaryCall(context.Background(), req, grpc.Peer(peer)); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } else { - pa := peer.Addr.String() - if e.network == "unix" { - if pa != te.srvAddr { - t.Fatalf("peer.Addr = %v, want %v", pa, te.srvAddr) - } - return - } - _, pp, err := net.SplitHostPort(pa) - if err != nil { - t.Fatalf("Failed to parse address from peer.") - } - _, sp, err := net.SplitHostPort(te.srvAddr) - if err != nil { - t.Fatalf("Failed to parse address of test server.") - } - if pp != sp { - t.Fatalf("peer.Addr = localhost:%v, want localhost:%v", pp, sp) - } - } -} - -func TestMetadataUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMetadataUnaryRPC(t, e) - } -} - -func testMetadataUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const argSize = 2718 - const respSize = 314 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - var header, trailer metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.Trailer(&trailer)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err) - } - // Ignore optional response headers that Servers may set: - if header != nil { - delete(header, "trailer") // RFC 2616 says server SHOULD (but optional) declare trailers - delete(header, "date") // the Date header is also optional - delete(header, "user-agent") - } - if !reflect.DeepEqual(header, testMetadata) { - t.Fatalf("Received header metadata %v, want %v", header, testMetadata) - } - if !reflect.DeepEqual(trailer, testTrailerMetadata) { - t.Fatalf("Received trailer metadata %v, want %v", trailer, testTrailerMetadata) - } -} - -func TestMultipleSetTrailerUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMultipleSetTrailerUnaryRPC(t, e) - } -} - -func testMultipleSetTrailerUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, multipleSetTrailer: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - var trailer metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Trailer(&trailer), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err) - } - expectedTrailer := metadata.Join(testTrailerMetadata, testTrailerMetadata2) - if !reflect.DeepEqual(trailer, expectedTrailer) { - t.Fatalf("Received trailer metadata %v, want %v", trailer, expectedTrailer) - } -} - -func TestMultipleSetTrailerStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMultipleSetTrailerStreamingRPC(t, e) - } -} - -func testMultipleSetTrailerStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, multipleSetTrailer: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err) - } - - trailer := stream.Trailer() - expectedTrailer := metadata.Join(testTrailerMetadata, testTrailerMetadata2) - if !reflect.DeepEqual(trailer, expectedTrailer) { - t.Fatalf("Received trailer metadata %v, want %v", trailer, expectedTrailer) - } -} - -func TestSetAndSendHeaderUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testSetAndSendHeaderUnaryRPC(t, e) - } -} - -// To test header metadata is sent on SendHeader(). -func testSetAndSendHeaderUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setAndSendHeader: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - var header metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err) - } - delete(header, "user-agent") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestMultipleSetHeaderUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderUnaryRPC(t, e) - } -} - -// To test header metadata is sent when sending response. -func testMultipleSetHeaderUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - - var header metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err) - } - delete(header, "user-agent") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestMultipleSetHeaderUnaryRPCError(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderUnaryRPCError(t, e) - } -} - -// To test header metadata is sent when sending status. -func testMultipleSetHeaderUnaryRPCError(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = -1 // Invalid respSize to make RPC fail. - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - var header metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.FailFast(false)); err == nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <non-nil>", ctx, err) - } - delete(header, "user-agent") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestSetAndSendHeaderStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testSetAndSendHeaderStreamingRPC(t, e) - } -} - -// To test header metadata is sent on SendHeader(). -func testSetAndSendHeaderStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setAndSendHeader: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err) - } - - header, err := stream.Header() - if err != nil { - t.Fatalf("%v.Header() = _, %v, want _, <nil>", stream, err) - } - delete(header, "user-agent") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestMultipleSetHeaderStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderStreamingRPC(t, e) - } -} - -// To test header metadata is sent when sending response. -func testMultipleSetHeaderStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: []*testpb.ResponseParameters{ - {Size: proto.Int32(respSize)}, - }, - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want <nil>", stream, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err) - } - - header, err := stream.Header() - if err != nil { - t.Fatalf("%v.Header() = _, %v, want _, <nil>", stream, err) - } - delete(header, "user-agent") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } - -} - -func TestMultipleSetHeaderStreamingRPCError(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderStreamingRPCError(t, e) - } -} - -// To test header metadata is sent when sending status. -func testMultipleSetHeaderStreamingRPCError(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = -1 - ) - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: []*testpb.ResponseParameters{ - {Size: proto.Int32(respSize)}, - }, - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - if _, err := stream.Recv(); err == nil { - t.Fatalf("%v.Recv() = %v, want <non-nil>", stream, err) - } - - header, err := stream.Header() - if err != nil { - t.Fatalf("%v.Header() = _, %v, want _, <nil>", stream, err) - } - delete(header, "user-agent") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } - - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } -} - -// TestMalformedHTTP2Metedata verfies the returned error when the client -// sends an illegal metadata. -func TestMalformedHTTP2Metadata(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - // Failed with "server stops accepting new RPCs". - // Server stops accepting new RPCs when the client sends an illegal http2 header. - continue - } - testMalformedHTTP2Metadata(t, e) - } -} - -func testMalformedHTTP2Metadata(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 2718) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(314), - Payload: payload, - } - ctx := metadata.NewOutgoingContext(context.Background(), malformedHTTP2Metadata) - if _, err := tc.UnaryCall(ctx, req); grpc.Code(err) != codes.Internal { - t.Fatalf("TestService.UnaryCall(%v, _) = _, %v; want _, %s", ctx, err, codes.Internal) - } -} - -func performOneRPC(t *testing.T, tc testpb.TestServiceClient, wg *sync.WaitGroup) { - defer wg.Done() - const argSize = 2718 - const respSize = 314 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Error(err) - return - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - reply, err := tc.UnaryCall(context.Background(), req, grpc.FailFast(false)) - if err != nil { - t.Errorf("TestService/UnaryCall(_, _) = _, %v, want _, <nil>", err) - return - } - pt := reply.GetPayload().GetType() - ps := len(reply.GetPayload().GetBody()) - if pt != testpb.PayloadType_COMPRESSABLE || ps != respSize { - t.Errorf("Got reply with type %d len %d; want %d, %d", pt, ps, testpb.PayloadType_COMPRESSABLE, respSize) - return - } -} - -func TestRetry(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - // Fails with RST_STREAM / FLOW_CONTROL_ERROR - continue - } - testRetry(t, e) - } -} - -// This test mimics a user who sends 1000 RPCs concurrently on a faulty transport. -// TODO(zhaoq): Refactor to make this clearer and add more cases to test racy -// and error-prone paths. -func testRetry(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise("transport: http2Client.notifyError got notified that the client transport was broken") - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - var wg sync.WaitGroup - - numRPC := 1000 - rpcSpacing := 2 * time.Millisecond - if raceMode { - // The race detector has a limit on how many goroutines it can track. - // This test is near the upper limit, and goes over the limit - // depending on the environment (the http.Handler environment uses - // more goroutines) - t.Logf("Shortening test in race mode.") - numRPC /= 2 - rpcSpacing *= 2 - } - - wg.Add(1) - go func() { - // Halfway through starting RPCs, kill all connections: - time.Sleep(time.Duration(numRPC/2) * rpcSpacing) - - // The server shuts down the network connection to make a - // transport error which will be detected by the client side - // code. - internal.TestingCloseConns(te.srv) - wg.Done() - }() - // All these RPCs should succeed eventually. - for i := 0; i < numRPC; i++ { - time.Sleep(rpcSpacing) - wg.Add(1) - go performOneRPC(t, tc, &wg) - } - wg.Wait() -} - -func TestRPCTimeout(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testRPCTimeout(t, e) - } -} - -// TODO(zhaoq): Have a better test coverage of timeout and cancellation mechanism. -func testRPCTimeout(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, unaryCallSleepTime: 50 * time.Millisecond}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - const argSize = 2718 - const respSize = 314 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - for i := -1; i <= 10; i++ { - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(i)*time.Millisecond) - if _, err := tc.UnaryCall(ctx, req); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/UnaryCallv(_, _) = _, %v; want <nil>, error code: %s", err, codes.DeadlineExceeded) - } - cancel() - } -} - -func TestCancel(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCancel(t, e) - } -} - -func testCancel(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise("grpc: the client connection is closing; please retry") - te.startServer(&testServer{security: e.security, unaryCallSleepTime: time.Second}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - const argSize = 2718 - const respSize = 314 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - ctx, cancel := context.WithCancel(context.Background()) - time.AfterFunc(1*time.Millisecond, cancel) - if r, err := tc.UnaryCall(ctx, req); grpc.Code(err) != codes.Canceled { - t.Fatalf("TestService/UnaryCall(_, _) = %v, %v; want _, error code: %s", r, err, codes.Canceled) - } - awaitNewConnLogOutput() -} - -func TestCancelNoIO(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCancelNoIO(t, e) - } -} - -func testCancelNoIO(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise("http2Client.notifyError got notified that the client transport was broken") - te.maxStream = 1 // Only allows 1 live stream per server transport. - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - // Start one blocked RPC for which we'll never send streaming - // input. This will consume the 1 maximum concurrent streams, - // causing future RPCs to hang. - ctx, cancelFirst := context.WithCancel(context.Background()) - _, err := tc.StreamingInputCall(ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err) - } - - // Loop until the ClientConn receives the initial settings - // frame from the server, notifying it about the maximum - // concurrent streams. We know when it's received it because - // an RPC will fail with codes.DeadlineExceeded instead of - // succeeding. - // TODO(bradfitz): add internal test hook for this (Issue 534) - for { - ctx, cancelSecond := context.WithTimeout(context.Background(), 50*time.Millisecond) - _, err := tc.StreamingInputCall(ctx) - cancelSecond() - if err == nil { - continue - } - if grpc.Code(err) == codes.DeadlineExceeded { - break - } - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded) - } - // If there are any RPCs in flight before the client receives - // the max streams setting, let them be expired. - // TODO(bradfitz): add internal test hook for this (Issue 534) - time.Sleep(50 * time.Millisecond) - - go func() { - time.Sleep(50 * time.Millisecond) - cancelFirst() - }() - - // This should be blocked until the 1st is canceled, then succeed. - ctx, cancelThird := context.WithTimeout(context.Background(), 500*time.Millisecond) - if _, err := tc.StreamingInputCall(ctx); err != nil { - t.Errorf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err) - } - cancelThird() -} - -// The following tests the gRPC streaming RPC implementations. -// TODO(zhaoq): Have better coverage on error cases. -var ( - reqSizes = []int{27182, 8, 1828, 45904} - respSizes = []int{31415, 9, 2653, 58979} -) - -func TestNoService(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testNoService(t, e) - } -} - -func testNoService(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(nil) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - stream, err := tc.FullDuplexCall(te.ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if _, err := stream.Recv(); grpc.Code(err) != codes.Unimplemented { - t.Fatalf("stream.Recv() = _, %v, want _, error code %s", err, codes.Unimplemented) - } -} - -func TestPingPong(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPingPong(t, e) - } -} - -func testPingPong(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - var index int - for index < len(reqSizes) { - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(respSizes[index])), - }, - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(reqSizes[index])) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - reply, err := stream.Recv() - if err != nil { - t.Fatalf("%v.Recv() = %v, want <nil>", stream, err) - } - pt := reply.GetPayload().GetType() - if pt != testpb.PayloadType_COMPRESSABLE { - t.Fatalf("Got the reply of type %d, want %d", pt, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != int(respSizes[index]) { - t.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the ping pong test: %v", stream, err) - } -} - -func TestMetadataStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMetadataStreamingRPC(t, e) - } -} - -func testMetadataStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx := metadata.NewOutgoingContext(te.ctx, testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - go func() { - headerMD, err := stream.Header() - if e.security == "tls" { - delete(headerMD, "transport_security_type") - } - delete(headerMD, "trailer") // ignore if present - delete(headerMD, "user-agent") - if err != nil || !reflect.DeepEqual(testMetadata, headerMD) { - t.Errorf("#1 %v.Header() = %v, %v, want %v, <nil>", stream, headerMD, err, testMetadata) - } - // test the cached value. - headerMD, err = stream.Header() - delete(headerMD, "trailer") // ignore if present - delete(headerMD, "user-agent") - if err != nil || !reflect.DeepEqual(testMetadata, headerMD) { - t.Errorf("#2 %v.Header() = %v, %v, want %v, <nil>", stream, headerMD, err, testMetadata) - } - err = func() error { - for index := 0; index < len(reqSizes); index++ { - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(respSizes[index])), - }, - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(reqSizes[index])) - if err != nil { - return err - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(req); err != nil { - return fmt.Errorf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - } - return nil - }() - // Tell the server we're done sending args. - stream.CloseSend() - if err != nil { - t.Error(err) - } - }() - for { - if _, err := stream.Recv(); err != nil { - break - } - } - trailerMD := stream.Trailer() - if !reflect.DeepEqual(testTrailerMetadata, trailerMD) { - t.Fatalf("%v.Trailer() = %v, want %v", stream, trailerMD, testTrailerMetadata) - } -} - -func TestServerStreaming(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServerStreaming(t, e) - } -} - -func testServerStreaming(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - respParam := make([]*testpb.ResponseParameters, len(respSizes)) - for i, s := range respSizes { - respParam[i] = &testpb.ResponseParameters{ - Size: proto.Int32(int32(s)), - } - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - } - stream, err := tc.StreamingOutputCall(context.Background(), req) - if err != nil { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want <nil>", tc, err) - } - var rpcStatus error - var respCnt int - var index int - for { - reply, err := stream.Recv() - if err != nil { - rpcStatus = err - break - } - pt := reply.GetPayload().GetType() - if pt != testpb.PayloadType_COMPRESSABLE { - t.Fatalf("Got the reply of type %d, want %d", pt, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != int(respSizes[index]) { - t.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - respCnt++ - } - if rpcStatus != io.EOF { - t.Fatalf("Failed to finish the server streaming rpc: %v, want <EOF>", rpcStatus) - } - if respCnt != len(respSizes) { - t.Fatalf("Got %d reply, want %d", len(respSizes), respCnt) - } -} - -func TestFailedServerStreaming(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testFailedServerStreaming(t, e) - } -} - -func testFailedServerStreaming(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = failAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - respParam := make([]*testpb.ResponseParameters, len(respSizes)) - for i, s := range respSizes { - respParam[i] = &testpb.ResponseParameters{ - Size: proto.Int32(int32(s)), - } - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - } - ctx := metadata.NewOutgoingContext(te.ctx, testMetadata) - stream, err := tc.StreamingOutputCall(ctx, req) - if err != nil { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want <nil>", tc, err) - } - wantErr := grpc.Errorf(codes.DataLoss, "error for testing: "+failAppUA) - if _, err := stream.Recv(); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("%v.Recv() = _, %v, want _, %v", stream, err, wantErr) - } -} - -// concurrentSendServer is a TestServiceServer whose -// StreamingOutputCall makes ten serial Send calls, sending payloads -// "0".."9", inclusive. TestServerStreamingConcurrent verifies they -// were received in the correct order, and that there were no races. -// -// All other TestServiceServer methods crash if called. -type concurrentSendServer struct { - testpb.TestServiceServer -} - -func (s concurrentSendServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { - for i := 0; i < 10; i++ { - stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: &testpb.Payload{ - Body: []byte{'0' + uint8(i)}, - }, - }) - } - return nil -} - -// Tests doing a bunch of concurrent streaming output calls. -func TestServerStreamingConcurrent(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServerStreamingConcurrent(t, e) - } -} - -func testServerStreamingConcurrent(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(concurrentSendServer{}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - doStreamingCall := func() { - req := &testpb.StreamingOutputCallRequest{} - stream, err := tc.StreamingOutputCall(context.Background(), req) - if err != nil { - t.Errorf("%v.StreamingOutputCall(_) = _, %v, want <nil>", tc, err) - return - } - var ngot int - var buf bytes.Buffer - for { - reply, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - ngot++ - if buf.Len() > 0 { - buf.WriteByte(',') - } - buf.Write(reply.GetPayload().GetBody()) - } - if want := 10; ngot != want { - t.Errorf("Got %d replies, want %d", ngot, want) - } - if got, want := buf.String(), "0,1,2,3,4,5,6,7,8,9"; got != want { - t.Errorf("Got replies %q; want %q", got, want) - } - } - - var wg sync.WaitGroup - for i := 0; i < 20; i++ { - wg.Add(1) - go func() { - defer wg.Done() - doStreamingCall() - }() - } - wg.Wait() - -} - -func generatePayloadSizes() [][]int { - reqSizes := [][]int{ - {27182, 8, 1828, 45904}, - } - - num8KPayloads := 1024 - eightKPayloads := []int{} - for i := 0; i < num8KPayloads; i++ { - eightKPayloads = append(eightKPayloads, (1 << 13)) - } - reqSizes = append(reqSizes, eightKPayloads) - - num2MPayloads := 8 - twoMPayloads := []int{} - for i := 0; i < num2MPayloads; i++ { - twoMPayloads = append(twoMPayloads, (1 << 21)) - } - reqSizes = append(reqSizes, twoMPayloads) - - return reqSizes -} - -func TestClientStreaming(t *testing.T) { - defer leakcheck.Check(t) - for _, s := range generatePayloadSizes() { - for _, e := range listTestEnv() { - testClientStreaming(t, e, s) - } - } -} - -func testClientStreaming(t *testing.T, e env, sizes []int) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx, cancel := context.WithTimeout(te.ctx, time.Second*30) - defer cancel() - stream, err := tc.StreamingInputCall(ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want <nil>", tc, err) - } - - var sum int - for _, s := range sizes { - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(s)) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingInputCallRequest{ - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - sum += s - } - reply, err := stream.CloseAndRecv() - if err != nil { - t.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) - } - if reply.GetAggregatedPayloadSize() != int32(sum) { - t.Fatalf("%v.CloseAndRecv().GetAggregatePayloadSize() = %v; want %v", stream, reply.GetAggregatedPayloadSize(), sum) - } -} - -func TestClientStreamingError(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testClientStreamingError(t, e) - } -} - -func testClientStreamingError(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, earlyFail: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - stream, err := tc.StreamingInputCall(te.ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want <nil>", tc, err) - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 1) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingInputCallRequest{ - Payload: payload, - } - // The 1st request should go through. - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - for { - if err := stream.Send(req); err != io.EOF { - continue - } - if _, err := stream.CloseAndRecv(); grpc.Code(err) != codes.NotFound { - t.Fatalf("%v.CloseAndRecv() = %v, want error %s", stream, err, codes.NotFound) - } - break - } -} - -func TestExceedMaxStreamsLimit(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testExceedMaxStreamsLimit(t, e) - } -} - -func testExceedMaxStreamsLimit(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise( - "http2Client.notifyError got notified that the client transport was broken", - "Conn.resetTransport failed to create client transport", - "grpc: the connection is closing", - ) - te.maxStream = 1 // Only allows 1 live stream per server transport. - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - _, err := tc.StreamingInputCall(te.ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err) - } - // Loop until receiving the new max stream setting from the server. - for { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - _, err := tc.StreamingInputCall(ctx) - if err == nil { - time.Sleep(50 * time.Millisecond) - continue - } - if grpc.Code(err) == codes.DeadlineExceeded { - break - } - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded) - } -} - -const defaultMaxStreamsClient = 100 - -func TestExceedDefaultMaxStreamsLimit(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - // The default max stream limit in handler_server is not 100? - continue - } - testExceedDefaultMaxStreamsLimit(t, e) - } -} - -func testExceedDefaultMaxStreamsLimit(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise( - "http2Client.notifyError got notified that the client transport was broken", - "Conn.resetTransport failed to create client transport", - "grpc: the connection is closing", - ) - // When masStream is set to 0 the server doesn't send a settings frame for - // MaxConcurrentStreams, essentially allowing infinite (math.MaxInt32) streams. - // In such a case, there should be a default cap on the client-side. - te.maxStream = 0 - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - // Create as many streams as a client can. - for i := 0; i < defaultMaxStreamsClient; i++ { - if _, err := tc.StreamingInputCall(te.ctx); err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err) - } - } - - // Trying to create one more should timeout. - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - _, err := tc.StreamingInputCall(ctx) - if err == nil || grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded) - } -} - -func TestStreamsQuotaRecovery(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testStreamsQuotaRecovery(t, e) - } -} - -func testStreamsQuotaRecovery(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise( - "http2Client.notifyError got notified that the client transport was broken", - "Conn.resetTransport failed to create client transport", - "grpc: the connection is closing", - ) - te.maxStream = 1 // Allows 1 live stream. - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.StreamingInputCall(context.Background()); err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, <nil>", tc, err) - } - // Loop until the new max stream setting is effective. - for { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - _, err := tc.StreamingInputCall(ctx) - if err == nil { - time.Sleep(50 * time.Millisecond) - continue - } - if grpc.Code(err) == codes.DeadlineExceeded { - break - } - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded) - } - - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 314) - if err != nil { - t.Error(err) - return - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(1592), - Payload: payload, - } - // No rpc should go through due to the max streams limit. - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - defer cancel() - if _, err := tc.UnaryCall(ctx, req, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Errorf("TestService/UnaryCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - }() - } - wg.Wait() -} - -func TestCompressServerHasNoSupport(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCompressServerHasNoSupport(t, e) - } -} - -func testCompressServerHasNoSupport(t *testing.T, e env) { - te := newTest(t, e) - te.serverCompression = false - te.clientCompression = true - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const argSize = 271828 - const respSize = 314159 - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - if _, err := tc.UnaryCall(context.Background(), req); err == nil || grpc.Code(err) != codes.Unimplemented { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code %s", err, codes.Unimplemented) - } - // Streaming RPC - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(31415), - }, - } - payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415)) - if err != nil { - t.Fatal(err) - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || grpc.Code(err) != codes.Unimplemented { - t.Fatalf("%v.Recv() = %v, want error code %s", stream, err, codes.Unimplemented) - } -} - -func TestCompressOK(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCompressOK(t, e) - } -} - -func testCompressOK(t *testing.T, e env) { - te := newTest(t, e) - te.serverCompression = true - te.clientCompression = true - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - // Unary call - const argSize = 271828 - const respSize = 314159 - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseSize: proto.Int32(respSize), - Payload: payload, - } - ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("something", "something")) - if _, err := tc.UnaryCall(ctx, req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, <nil>", err) - } - // Streaming RPC - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(31415), - }, - } - payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415)) - if err != nil { - t.Fatal(err) - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want <nil>", stream, err) - } -} - -func TestUnaryClientInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testUnaryClientInterceptor(t, e) - } -} - -func failOkayRPC(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - err := invoker(ctx, method, req, reply, cc, opts...) - if err == nil { - return grpc.Errorf(codes.NotFound, "") - } - return err -} - -func testUnaryClientInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.unaryClientInt = failOkayRPC - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.NotFound { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, error code %s", tc, err, codes.NotFound) - } -} - -func TestStreamClientInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testStreamClientInterceptor(t, e) - } -} - -func failOkayStream(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - s, err := streamer(ctx, desc, cc, method, opts...) - if err == nil { - return nil, grpc.Errorf(codes.NotFound, "") - } - return s, nil -} - -func testStreamClientInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.streamClientInt = failOkayStream - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(1)), - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(1)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - if _, err := tc.StreamingOutputCall(context.Background(), req); grpc.Code(err) != codes.NotFound { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want _, error code %s", tc, err, codes.NotFound) - } -} - -func TestUnaryServerInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testUnaryServerInterceptor(t, e) - } -} - -func errInjector(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - return nil, grpc.Errorf(codes.PermissionDenied, "") -} - -func testUnaryServerInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.unaryServerInt = errInjector - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.PermissionDenied { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, error code %s", tc, err, codes.PermissionDenied) - } -} - -func TestStreamServerInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - // TODO(bradfitz): Temporarily skip this env due to #619. - if e.name == "handler-tls" { - continue - } - testStreamServerInterceptor(t, e) - } -} - -func fullDuplexOnly(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - if info.FullMethod == "/grpc.testing.TestService/FullDuplexCall" { - return handler(srv, ss) - } - // Reject the other methods. - return grpc.Errorf(codes.PermissionDenied, "") -} - -func testStreamServerInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.streamServerInt = fullDuplexOnly - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(1)), - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(1)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: payload, - } - s1, err := tc.StreamingOutputCall(context.Background(), req) - if err != nil { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want _, <nil>", tc, err) - } - if _, err := s1.Recv(); grpc.Code(err) != codes.PermissionDenied { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, error code %s", tc, err, codes.PermissionDenied) - } - s2, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err := s2.Send(req); err != nil { - t.Fatalf("%v.Send(_) = %v, want <nil>", s2, err) - } - if _, err := s2.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, <nil>", s2, err) - } -} - -// funcServer implements methods of TestServiceServer using funcs, -// similar to an http.HandlerFunc. -// Any unimplemented method will crash. Tests implement the method(s) -// they need. -type funcServer struct { - testpb.TestServiceServer - unaryCall func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) - streamingInputCall func(stream testpb.TestService_StreamingInputCallServer) error -} - -func (s *funcServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - return s.unaryCall(ctx, in) -} - -func (s *funcServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { - return s.streamingInputCall(stream) -} - -func TestClientRequestBodyErrorUnexpectedEOF(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorUnexpectedEOF(t, e) - } -} - -func testClientRequestBodyErrorUnexpectedEOF(t *testing.T, e env) { - te := newTest(t, e) - ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - errUnexpectedCall := errors.New("unexpected call func server method") - t.Error(errUnexpectedCall) - return nil, errUnexpectedCall - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall") - // Say we have 5 bytes coming, but set END_STREAM flag: - st.writeData(1, true, []byte{0, 0, 0, 0, 5}) - st.wantAnyFrame() // wait for server to crash (it used to crash) - }) -} - -func TestClientRequestBodyErrorCloseAfterLength(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorCloseAfterLength(t, e) - } -} - -func testClientRequestBodyErrorCloseAfterLength(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise("Server.processUnaryRPC failed to write status") - ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - errUnexpectedCall := errors.New("unexpected call func server method") - t.Error(errUnexpectedCall) - return nil, errUnexpectedCall - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall") - // say we're sending 5 bytes, but then close the connection instead. - st.writeData(1, false, []byte{0, 0, 0, 0, 5}) - st.cc.Close() - }) -} - -func TestClientRequestBodyErrorCancel(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorCancel(t, e) - } -} - -func testClientRequestBodyErrorCancel(t *testing.T, e env) { - te := newTest(t, e) - gotCall := make(chan bool, 1) - ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - gotCall <- true - return new(testpb.SimpleResponse), nil - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall") - // Say we have 5 bytes coming, but cancel it instead. - st.writeRSTStream(1, http2.ErrCodeCancel) - st.writeData(1, false, []byte{0, 0, 0, 0, 5}) - - // Verify we didn't a call yet. - select { - case <-gotCall: - t.Fatal("unexpected call") - default: - } - - // And now send an uncanceled (but still invalid), just to get a response. - st.writeHeadersGRPC(3, "/grpc.testing.TestService/UnaryCall") - st.writeData(3, true, []byte{0, 0, 0, 0, 0}) - <-gotCall - st.wantAnyFrame() - }) -} - -func TestClientRequestBodyErrorCancelStreamingInput(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorCancelStreamingInput(t, e) - } -} - -func testClientRequestBodyErrorCancelStreamingInput(t *testing.T, e env) { - te := newTest(t, e) - recvErr := make(chan error, 1) - ts := &funcServer{streamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { - _, err := stream.Recv() - recvErr <- err - return nil - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/StreamingInputCall") - // Say we have 5 bytes coming, but cancel it instead. - st.writeData(1, false, []byte{0, 0, 0, 0, 5}) - st.writeRSTStream(1, http2.ErrCodeCancel) - - var got error - select { - case got = <-recvErr: - case <-time.After(3 * time.Second): - t.Fatal("timeout waiting for error") - } - if grpc.Code(got) != codes.Canceled { - t.Errorf("error = %#v; want error code %s", got, codes.Canceled) - } - }) -} - -const clientAlwaysFailCredErrorMsg = "clientAlwaysFailCred always fails" - -var errClientAlwaysFailCred = errors.New(clientAlwaysFailCredErrorMsg) - -type clientAlwaysFailCred struct{} - -func (c clientAlwaysFailCred) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return nil, nil, errClientAlwaysFailCred -} -func (c clientAlwaysFailCred) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c clientAlwaysFailCred) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c clientAlwaysFailCred) Clone() credentials.TransportCredentials { - return nil -} -func (c clientAlwaysFailCred) OverrideServerName(s string) error { - return nil -} - -func TestDialWithBlockErrorOnBadCertificates(t *testing.T) { - te := newTest(t, env{name: "bad-cred", network: "tcp", security: "clientAlwaysFailCred", balancer: "v1"}) - te.startServer(&testServer{security: te.e.security}) - defer te.tearDown() - - var ( - err error - opts []grpc.DialOption - ) - opts = append(opts, grpc.WithTransportCredentials(clientAlwaysFailCred{}), grpc.WithBlock()) - te.cc, err = grpc.Dial(te.srvAddr, opts...) - if err != errClientAlwaysFailCred { - te.t.Fatalf("Dial(%q) = %v, want %v", te.srvAddr, err, errClientAlwaysFailCred) - } -} - -type clientTimeoutCreds struct { - timeoutReturned bool -} - -func (c *clientTimeoutCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - if !c.timeoutReturned { - c.timeoutReturned = true - return nil, nil, context.DeadlineExceeded - } - return rawConn, nil, nil -} -func (c *clientTimeoutCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c *clientTimeoutCreds) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c *clientTimeoutCreds) Clone() credentials.TransportCredentials { - return nil -} -func (c *clientTimeoutCreds) OverrideServerName(s string) error { - return nil -} - -func TestNonFailFastRPCSucceedOnTimeoutCreds(t *testing.T) { - te := newTest(t, env{name: "timeout-cred", network: "tcp", security: "clientTimeoutCreds", balancer: "v1"}) - te.userAgent = testAppUA - te.startServer(&testServer{security: te.e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // This unary call should succeed, because ClientHandshake will succeed for the second time. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - te.t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want <nil>", err) - } -} - -type serverDispatchCred struct { - rawConnCh chan net.Conn -} - -func newServerDispatchCred() *serverDispatchCred { - return &serverDispatchCred{ - rawConnCh: make(chan net.Conn, 1), - } -} -func (c *serverDispatchCred) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c *serverDispatchCred) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - select { - case c.rawConnCh <- rawConn: - default: - } - return nil, nil, credentials.ErrConnDispatched -} -func (c *serverDispatchCred) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c *serverDispatchCred) Clone() credentials.TransportCredentials { - return nil -} -func (c *serverDispatchCred) OverrideServerName(s string) error { - return nil -} -func (c *serverDispatchCred) getRawConn() net.Conn { - return <-c.rawConnCh -} - -func TestServerCredsDispatch(t *testing.T) { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - cred := newServerDispatchCred() - s := grpc.NewServer(grpc.Creds(cred)) - go s.Serve(lis) - defer s.Stop() - - cc, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(cred)) - if err != nil { - t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - defer cc.Close() - - rawConn := cred.getRawConn() - // Give grpc a chance to see the error and potentially close the connection. - // And check that connection is not closed after that. - time.Sleep(100 * time.Millisecond) - // Check rawConn is not closed. - if n, err := rawConn.Write([]byte{0}); n <= 0 || err != nil { - t.Errorf("Read() = %v, %v; want n>0, <nil>", n, err) - } -} - -func TestFlowControlLogicalRace(t *testing.T) { - // Test for a regression of https://github.com/grpc/grpc-go/issues/632, - // and other flow control bugs. - - defer leakcheck.Check(t) - - const ( - itemCount = 100 - itemSize = 1 << 10 - recvCount = 2 - maxFailures = 3 - - requestTimeout = time.Second * 5 - ) - - requestCount := 10000 - if raceMode { - requestCount = 1000 - } - - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - defer lis.Close() - - s := grpc.NewServer() - testpb.RegisterTestServiceServer(s, &flowControlLogicalRaceServer{ - itemCount: itemCount, - itemSize: itemSize, - }) - defer s.Stop() - - go s.Serve(lis) - - ctx := context.Background() - - cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock()) - if err != nil { - t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - defer cc.Close() - cl := testpb.NewTestServiceClient(cc) - - failures := 0 - for i := 0; i < requestCount; i++ { - ctx, cancel := context.WithTimeout(ctx, requestTimeout) - output, err := cl.StreamingOutputCall(ctx, &testpb.StreamingOutputCallRequest{}) - if err != nil { - t.Fatalf("StreamingOutputCall; err = %q", err) - } - - j := 0 - loop: - for ; j < recvCount; j++ { - _, err := output.Recv() - if err != nil { - if err == io.EOF { - break loop - } - switch grpc.Code(err) { - case codes.DeadlineExceeded: - break loop - default: - t.Fatalf("Recv; err = %q", err) - } - } - } - cancel() - <-ctx.Done() - - if j < recvCount { - t.Errorf("got %d responses to request %d", j, i) - failures++ - if failures >= maxFailures { - // Continue past the first failure to see if the connection is - // entirely broken, or if only a single RPC was affected - break - } - } - } -} - -type flowControlLogicalRaceServer struct { - testpb.TestServiceServer - - itemSize int - itemCount int -} - -func (s *flowControlLogicalRaceServer) StreamingOutputCall(req *testpb.StreamingOutputCallRequest, srv testpb.TestService_StreamingOutputCallServer) error { - for i := 0; i < s.itemCount; i++ { - err := srv.Send(&testpb.StreamingOutputCallResponse{ - Payload: &testpb.Payload{ - // Sending a large stream of data which the client reject - // helps to trigger some types of flow control bugs. - // - // Reallocating memory here is inefficient, but the stress it - // puts on the GC leads to more frequent flow control - // failures. The GC likely causes more variety in the - // goroutine scheduling orders. - Body: bytes.Repeat([]byte("a"), s.itemSize), - }, - }) - if err != nil { - return err - } - } - return nil -} - -type lockingWriter struct { - mu sync.Mutex - w io.Writer -} - -func (lw *lockingWriter) Write(p []byte) (n int, err error) { - lw.mu.Lock() - defer lw.mu.Unlock() - return lw.w.Write(p) -} - -func (lw *lockingWriter) setWriter(w io.Writer) { - lw.mu.Lock() - defer lw.mu.Unlock() - lw.w = w -} - -var testLogOutput = &lockingWriter{w: os.Stderr} - -// awaitNewConnLogOutput waits for any of grpc.NewConn's goroutines to -// terminate, if they're still running. It spams logs with this -// message. We wait for it so our log filter is still -// active. Otherwise the "defer restore()" at the top of various test -// functions restores our log filter and then the goroutine spams. -func awaitNewConnLogOutput() { - awaitLogOutput(50*time.Millisecond, "grpc: the client connection is closing; please retry") -} - -func awaitLogOutput(maxWait time.Duration, phrase string) { - pb := []byte(phrase) - - timer := time.NewTimer(maxWait) - defer timer.Stop() - wakeup := make(chan bool, 1) - for { - if logOutputHasContents(pb, wakeup) { - return - } - select { - case <-timer.C: - // Too slow. Oh well. - return - case <-wakeup: - } - } -} - -func logOutputHasContents(v []byte, wakeup chan<- bool) bool { - testLogOutput.mu.Lock() - defer testLogOutput.mu.Unlock() - fw, ok := testLogOutput.w.(*filterWriter) - if !ok { - return false - } - fw.mu.Lock() - defer fw.mu.Unlock() - if bytes.Contains(fw.buf.Bytes(), v) { - return true - } - fw.wakeup = wakeup - return false -} - -var verboseLogs = flag.Bool("verbose_logs", false, "show all grpclog output, without filtering") - -func noop() {} - -// declareLogNoise declares that t is expected to emit the following noisy phrases, -// even on success. Those phrases will be filtered from grpclog output -// and only be shown if *verbose_logs or t ends up failing. -// The returned restore function should be called with defer to be run -// before the test ends. -func declareLogNoise(t *testing.T, phrases ...string) (restore func()) { - if *verboseLogs { - return noop - } - fw := &filterWriter{dst: os.Stderr, filter: phrases} - testLogOutput.setWriter(fw) - return func() { - if t.Failed() { - fw.mu.Lock() - defer fw.mu.Unlock() - if fw.buf.Len() > 0 { - t.Logf("Complete log output:\n%s", fw.buf.Bytes()) - } - } - testLogOutput.setWriter(os.Stderr) - } -} - -type filterWriter struct { - dst io.Writer - filter []string - - mu sync.Mutex - buf bytes.Buffer - wakeup chan<- bool // if non-nil, gets true on write -} - -func (fw *filterWriter) Write(p []byte) (n int, err error) { - fw.mu.Lock() - fw.buf.Write(p) - if fw.wakeup != nil { - select { - case fw.wakeup <- true: - default: - } - } - fw.mu.Unlock() - - ps := string(p) - for _, f := range fw.filter { - if strings.Contains(ps, f) { - return len(p), nil - } - } - return fw.dst.Write(p) -} - -// stubServer is a server that is easy to customize within individual test -// cases. -type stubServer struct { - // Guarantees we satisfy this interface; panics if unimplemented methods are called. - testpb.TestServiceServer - - // Customizable implementations of server handlers. - emptyCall func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) - fullDuplexCall func(stream testpb.TestService_FullDuplexCallServer) error - - // A client connected to this service the test may use. Created in Start(). - client testpb.TestServiceClient - - cleanups []func() // Lambdas executed in Stop(); populated by Start(). -} - -func (ss *stubServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - return ss.emptyCall(ctx, in) -} - -func (ss *stubServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - return ss.fullDuplexCall(stream) -} - -// Start starts the server and creates a client connected to it. -func (ss *stubServer) Start(sopts []grpc.ServerOption) error { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - return fmt.Errorf(`net.Listen("tcp", "localhost:0") = %v`, err) - } - ss.cleanups = append(ss.cleanups, func() { lis.Close() }) - - s := grpc.NewServer(sopts...) - testpb.RegisterTestServiceServer(s, ss) - go s.Serve(lis) - ss.cleanups = append(ss.cleanups, s.Stop) - - cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock()) - if err != nil { - return fmt.Errorf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - ss.cleanups = append(ss.cleanups, func() { cc.Close() }) - - ss.client = testpb.NewTestServiceClient(cc) - return nil -} - -func (ss *stubServer) Stop() { - for i := len(ss.cleanups) - 1; i >= 0; i-- { - ss.cleanups[i]() - } -} - -func TestUnaryProxyDoesNotForwardMetadata(t *testing.T) { - const mdkey = "somedata" - - // endpoint ensures mdkey is NOT in metadata and returns an error if it is. - endpoint := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] != nil { - return nil, status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey) - } - return &testpb.Empty{}, nil - }, - } - if err := endpoint.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer endpoint.Stop() - - // proxy ensures mdkey IS in metadata, then forwards the RPC to endpoint - // without explicitly copying the metadata. - proxy := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] == nil { - return nil, status.Errorf(codes.Internal, "proxy: md=%v; want contains(%q)", md, mdkey) - } - return endpoint.client.EmptyCall(ctx, in) - }, - } - if err := proxy.Start(nil); err != nil { - t.Fatalf("Error starting proxy server: %v", err) - } - defer proxy.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - md := metadata.Pairs(mdkey, "val") - ctx = metadata.NewOutgoingContext(ctx, md) - - // Sanity check that endpoint properly errors when it sees mdkey. - _, err := endpoint.client.EmptyCall(ctx, &testpb.Empty{}) - if s, ok := status.FromError(err); !ok || s.Code() != codes.Internal { - t.Fatalf("endpoint.client.EmptyCall(_, _) = _, %v; want _, <status with Code()=Internal>", err) - } - - if _, err := proxy.client.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatal(err.Error()) - } -} - -func TestStreamingProxyDoesNotForwardMetadata(t *testing.T) { - const mdkey = "somedata" - - // doFDC performs a FullDuplexCall with client and returns the error from the - // first stream.Recv call, or nil if that error is io.EOF. Calls t.Fatal if - // the stream cannot be established. - doFDC := func(ctx context.Context, client testpb.TestServiceClient) error { - stream, err := client.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("Unwanted error: %v", err) - } - if _, err := stream.Recv(); err != io.EOF { - return err - } - return nil - } - - // endpoint ensures mdkey is NOT in metadata and returns an error if it is. - endpoint := &stubServer{ - fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { - ctx := stream.Context() - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] != nil { - return status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey) - } - return nil - }, - } - if err := endpoint.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer endpoint.Stop() - - // proxy ensures mdkey IS in metadata, then forwards the RPC to endpoint - // without explicitly copying the metadata. - proxy := &stubServer{ - fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { - ctx := stream.Context() - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] == nil { - return status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey) - } - return doFDC(ctx, endpoint.client) - }, - } - if err := proxy.Start(nil); err != nil { - t.Fatalf("Error starting proxy server: %v", err) - } - defer proxy.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - md := metadata.Pairs(mdkey, "val") - ctx = metadata.NewOutgoingContext(ctx, md) - - // Sanity check that endpoint properly errors when it sees mdkey in ctx. - err := doFDC(ctx, endpoint.client) - if s, ok := status.FromError(err); !ok || s.Code() != codes.Internal { - t.Fatalf("stream.Recv() = _, %v; want _, <status with Code()=Internal>", err) - } - - if err := doFDC(ctx, proxy.client); err != nil { - t.Fatalf("doFDC(_, proxy.client) = %v; want nil", err) - } -} - -func TestStatsTagsAndTrace(t *testing.T) { - // Data added to context by client (typically in a stats handler). - tags := []byte{1, 5, 2, 4, 3} - trace := []byte{5, 2, 1, 3, 4} - - // endpoint ensures Tags() and Trace() in context match those that were added - // by the client and returns an error if not. - endpoint := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - md, _ := metadata.FromIncomingContext(ctx) - if tg := stats.Tags(ctx); !reflect.DeepEqual(tg, tags) { - return nil, status.Errorf(codes.Internal, "stats.Tags(%v)=%v; want %v", ctx, tg, tags) - } - if !reflect.DeepEqual(md["grpc-tags-bin"], []string{string(tags)}) { - return nil, status.Errorf(codes.Internal, "md['grpc-tags-bin']=%v; want %v", md["grpc-tags-bin"], tags) - } - if tr := stats.Trace(ctx); !reflect.DeepEqual(tr, trace) { - return nil, status.Errorf(codes.Internal, "stats.Trace(%v)=%v; want %v", ctx, tr, trace) - } - if !reflect.DeepEqual(md["grpc-trace-bin"], []string{string(trace)}) { - return nil, status.Errorf(codes.Internal, "md['grpc-trace-bin']=%v; want %v", md["grpc-trace-bin"], trace) - } - return &testpb.Empty{}, nil - }, - } - if err := endpoint.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer endpoint.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - testCases := []struct { - ctx context.Context - want codes.Code - }{ - {ctx: ctx, want: codes.Internal}, - {ctx: stats.SetTags(ctx, tags), want: codes.Internal}, - {ctx: stats.SetTrace(ctx, trace), want: codes.Internal}, - {ctx: stats.SetTags(stats.SetTrace(ctx, tags), tags), want: codes.Internal}, - {ctx: stats.SetTags(stats.SetTrace(ctx, trace), tags), want: codes.OK}, - } - - for _, tc := range testCases { - _, err := endpoint.client.EmptyCall(tc.ctx, &testpb.Empty{}) - if tc.want == codes.OK && err != nil { - t.Fatalf("endpoint.client.EmptyCall(%v, _) = _, %v; want _, nil", tc.ctx, err) - } - if s, ok := status.FromError(err); !ok || s.Code() != tc.want { - t.Fatalf("endpoint.client.EmptyCall(%v, _) = _, %v; want _, <status with Code()=%v>", tc.ctx, err, tc.want) - } - } -} - -func TestTapTimeout(t *testing.T) { - sopts := []grpc.ServerOption{ - grpc.InTapHandle(func(ctx context.Context, _ *tap.Info) (context.Context, error) { - c, cancel := context.WithCancel(ctx) - // Call cancel instead of setting a deadline so we can detect which error - // occurred -- this cancellation (desired) or the client's deadline - // expired (indicating this cancellation did not affect the RPC). - time.AfterFunc(10*time.Millisecond, cancel) - return c, nil - }), - } - - ss := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - <-ctx.Done() - return &testpb.Empty{}, nil - }, - } - if err := ss.Start(sopts); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer ss.Stop() - - // This was known to be flaky; test several times. - for i := 0; i < 10; i++ { - // Set our own deadline in case the server hangs. - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - res, err := ss.client.EmptyCall(ctx, &testpb.Empty{}) - cancel() - if s, ok := status.FromError(err); !ok || s.Code() != codes.Canceled { - t.Fatalf("ss.client.EmptyCall(context.Background(), _) = %v, %v; want nil, <status with Code()=Canceled>", res, err) - } - } -} - -type windowSizeConfig struct { - serverStream int32 - serverConn int32 - clientStream int32 - clientConn int32 -} - -func max(a, b int32) int32 { - if a > b { - return a - } - return b -} - -func TestConfigurableWindowSizeWithLargeWindow(t *testing.T) { - defer leakcheck.Check(t) - wc := windowSizeConfig{ - serverStream: 8 * 1024 * 1024, - serverConn: 12 * 1024 * 1024, - clientStream: 6 * 1024 * 1024, - clientConn: 8 * 1024 * 1024, - } - for _, e := range listTestEnv() { - testConfigurableWindowSize(t, e, wc) - } -} - -func TestConfigurableWindowSizeWithSmallWindow(t *testing.T) { - defer leakcheck.Check(t) - wc := windowSizeConfig{ - serverStream: 1, - serverConn: 1, - clientStream: 1, - clientConn: 1, - } - for _, e := range listTestEnv() { - testConfigurableWindowSize(t, e, wc) - } -} - -func testConfigurableWindowSize(t *testing.T, e env, wc windowSizeConfig) { - te := newTest(t, e) - te.serverInitialWindowSize = wc.serverStream - te.serverInitialConnWindowSize = wc.serverConn - te.clientInitialWindowSize = wc.clientStream - te.clientInitialConnWindowSize = wc.clientConn - - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - numOfIter := 11 - // Set message size to exhaust largest of window sizes. - messageSize := max(max(wc.serverStream, wc.serverConn), max(wc.clientStream, wc.clientConn)) / int32(numOfIter-1) - messageSize = max(messageSize, 64*1024) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, messageSize) - if err != nil { - t.Fatal(err) - } - respParams := []*testpb.ResponseParameters{ - { - Size: proto.Int32(messageSize), - }, - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParams, - Payload: payload, - } - for i := 0; i < numOfIter; i++ { - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, req, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, <nil>", stream, err) - } - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() = %v, want <nil>", stream, err) - } -} - -var ( - // test authdata - authdata = map[string]string{ - "test-key": "test-value", - "test-key2-bin": string([]byte{1, 2, 3}), - } -) - -type testPerRPCCredentials struct{} - -func (cr testPerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return authdata, nil -} - -func (cr testPerRPCCredentials) RequireTransportSecurity() bool { - return false -} - -func authHandle(ctx context.Context, info *tap.Info) (context.Context, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return ctx, fmt.Errorf("didn't find metadata in context") - } - for k, vwant := range authdata { - vgot, ok := md[k] - if !ok { - return ctx, fmt.Errorf("didn't find authdata key %v in context", k) - } - if vgot[0] != vwant { - return ctx, fmt.Errorf("for key %v, got value %v, want %v", k, vgot, vwant) - } - } - return ctx, nil -} - -func TestPerRPCCredentialsViaDialOptions(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPerRPCCredentialsViaDialOptions(t, e) - } -} - -func testPerRPCCredentialsViaDialOptions(t *testing.T, e env) { - te := newTest(t, e) - te.tapHandle = authHandle - te.perRPCCreds = testPerRPCCredentials{} - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("Test failed. Reason: %v", err) - } -} - -func TestPerRPCCredentialsViaCallOptions(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPerRPCCredentialsViaCallOptions(t, e) - } -} - -func testPerRPCCredentialsViaCallOptions(t *testing.T, e env) { - te := newTest(t, e) - te.tapHandle = authHandle - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.PerRPCCredentials(testPerRPCCredentials{})); err != nil { - t.Fatalf("Test failed. Reason: %v", err) - } -} - -func TestPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPerRPCCredentialsViaDialOptionsAndCallOptions(t, e) - } -} - -func testPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T, e env) { - te := newTest(t, e) - te.perRPCCreds = testPerRPCCredentials{} - // When credentials are provided via both dial options and call options, - // we apply both sets. - te.tapHandle = func(ctx context.Context, _ *tap.Info) (context.Context, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return ctx, fmt.Errorf("couldn't find metadata in context") - } - for k, vwant := range authdata { - vgot, ok := md[k] - if !ok { - return ctx, fmt.Errorf("couldn't find metadata for key %v", k) - } - if len(vgot) != 2 { - return ctx, fmt.Errorf("len of value for key %v was %v, want 2", k, len(vgot)) - } - if vgot[0] != vwant || vgot[1] != vwant { - return ctx, fmt.Errorf("value for %v was %v, want [%v, %v]", k, vgot, vwant, vwant) - } - } - return ctx, nil - } - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.PerRPCCredentials(testPerRPCCredentials{})); err != nil { - t.Fatalf("Test failed. Reason: %v", err) - } -} - -func TestWaitForReadyConnection(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testWaitForReadyConnection(t, e) - } - -} - -func testWaitForReadyConnection(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() // Non-blocking dial. - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - state := cc.GetState() - // Wait for connection to be Ready. - for ; state != connectivity.Ready && cc.WaitForStateChange(ctx, state); state = cc.GetState() { - } - if state != connectivity.Ready { - t.Fatalf("Want connection state to be Ready, got %v", state) - } - ctx, cancel = context.WithTimeout(context.Background(), time.Second) - defer cancel() - // Make a fail-fast RPC. - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_,_) = _, %v, want _, nil", err) - } -} - -type errCodec struct { - noError bool -} - -func (c *errCodec) Marshal(v interface{}) ([]byte, error) { - if c.noError { - return []byte{}, nil - } - return nil, fmt.Errorf("3987^12 + 4365^12 = 4472^12") -} - -func (c *errCodec) Unmarshal(data []byte, v interface{}) error { - return nil -} - -func (c *errCodec) String() string { - return "Fermat's near-miss." -} - -func TestEncodeDoesntPanic(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testEncodeDoesntPanic(t, e) - } -} - -func testEncodeDoesntPanic(t *testing.T, e env) { - te := newTest(t, e) - erc := &errCodec{} - te.customCodec = erc - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - te.customCodec = nil - tc := testpb.NewTestServiceClient(te.clientConn()) - // Failure case, should not panic. - tc.EmptyCall(context.Background(), &testpb.Empty{}) - erc.noError = true - // Passing case. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("EmptyCall(_, _) = _, %v, want _, <nil>", err) - } -} - -func TestSvrWriteStatusEarlyWrite(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testSvrWriteStatusEarlyWrite(t, e) - } -} - -func testSvrWriteStatusEarlyWrite(t *testing.T, e env) { - te := newTest(t, e) - const smallSize = 1024 - const largeSize = 2048 - const extraLargeSize = 4096 - te.maxServerReceiveMsgSize = newInt(largeSize) - te.maxServerSendMsgSize = newInt(largeSize) - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize) - if err != nil { - t.Fatal(err) - } - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - respParam := []*testpb.ResponseParameters{ - { - Size: proto.Int32(int32(smallSize)), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(), - ResponseParameters: respParam, - Payload: extraLargePayload, - } - // Test recv case: server receives a message larger than maxServerReceiveMsgSize. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send() = _, %v, want <nil>", stream, err) - } - if _, err = stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - // Test send case: server sends a message larger than maxServerSendMsgSize. - sreq.Payload = smallPayload - respParam[0].Size = proto.Int32(int32(extraLargeSize)) - - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want <nil>", tc, err) - } - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want <nil>", stream, sreq, err) - } - if _, err = stream.Recv(); err == nil || grpc.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } -} diff --git a/vendor/google.golang.org/grpc/test/grpc_testing/test.pb.go b/vendor/google.golang.org/grpc/test/grpc_testing/test.pb.go deleted file mode 100644 index bb6efbe7d..000000000 --- a/vendor/google.golang.org/grpc/test/grpc_testing/test.pb.go +++ /dev/null @@ -1,788 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_testing/test.proto - -/* -Package grpc_testing is a generated protocol buffer package. - -It is generated from these files: - grpc_testing/test.proto - -It has these top-level messages: - Empty - Payload - SimpleRequest - SimpleResponse - StreamingInputCallRequest - StreamingInputCallResponse - ResponseParameters - StreamingOutputCallRequest - StreamingOutputCallResponse -*/ -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The type of payload that should be returned. -type PayloadType int32 - -const ( - // Compressable text format. - PayloadType_COMPRESSABLE PayloadType = 0 - // Uncompressable binary format. - PayloadType_UNCOMPRESSABLE PayloadType = 1 - // Randomly chosen from all other formats defined in this enum. - PayloadType_RANDOM PayloadType = 2 -) - -var PayloadType_name = map[int32]string{ - 0: "COMPRESSABLE", - 1: "UNCOMPRESSABLE", - 2: "RANDOM", -} -var PayloadType_value = map[string]int32{ - "COMPRESSABLE": 0, - "UNCOMPRESSABLE": 1, - "RANDOM": 2, -} - -func (x PayloadType) Enum() *PayloadType { - p := new(PayloadType) - *p = x - return p -} -func (x PayloadType) String() string { - return proto.EnumName(PayloadType_name, int32(x)) -} -func (x *PayloadType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PayloadType_value, data, "PayloadType") - if err != nil { - return err - } - *x = PayloadType(value) - return nil -} -func (PayloadType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -type Empty struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -// A block of data, to simply increase gRPC message size. -type Payload struct { - // The type of data in body. - Type *PayloadType `protobuf:"varint,1,opt,name=type,enum=grpc.testing.PayloadType" json:"type,omitempty"` - // Primary contents of payload. - Body []byte `protobuf:"bytes,2,opt,name=body" json:"body,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Payload) Reset() { *m = Payload{} } -func (m *Payload) String() string { return proto.CompactTextString(m) } -func (*Payload) ProtoMessage() {} -func (*Payload) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *Payload) GetType() PayloadType { - if m != nil && m.Type != nil { - return *m.Type - } - return PayloadType_COMPRESSABLE -} - -func (m *Payload) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -// Unary request. -type SimpleRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - ResponseSize *int32 `protobuf:"varint,2,opt,name=response_size,json=responseSize" json:"response_size,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"` - // Whether SimpleResponse should include username. - FillUsername *bool `protobuf:"varint,4,opt,name=fill_username,json=fillUsername" json:"fill_username,omitempty"` - // Whether SimpleResponse should include OAuth scope. - FillOauthScope *bool `protobuf:"varint,5,opt,name=fill_oauth_scope,json=fillOauthScope" json:"fill_oauth_scope,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *SimpleRequest) GetResponseType() PayloadType { - if m != nil && m.ResponseType != nil { - return *m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *SimpleRequest) GetResponseSize() int32 { - if m != nil && m.ResponseSize != nil { - return *m.ResponseSize - } - return 0 -} - -func (m *SimpleRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleRequest) GetFillUsername() bool { - if m != nil && m.FillUsername != nil { - return *m.FillUsername - } - return false -} - -func (m *SimpleRequest) GetFillOauthScope() bool { - if m != nil && m.FillOauthScope != nil { - return *m.FillOauthScope - } - return false -} - -// Unary response, as configured by the request. -type SimpleResponse struct { - // Payload to increase message size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` - // The user the request came from, for verifying authentication was - // successful when the client expected it. - Username *string `protobuf:"bytes,2,opt,name=username" json:"username,omitempty"` - // OAuth scope. - OauthScope *string `protobuf:"bytes,3,opt,name=oauth_scope,json=oauthScope" json:"oauth_scope,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *SimpleResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleResponse) GetUsername() string { - if m != nil && m.Username != nil { - return *m.Username - } - return "" -} - -func (m *SimpleResponse) GetOauthScope() string { - if m != nil && m.OauthScope != nil { - return *m.OauthScope - } - return "" -} - -// Client-streaming request. -type StreamingInputCallRequest struct { - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} } -func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallRequest) ProtoMessage() {} -func (*StreamingInputCallRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -func (m *StreamingInputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Client-streaming response. -type StreamingInputCallResponse struct { - // Aggregated size of payloads received from the client. - AggregatedPayloadSize *int32 `protobuf:"varint,1,opt,name=aggregated_payload_size,json=aggregatedPayloadSize" json:"aggregated_payload_size,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} } -func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallResponse) ProtoMessage() {} -func (*StreamingInputCallResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } - -func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 { - if m != nil && m.AggregatedPayloadSize != nil { - return *m.AggregatedPayloadSize - } - return 0 -} - -// Configuration for a particular response. -type ResponseParameters struct { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - Size *int32 `protobuf:"varint,1,opt,name=size" json:"size,omitempty"` - // Desired interval between consecutive responses in the response stream in - // microseconds. - IntervalUs *int32 `protobuf:"varint,2,opt,name=interval_us,json=intervalUs" json:"interval_us,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ResponseParameters) Reset() { *m = ResponseParameters{} } -func (m *ResponseParameters) String() string { return proto.CompactTextString(m) } -func (*ResponseParameters) ProtoMessage() {} -func (*ResponseParameters) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } - -func (m *ResponseParameters) GetSize() int32 { - if m != nil && m.Size != nil { - return *m.Size - } - return 0 -} - -func (m *ResponseParameters) GetIntervalUs() int32 { - if m != nil && m.IntervalUs != nil { - return *m.IntervalUs - } - return 0 -} - -// Server-streaming request. -type StreamingOutputCallRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - ResponseType *PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Configuration for each expected response message. - ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters,json=responseParameters" json:"response_parameters,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload" json:"payload,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} } -func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallRequest) ProtoMessage() {} -func (*StreamingOutputCallRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } - -func (m *StreamingOutputCallRequest) GetResponseType() PayloadType { - if m != nil && m.ResponseType != nil { - return *m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters { - if m != nil { - return m.ResponseParameters - } - return nil -} - -func (m *StreamingOutputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Server-streaming response, as configured by the request and parameters. -type StreamingOutputCallResponse struct { - // Payload to increase response size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload" json:"payload,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} } -func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallResponse) ProtoMessage() {} -func (*StreamingOutputCallResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } - -func (m *StreamingOutputCallResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func init() { - proto.RegisterType((*Empty)(nil), "grpc.testing.Empty") - proto.RegisterType((*Payload)(nil), "grpc.testing.Payload") - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") - proto.RegisterType((*StreamingInputCallRequest)(nil), "grpc.testing.StreamingInputCallRequest") - proto.RegisterType((*StreamingInputCallResponse)(nil), "grpc.testing.StreamingInputCallResponse") - proto.RegisterType((*ResponseParameters)(nil), "grpc.testing.ResponseParameters") - proto.RegisterType((*StreamingOutputCallRequest)(nil), "grpc.testing.StreamingOutputCallRequest") - proto.RegisterType((*StreamingOutputCallResponse)(nil), "grpc.testing.StreamingOutputCallResponse") - proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for TestService service - -type TestServiceClient interface { - // One empty request followed by one empty response. - EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) - // A sequence of requests followed by a sequence of responses. - // 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 - // first request. - HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) -} - -type testServiceClient struct { - cc *grpc.ClientConn -} - -func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient { - return &testServiceClient{cc} -} - -func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := grpc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := grpc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[0], c.cc, "/grpc.testing.TestService/StreamingOutputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingOutputCallClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type TestService_StreamingOutputCallClient interface { - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingOutputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[1], c.cc, "/grpc.testing.TestService/StreamingInputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingInputCallClient{stream} - return x, nil -} - -type TestService_StreamingInputCallClient interface { - Send(*StreamingInputCallRequest) error - CloseAndRecv() (*StreamingInputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingInputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingInputCallClient) Send(m *StreamingInputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCallResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(StreamingInputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[2], c.cc, "/grpc.testing.TestService/FullDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceFullDuplexCallClient{stream} - return x, nil -} - -type TestService_FullDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceFullDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceFullDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { - stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[3], c.cc, "/grpc.testing.TestService/HalfDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceHalfDuplexCallClient{stream} - return x, nil -} - -type TestService_HalfDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceHalfDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceHalfDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for TestService service - -type TestServiceServer interface { - // One empty request followed by one empty response. - EmptyCall(context.Context, *Empty) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(TestService_StreamingInputCallServer) error - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(TestService_FullDuplexCallServer) error - // A sequence of requests followed by a sequence of responses. - // 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 - // first request. - HalfDuplexCall(TestService_HalfDuplexCallServer) error -} - -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) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).EmptyCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/EmptyCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(StreamingOutputCallRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) -} - -type TestService_StreamingOutputCallServer interface { - Send(*StreamingOutputCallResponse) error - grpc.ServerStream -} - -type testServiceStreamingOutputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallResponse) error { - 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 { - SendAndClose(*StreamingInputCallResponse) error - Recv() (*StreamingInputCallRequest, error) - grpc.ServerStream -} - -type testServiceStreamingInputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingInputCallServer) SendAndClose(m *StreamingInputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest, error) { - m := new(StreamingInputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} - -type TestService_FullDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceFullDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceFullDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) -} - -type TestService_HalfDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceHalfDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceHalfDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _TestService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - HandlerType: (*TestServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "EmptyCall", - Handler: _TestService_EmptyCall_Handler, - }, - { - MethodName: "UnaryCall", - Handler: _TestService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - 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: "grpc_testing/test.proto", -} - -func init() { proto.RegisterFile("grpc_testing/test.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 582 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0xdd, 0x6e, 0xd3, 0x4c, - 0x10, 0xfd, 0xb6, 0x49, 0xbe, 0x34, 0x93, 0xd4, 0x8a, 0x36, 0xaa, 0xea, 0xba, 0x48, 0x58, 0xe6, - 0x02, 0x83, 0x44, 0x8a, 0x22, 0xc1, 0x25, 0xa8, 0xb4, 0xa9, 0xa8, 0x94, 0x26, 0xc1, 0x4e, 0xae, - 0xa3, 0x25, 0xd9, 0x1a, 0x4b, 0x8e, 0xbd, 0xac, 0xd7, 0x15, 0xe9, 0x05, 0x2f, 0xc6, 0xcb, 0xf0, - 0x10, 0x3c, 0x00, 0x5a, 0xff, 0x24, 0x4e, 0xe2, 0x8a, 0x14, 0x04, 0x57, 0xb6, 0x67, 0xce, 0x9c, - 0x39, 0xc7, 0x33, 0xbb, 0x70, 0xe4, 0x70, 0x36, 0x9d, 0x08, 0x1a, 0x0a, 0xd7, 0x77, 0x4e, 0xe5, - 0xb3, 0xcd, 0x78, 0x20, 0x02, 0xdc, 0x90, 0x89, 0x76, 0x9a, 0x30, 0xaa, 0x50, 0xe9, 0xce, 0x99, - 0x58, 0x18, 0x3d, 0xa8, 0x0e, 0xc9, 0xc2, 0x0b, 0xc8, 0x0c, 0xbf, 0x80, 0xb2, 0x58, 0x30, 0xaa, - 0x22, 0x1d, 0x99, 0x4a, 0xe7, 0xb8, 0x9d, 0x2f, 0x68, 0xa7, 0xa0, 0xd1, 0x82, 0x51, 0x2b, 0x86, - 0x61, 0x0c, 0xe5, 0x8f, 0xc1, 0x6c, 0xa1, 0xee, 0xe9, 0xc8, 0x6c, 0x58, 0xf1, 0xbb, 0xf1, 0x03, - 0xc1, 0x81, 0xed, 0xce, 0x99, 0x47, 0x2d, 0xfa, 0x39, 0xa2, 0xa1, 0xc0, 0x6f, 0xe0, 0x80, 0xd3, - 0x90, 0x05, 0x7e, 0x48, 0x27, 0xbb, 0xb1, 0x37, 0x32, 0xbc, 0xfc, 0xc2, 0x4f, 0x72, 0xf5, 0xa1, - 0x7b, 0x47, 0xe3, 0x76, 0x95, 0x15, 0xc8, 0x76, 0xef, 0x28, 0x3e, 0x85, 0x2a, 0x4b, 0x18, 0xd4, - 0x92, 0x8e, 0xcc, 0x7a, 0xe7, 0xb0, 0x90, 0xde, 0xca, 0x50, 0x92, 0xf5, 0xc6, 0xf5, 0xbc, 0x49, - 0x14, 0x52, 0xee, 0x93, 0x39, 0x55, 0xcb, 0x3a, 0x32, 0xf7, 0xad, 0x86, 0x0c, 0x8e, 0xd3, 0x18, - 0x36, 0xa1, 0x19, 0x83, 0x02, 0x12, 0x89, 0x4f, 0x93, 0x70, 0x1a, 0x30, 0xaa, 0x56, 0x62, 0x9c, - 0x22, 0xe3, 0x03, 0x19, 0xb6, 0x65, 0xd4, 0xf8, 0x0a, 0x4a, 0xe6, 0x3a, 0x51, 0x95, 0x57, 0x84, - 0x76, 0x52, 0xa4, 0xc1, 0xfe, 0x52, 0x8c, 0xb4, 0x58, 0xb3, 0x96, 0xdf, 0xf8, 0x31, 0xd4, 0xf3, - 0x1a, 0x4a, 0x71, 0x1a, 0x82, 0x55, 0xff, 0x1e, 0x1c, 0xdb, 0x82, 0x53, 0x32, 0x77, 0x7d, 0xe7, - 0xca, 0x67, 0x91, 0x38, 0x27, 0x9e, 0x97, 0x4d, 0xe0, 0xa1, 0x52, 0x8c, 0x11, 0x68, 0x45, 0x6c, - 0xa9, 0xb3, 0xd7, 0x70, 0x44, 0x1c, 0x87, 0x53, 0x87, 0x08, 0x3a, 0x9b, 0xa4, 0x35, 0xc9, 0x68, - 0x50, 0x3c, 0x9a, 0xc3, 0x55, 0x3a, 0xa5, 0x96, 0x33, 0x32, 0xae, 0x00, 0x67, 0x1c, 0x43, 0xc2, - 0xc9, 0x9c, 0x0a, 0xca, 0x43, 0xb9, 0x44, 0xb9, 0xd2, 0xf8, 0x5d, 0xda, 0x75, 0x7d, 0x41, 0xf9, - 0x2d, 0x91, 0x03, 0x4a, 0x07, 0x0e, 0x59, 0x68, 0x1c, 0x1a, 0xdf, 0x51, 0x4e, 0xe1, 0x20, 0x12, - 0x1b, 0x86, 0xff, 0x74, 0xe5, 0x3e, 0x40, 0x6b, 0x59, 0xcf, 0x96, 0x52, 0xd5, 0x3d, 0xbd, 0x64, - 0xd6, 0x3b, 0xfa, 0x3a, 0xcb, 0xb6, 0x25, 0x0b, 0xf3, 0x6d, 0x9b, 0x0f, 0x5d, 0x50, 0xa3, 0x0f, - 0x27, 0x85, 0x0e, 0x7f, 0x73, 0xbd, 0x9e, 0xbf, 0x85, 0x7a, 0xce, 0x30, 0x6e, 0x42, 0xe3, 0x7c, - 0x70, 0x3d, 0xb4, 0xba, 0xb6, 0x7d, 0xf6, 0xae, 0xd7, 0x6d, 0xfe, 0x87, 0x31, 0x28, 0xe3, 0xfe, - 0x5a, 0x0c, 0x61, 0x80, 0xff, 0xad, 0xb3, 0xfe, 0xc5, 0xe0, 0xba, 0xb9, 0xd7, 0xf9, 0x56, 0x86, - 0xfa, 0x88, 0x86, 0xc2, 0xa6, 0xfc, 0xd6, 0x9d, 0x52, 0xfc, 0x0a, 0x6a, 0xf1, 0x05, 0x22, 0x65, - 0xe1, 0xd6, 0x7a, 0xf7, 0x38, 0xa1, 0x15, 0x05, 0xf1, 0x25, 0xd4, 0xc6, 0x3e, 0xe1, 0x49, 0xd9, - 0xc9, 0x3a, 0x62, 0xed, 0xe2, 0xd0, 0x1e, 0x15, 0x27, 0xd3, 0x1f, 0xe0, 0x41, 0xab, 0xe0, 0xff, - 0x60, 0x73, 0xa3, 0xe8, 0xde, 0x25, 0xd1, 0x9e, 0xed, 0x80, 0x4c, 0x7a, 0xbd, 0x44, 0xd8, 0x05, - 0xbc, 0x7d, 0x22, 0xf0, 0xd3, 0x7b, 0x28, 0x36, 0x4f, 0xa0, 0x66, 0xfe, 0x1a, 0x98, 0xb4, 0x32, - 0x65, 0x2b, 0xe5, 0x32, 0xf2, 0xbc, 0x8b, 0x88, 0x79, 0xf4, 0xcb, 0x5f, 0xf3, 0x64, 0xa2, 0xd8, - 0x95, 0xf2, 0x9e, 0x78, 0x37, 0xff, 0xa0, 0xd5, 0xcf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb8, 0xa6, - 0x30, 0x01, 0x96, 0x06, 0x00, 0x00, -} diff --git a/vendor/google.golang.org/grpc/test/grpc_testing/test.proto b/vendor/google.golang.org/grpc/test/grpc_testing/test.proto deleted file mode 100644 index fbd22dec9..000000000 --- a/vendor/google.golang.org/grpc/test/grpc_testing/test.proto +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An integration test service that covers all the method signature permutations -// of unary/streaming requests/responses. -syntax = "proto2"; - -package grpc.testing; - -message Empty {} - -// The type of payload that should be returned. -enum PayloadType { - // Compressable text format. - COMPRESSABLE = 0; - - // Uncompressable binary format. - UNCOMPRESSABLE = 1; - - // Randomly chosen from all other formats defined in this enum. - RANDOM = 2; -} - -// A block of data, to simply increase gRPC message size. -message Payload { - // The type of data in body. - optional PayloadType type = 1; - // Primary contents of payload. - optional bytes body = 2; -} - -// Unary request. -message SimpleRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - optional PayloadType response_type = 1; - - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - optional int32 response_size = 2; - - // Optional input payload sent along with the request. - optional Payload payload = 3; - - // Whether SimpleResponse should include username. - optional bool fill_username = 4; - - // Whether SimpleResponse should include OAuth scope. - optional bool fill_oauth_scope = 5; -} - -// Unary response, as configured by the request. -message SimpleResponse { - // Payload to increase message size. - optional Payload payload = 1; - - // The user the request came from, for verifying authentication was - // successful when the client expected it. - optional string username = 2; - - // OAuth scope. - optional string oauth_scope = 3; -} - -// Client-streaming request. -message StreamingInputCallRequest { - // Optional input payload sent along with the request. - optional Payload payload = 1; - - // Not expecting any payload from the response. -} - -// Client-streaming response. -message StreamingInputCallResponse { - // Aggregated size of payloads received from the client. - optional int32 aggregated_payload_size = 1; -} - -// Configuration for a particular response. -message ResponseParameters { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - optional int32 size = 1; - - // Desired interval between consecutive responses in the response stream in - // microseconds. - optional int32 interval_us = 2; -} - -// Server-streaming request. -message StreamingOutputCallRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - optional PayloadType response_type = 1; - - // Configuration for each expected response message. - repeated ResponseParameters response_parameters = 2; - - // Optional input payload sent along with the request. - optional Payload payload = 3; -} - -// Server-streaming response, as configured by the request and parameters. -message StreamingOutputCallResponse { - // Payload to increase response size. - optional Payload payload = 1; -} - -// A simple service to test the various types of RPCs and experiment with -// performance with various types of payload. -service TestService { - // One empty request followed by one empty response. - rpc EmptyCall(Empty) returns (Empty); - - // One request followed by one response. - // The server returns the client payload as-is. - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - rpc StreamingOutputCall(StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - rpc StreamingInputCall(stream StreamingInputCallRequest) - returns (StreamingInputCallResponse); - - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - rpc FullDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by a sequence of responses. - // 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 - // first request. - rpc HalfDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); -} diff --git a/vendor/google.golang.org/grpc/test/leakcheck/leakcheck.go b/vendor/google.golang.org/grpc/test/leakcheck/leakcheck.go deleted file mode 100644 index 76f9fc541..000000000 --- a/vendor/google.golang.org/grpc/test/leakcheck/leakcheck.go +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package leakcheck contains functions to check leaked goroutines. -// -// Call "defer leakcheck.Check(t)" at the beginning of tests. -package leakcheck - -import ( - "runtime" - "sort" - "strings" - "time" -) - -var goroutinesToIgnore = []string{ - "testing.Main(", - "testing.tRunner(", - "testing.(*M).", - "runtime.goexit", - "created by runtime.gc", - "created by runtime/trace.Start", - "interestingGoroutines", - "runtime.MHeap_Scavenger", - "signal.signal_recv", - "sigterm.handler", - "runtime_mcall", - "(*loggingT).flushDaemon", - "goroutine in C code", -} - -// RegisterIgnoreGoroutine appends s into the ignore goroutine list. The -// goroutines whose stack trace contains s will not be identified as leaked -// goroutines. Not thread-safe, only call this function in init(). -func RegisterIgnoreGoroutine(s string) { - goroutinesToIgnore = append(goroutinesToIgnore, s) -} - -func ignore(g string) bool { - sl := strings.SplitN(g, "\n", 2) - if len(sl) != 2 { - return true - } - stack := strings.TrimSpace(sl[1]) - if strings.HasPrefix(stack, "testing.RunTests") { - return true - } - - if stack == "" { - return true - } - - for _, s := range goroutinesToIgnore { - if strings.Contains(stack, s) { - return true - } - } - - return false -} - -// interestingGoroutines returns all goroutines we care about for the purpose of -// leak checking. It excludes testing or runtime ones. -func interestingGoroutines() (gs []string) { - buf := make([]byte, 2<<20) - buf = buf[:runtime.Stack(buf, true)] - for _, g := range strings.Split(string(buf), "\n\n") { - if !ignore(g) { - gs = append(gs, g) - } - } - sort.Strings(gs) - return -} - -// Errorfer is the interface that wraps the Errorf method. It's a subset of -// testing.TB to make it easy to use Check. -type Errorfer interface { - Errorf(format string, args ...interface{}) -} - -func check(efer Errorfer, timeout time.Duration) { - // Loop, waiting for goroutines to shut down. - // Wait up to timeout, but finish as quickly as possible. - deadline := time.Now().Add(timeout) - var leaked []string - for time.Now().Before(deadline) { - if leaked = interestingGoroutines(); len(leaked) == 0 { - return - } - time.Sleep(50 * time.Millisecond) - } - for _, g := range leaked { - efer.Errorf("Leaked goroutine: %v", g) - } -} - -// Check looks at the currently-running goroutines and checks if there are any -// interestring (created by gRPC) goroutines leaked. It waits up to 10 seconds -// in the error cases. -func Check(efer Errorfer) { - check(efer, 10*time.Second) -} diff --git a/vendor/google.golang.org/grpc/test/leakcheck/leakcheck_test.go b/vendor/google.golang.org/grpc/test/leakcheck/leakcheck_test.go deleted file mode 100644 index 50927e9db..000000000 --- a/vendor/google.golang.org/grpc/test/leakcheck/leakcheck_test.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package leakcheck - -import ( - "fmt" - "strings" - "testing" - "time" -) - -type testErrorfer struct { - errorCount int - errors []string -} - -func (e *testErrorfer) Errorf(format string, args ...interface{}) { - e.errors = append(e.errors, fmt.Sprintf(format, args...)) - e.errorCount++ -} - -func TestCheck(t *testing.T) { - const leakCount = 3 - for i := 0; i < leakCount; i++ { - go func() { time.Sleep(2 * time.Second) }() - } - if ig := interestingGoroutines(); len(ig) == 0 { - t.Error("blah") - } - e := &testErrorfer{} - check(e, time.Second) - if e.errorCount != leakCount { - t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount) - t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n")) - } - check(t, 3*time.Second) -} - -func ignoredTestingLeak(d time.Duration) { - time.Sleep(d) -} - -func TestCheckRegisterIgnore(t *testing.T) { - RegisterIgnoreGoroutine("ignoredTestingLeak") - const leakCount = 3 - for i := 0; i < leakCount; i++ { - go func() { time.Sleep(2 * time.Second) }() - } - go func() { ignoredTestingLeak(3 * time.Second) }() - if ig := interestingGoroutines(); len(ig) == 0 { - t.Error("blah") - } - e := &testErrorfer{} - check(e, time.Second) - if e.errorCount != leakCount { - t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount) - t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n")) - } - check(t, 3*time.Second) -} diff --git a/vendor/google.golang.org/grpc/test/race.go b/vendor/google.golang.org/grpc/test/race.go deleted file mode 100644 index acfa0dfae..000000000 --- a/vendor/google.golang.org/grpc/test/race.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build race - -/* - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package test - -func init() { - raceMode = true -} diff --git a/vendor/google.golang.org/grpc/test/servertester.go b/vendor/google.golang.org/grpc/test/servertester.go deleted file mode 100644 index daeca0622..000000000 --- a/vendor/google.golang.org/grpc/test/servertester.go +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test - -import ( - "bytes" - "errors" - "io" - "strings" - "testing" - "time" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" -) - -// This is a subset of http2's serverTester type. -// -// serverTester wraps a io.ReadWriter (acting like the underlying -// network connection) and provides utility methods to read and write -// http2 frames. -// -// NOTE(bradfitz): this could eventually be exported somewhere. Others -// have asked for it too. For now I'm still experimenting with the -// API and don't feel like maintaining a stable testing API. - -type serverTester struct { - cc io.ReadWriteCloser // client conn - t testing.TB - fr *http2.Framer - - // writing headers: - headerBuf bytes.Buffer - hpackEnc *hpack.Encoder - - // reading frames: - frc chan http2.Frame - frErrc chan error - readTimer *time.Timer -} - -func newServerTesterFromConn(t testing.TB, cc io.ReadWriteCloser) *serverTester { - st := &serverTester{ - t: t, - cc: cc, - frc: make(chan http2.Frame, 1), - frErrc: make(chan error, 1), - } - st.hpackEnc = hpack.NewEncoder(&st.headerBuf) - st.fr = http2.NewFramer(cc, cc) - st.fr.ReadMetaHeaders = hpack.NewDecoder(4096 /*initialHeaderTableSize*/, nil) - - return st -} - -func (st *serverTester) readFrame() (http2.Frame, error) { - go func() { - fr, err := st.fr.ReadFrame() - if err != nil { - st.frErrc <- err - } else { - st.frc <- fr - } - }() - t := time.NewTimer(2 * time.Second) - defer t.Stop() - select { - case f := <-st.frc: - return f, nil - case err := <-st.frErrc: - return nil, err - case <-t.C: - return nil, errors.New("timeout waiting for frame") - } -} - -// greet initiates the client's HTTP/2 connection into a state where -// frames may be sent. -func (st *serverTester) greet() { - st.writePreface() - st.writeInitialSettings() - st.wantSettings() - st.writeSettingsAck() - for { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - switch f := f.(type) { - case *http2.WindowUpdateFrame: - // grpc's transport/http2_server sends this - // before the settings ack. The Go http2 - // server uses a setting instead. - case *http2.SettingsFrame: - if f.IsAck() { - return - } - st.t.Fatalf("during greet, got non-ACK settings frame") - default: - st.t.Fatalf("during greet, unexpected frame type %T", f) - } - } -} - -func (st *serverTester) writePreface() { - n, err := st.cc.Write([]byte(http2.ClientPreface)) - if err != nil { - st.t.Fatalf("Error writing client preface: %v", err) - } - if n != len(http2.ClientPreface) { - st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(http2.ClientPreface)) - } -} - -func (st *serverTester) writeInitialSettings() { - if err := st.fr.WriteSettings(); err != nil { - st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err) - } -} - -func (st *serverTester) writeSettingsAck() { - if err := st.fr.WriteSettingsAck(); err != nil { - st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err) - } -} - -func (st *serverTester) wantSettings() *http2.SettingsFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err) - } - sf, ok := f.(*http2.SettingsFrame) - if !ok { - st.t.Fatalf("got a %T; want *SettingsFrame", f) - } - return sf -} - -func (st *serverTester) wantSettingsAck() { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - sf, ok := f.(*http2.SettingsFrame) - if !ok { - st.t.Fatalf("Wanting a settings ACK, received a %T", f) - } - if !sf.IsAck() { - st.t.Fatal("Settings Frame didn't have ACK set") - } -} - -// wait for any activity from the server -func (st *serverTester) wantAnyFrame() http2.Frame { - f, err := st.fr.ReadFrame() - if err != nil { - st.t.Fatal(err) - } - return f -} - -func (st *serverTester) encodeHeaderField(k, v string) { - err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v}) - if err != nil { - st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } -} - -// encodeHeader encodes headers and returns their HPACK bytes. headers -// must contain an even number of key/value pairs. There may be -// multiple pairs for keys (e.g. "cookie"). The :method, :path, and -// :scheme headers default to GET, / and https. -func (st *serverTester) encodeHeader(headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - - st.headerBuf.Reset() - - if len(headers) == 0 { - // Fast path, mostly for benchmarks, so test code doesn't pollute - // profiles when we're looking to improve server allocations. - st.encodeHeaderField(":method", "GET") - st.encodeHeaderField(":path", "/") - st.encodeHeaderField(":scheme", "https") - return st.headerBuf.Bytes() - } - - if len(headers) == 2 && headers[0] == ":method" { - // Another fast path for benchmarks. - st.encodeHeaderField(":method", headers[1]) - st.encodeHeaderField(":path", "/") - st.encodeHeaderField(":scheme", "https") - return st.headerBuf.Bytes() - } - - pseudoCount := map[string]int{} - keys := []string{":method", ":path", ":scheme"} - vals := map[string][]string{ - ":method": {"GET"}, - ":path": {"/"}, - ":scheme": {"https"}, - } - for len(headers) > 0 { - k, v := headers[0], headers[1] - headers = headers[2:] - if _, ok := vals[k]; !ok { - keys = append(keys, k) - } - if strings.HasPrefix(k, ":") { - pseudoCount[k]++ - if pseudoCount[k] == 1 { - vals[k] = []string{v} - } else { - // Allows testing of invalid headers w/ dup pseudo fields. - vals[k] = append(vals[k], v) - } - } else { - vals[k] = append(vals[k], v) - } - } - for _, k := range keys { - for _, v := range vals[k] { - st.encodeHeaderField(k, v) - } - } - return st.headerBuf.Bytes() -} - -func (st *serverTester) writeHeadersGRPC(streamID uint32, path string) { - st.writeHeaders(http2.HeadersFrameParam{ - StreamID: streamID, - BlockFragment: st.encodeHeader( - ":method", "POST", - ":path", path, - "content-type", "application/grpc", - "te", "trailers", - ), - EndStream: false, - EndHeaders: true, - }) -} - -func (st *serverTester) writeHeaders(p http2.HeadersFrameParam) { - if err := st.fr.WriteHeaders(p); err != nil { - st.t.Fatalf("Error writing HEADERS: %v", err) - } -} - -func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) { - if err := st.fr.WriteData(streamID, endStream, data); err != nil { - st.t.Fatalf("Error writing DATA: %v", err) - } -} - -func (st *serverTester) writeRSTStream(streamID uint32, code http2.ErrCode) { - if err := st.fr.WriteRSTStream(streamID, code); err != nil { - st.t.Fatalf("Error writing RST_STREAM: %v", err) - } -} - -func (st *serverTester) writeDataPadded(streamID uint32, endStream bool, data, padding []byte) { - if err := st.fr.WriteDataPadded(streamID, endStream, data, padding); err != nil { - st.t.Fatalf("Error writing DATA with padding: %v", err) - } -} diff --git a/vendor/google.golang.org/grpc/testdata/ca.pem b/vendor/google.golang.org/grpc/testdata/ca.pem deleted file mode 100644 index 6c8511a73..000000000 --- a/vendor/google.golang.org/grpc/testdata/ca.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICSjCCAbOgAwIBAgIJAJHGGR4dGioHMA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQxDzANBgNVBAMTBnRlc3RjYTAeFw0xNDExMTEyMjMxMjla -Fw0yNDExMDgyMjMxMjlaMFYxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0 -YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxDzANBgNVBAMT -BnRlc3RjYTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwEDfBV5MYdlHVHJ7 -+L4nxrZy7mBfAVXpOc5vMYztssUI7mL2/iYujiIXM+weZYNTEpLdjyJdu7R5gGUu -g1jSVK/EPHfc74O7AyZU34PNIP4Sh33N+/A5YexrNgJlPY+E3GdVYi4ldWJjgkAd -Qah2PH5ACLrIIC6tRka9hcaBlIECAwEAAaMgMB4wDAYDVR0TBAUwAwEB/zAOBgNV -HQ8BAf8EBAMCAgQwDQYJKoZIhvcNAQELBQADgYEAHzC7jdYlzAVmddi/gdAeKPau -sPBG/C2HCWqHzpCUHcKuvMzDVkY/MP2o6JIW2DBbY64bO/FceExhjcykgaYtCH/m -oIU63+CFOTtR7otyQAWHqXa7q4SbCDlG7DyRFxqG0txPtGvy12lgldA2+RgcigQG -Dfcog5wrJytaQ6UA0wE= ------END CERTIFICATE----- diff --git a/vendor/google.golang.org/grpc/testdata/server1.key b/vendor/google.golang.org/grpc/testdata/server1.key deleted file mode 100644 index 143a5b876..000000000 --- a/vendor/google.golang.org/grpc/testdata/server1.key +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOHDFScoLCVJpYDD -M4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1BgzkWF+slf -3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd9N8YwbBY -AckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAECgYAn7qGnM2vbjJNBm0VZCkOkTIWm -V10okw7EPJrdL2mkre9NasghNXbE1y5zDshx5Nt3KsazKOxTT8d0Jwh/3KbaN+YY -tTCbKGW0pXDRBhwUHRcuRzScjli8Rih5UOCiZkhefUTcRb6xIhZJuQy71tjaSy0p -dHZRmYyBYO2YEQ8xoQJBAPrJPhMBkzmEYFtyIEqAxQ/o/A6E+E4w8i+KM7nQCK7q -K4JXzyXVAjLfyBZWHGM2uro/fjqPggGD6QH1qXCkI4MCQQDmdKeb2TrKRh5BY1LR -81aJGKcJ2XbcDu6wMZK4oqWbTX2KiYn9GB0woM6nSr/Y6iy1u145YzYxEV/iMwff -DJULAkB8B2MnyzOg0pNFJqBJuH29bKCcHa8gHJzqXhNO5lAlEbMK95p/P2Wi+4Hd -aiEIAF1BF326QJcvYKmwSmrORp85AkAlSNxRJ50OWrfMZnBgzVjDx3xG6KsFQVk2 -ol6VhqL6dFgKUORFUWBvnKSyhjJxurlPEahV6oo6+A+mPhFY8eUvAkAZQyTdupP3 -XEFQKctGz+9+gKkemDp7LBBMEMBXrGTLPhpEfcjv/7KPdnFHYmhYeBTBnuVmTVWe -F98XJ7tIFfJq ------END PRIVATE KEY----- diff --git a/vendor/google.golang.org/grpc/testdata/server1.pem b/vendor/google.golang.org/grpc/testdata/server1.pem deleted file mode 100644 index f3d43fcc5..000000000 --- a/vendor/google.golang.org/grpc/testdata/server1.pem +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICnDCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJBVTET -MBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQ -dHkgTHRkMQ8wDQYDVQQDEwZ0ZXN0Y2EwHhcNMTUxMTA0MDIyMDI0WhcNMjUxMTAx -MDIyMDI0WjBlMQswCQYDVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNV -BAcTB0NoaWNhZ28xFTATBgNVBAoTDEV4YW1wbGUsIENvLjEaMBgGA1UEAxQRKi50 -ZXN0Lmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOHDFSco -LCVJpYDDM4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1Bg -zkWF+slf3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd -9N8YwbBYAckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAGjazBpMAkGA1UdEwQCMAAw -CwYDVR0PBAQDAgXgME8GA1UdEQRIMEaCECoudGVzdC5nb29nbGUuZnKCGHdhdGVy -em9vaS50ZXN0Lmdvb2dsZS5iZYISKi50ZXN0LnlvdXR1YmUuY29thwTAqAEDMA0G -CSqGSIb3DQEBCwUAA4GBAJFXVifQNub1LUP4JlnX5lXNlo8FxZ2a12AFQs+bzoJ6 -hM044EDjqyxUqSbVePK0ni3w1fHQB5rY9yYC5f8G7aqqTY1QOhoUk8ZTSTRpnkTh -y4jjdvTZeLDVBlueZUTDRmy2feY5aZIU18vFDK08dTG0A87pppuv1LNIR3loveU8 ------END CERTIFICATE----- diff --git a/vendor/google.golang.org/grpc/testdata/testdata.go b/vendor/google.golang.org/grpc/testdata/testdata.go deleted file mode 100644 index 5609b19b3..000000000 --- a/vendor/google.golang.org/grpc/testdata/testdata.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package testdata - -import ( - "log" - "os" - "path/filepath" -) - -// Path returns the absolute path the given relative file or directory path, -// relative to the google.golang.org/grpc/testdata directory in the user's GOPATH. -// If rel is already absolute, it is returned unmodified. -func Path(rel string) string { - if filepath.IsAbs(rel) { - return rel - } - - v, err := goPackagePath("google.golang.org/grpc/testdata") - if err != nil { - log.Fatalf("Error finding google.golang.org/grpc/testdata directory: %v", err) - } - - return filepath.Join(v, rel) -} - -func goPackagePath(pkg string) (path string, err error) { - gp := os.Getenv("GOPATH") - if gp == "" { - return path, os.ErrNotExist - } - - for _, p := range filepath.SplitList(gp) { - dir := filepath.Join(p, "src", filepath.FromSlash(pkg)) - fi, err := os.Stat(dir) - if os.IsNotExist(err) { - continue - } - if err != nil { - return "", err - } - if !fi.IsDir() { - continue - } - return dir, nil - } - return path, os.ErrNotExist -} diff --git a/vendor/google.golang.org/grpc/transport/bdp_estimator.go b/vendor/google.golang.org/grpc/transport/bdp_estimator.go index 8dd2ed427..63cd2627c 100644 --- a/vendor/google.golang.org/grpc/transport/bdp_estimator.go +++ b/vendor/google.golang.org/grpc/transport/bdp_estimator.go @@ -41,12 +41,9 @@ const ( gamma = 2 ) -var ( - // Adding arbitrary data to ping so that its ack can be - // identified. - // Easter-egg: what does the ping message say? - bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} -) +// Adding arbitrary data to ping so that its ack can be identified. +// Easter-egg: what does the ping message say? +var bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} type bdpEstimator struct { // sentAt is the time when the ping was sent. diff --git a/vendor/google.golang.org/grpc/transport/control.go b/vendor/google.golang.org/grpc/transport/control.go index dd1a8d42e..63194830d 100644 --- a/vendor/google.golang.org/grpc/transport/control.go +++ b/vendor/google.golang.org/grpc/transport/control.go @@ -20,9 +20,9 @@ package transport import ( "fmt" + "io" "math" "sync" - "sync/atomic" "time" "golang.org/x/net/http2" @@ -49,7 +49,7 @@ const ( // defaultLocalSendQuota sets is default value for number of data // bytes that each stream can schedule before some of it being // flushed out. - defaultLocalSendQuota = 64 * 1024 + defaultLocalSendQuota = 128 * 1024 ) // The following defines various control items which could flow through @@ -89,12 +89,16 @@ type windowUpdate struct { func (*windowUpdate) item() {} type settings struct { - ack bool - ss []http2.Setting + ss []http2.Setting } func (*settings) item() {} +type settingsAck struct { +} + +func (*settingsAck) item() {} + type resetStream struct { streamID uint32 code http2.ErrCode @@ -126,9 +130,8 @@ func (*ping) item() {} // quotaPool is a pool which accumulates the quota and sends it to acquire() // when it is available. type quotaPool struct { - c chan int - mu sync.Mutex + c chan struct{} version uint32 quota int } @@ -136,12 +139,8 @@ type quotaPool struct { // newQuotaPool creates a quotaPool which has quota q available to consume. func newQuotaPool(q int) *quotaPool { qb := "aPool{ - c: make(chan int, 1), - } - if q > 0 { - qb.c <- q - } else { - qb.quota = q + quota: q, + c: make(chan struct{}, 1), } return qb } @@ -155,60 +154,83 @@ func (qb *quotaPool) add(v int) { } func (qb *quotaPool) lockedAdd(v int) { - select { - case n := <-qb.c: - qb.quota += n - default: - } - qb.quota += v + var wakeUp bool if qb.quota <= 0 { - return + wakeUp = true // Wake up potential waiters. } - // After the pool has been created, this is the only place that sends on - // the channel. Since mu is held at this point and any quota that was sent - // on the channel has been retrieved, we know that this code will always - // place any positive quota value on the channel. - select { - case qb.c <- qb.quota: - qb.quota = 0 - default: + qb.quota += v + if wakeUp && qb.quota > 0 { + select { + case qb.c <- struct{}{}: + default: + } } } func (qb *quotaPool) addAndUpdate(v int) { qb.mu.Lock() - defer qb.mu.Unlock() qb.lockedAdd(v) - // Update the version only after having added to the quota - // so that if acquireWithVesrion sees the new vesrion it is - // guaranteed to have seen the updated quota. - // Also, still keep this inside of the lock, so that when - // compareAndExecute is processing, this function doesn't - // get executed partially (quota gets updated but the version - // doesn't). - atomic.AddUint32(&(qb.version), 1) + qb.version++ + qb.mu.Unlock() } -func (qb *quotaPool) acquireWithVersion() (<-chan int, uint32) { - return qb.c, atomic.LoadUint32(&(qb.version)) +func (qb *quotaPool) get(v int, wc waiters) (int, uint32, error) { + qb.mu.Lock() + if qb.quota > 0 { + if v > qb.quota { + v = qb.quota + } + qb.quota -= v + ver := qb.version + qb.mu.Unlock() + return v, ver, nil + } + qb.mu.Unlock() + for { + select { + case <-wc.ctx.Done(): + return 0, 0, ContextErr(wc.ctx.Err()) + case <-wc.tctx.Done(): + return 0, 0, ErrConnClosing + case <-wc.done: + return 0, 0, io.EOF + case <-wc.goAway: + return 0, 0, errStreamDrain + case <-qb.c: + qb.mu.Lock() + if qb.quota > 0 { + if v > qb.quota { + v = qb.quota + } + qb.quota -= v + ver := qb.version + if qb.quota > 0 { + select { + case qb.c <- struct{}{}: + default: + } + } + qb.mu.Unlock() + return v, ver, nil + + } + qb.mu.Unlock() + } + } } func (qb *quotaPool) compareAndExecute(version uint32, success, failure func()) bool { qb.mu.Lock() - defer qb.mu.Unlock() - if version == atomic.LoadUint32(&(qb.version)) { + if version == qb.version { success() + qb.mu.Unlock() return true } failure() + qb.mu.Unlock() return false } -// acquire returns the channel on which available quota amounts are sent. -func (qb *quotaPool) acquire() <-chan int { - return qb.c -} - // inFlow deals with inbound flow control type inFlow struct { mu sync.Mutex diff --git a/vendor/google.golang.org/grpc/transport/go16.go b/vendor/google.golang.org/grpc/transport/go16.go new file mode 100644 index 000000000..7cffee11e --- /dev/null +++ b/vendor/google.golang.org/grpc/transport/go16.go @@ -0,0 +1,45 @@ +// +build go1.6,!go1.7 + +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package transport + +import ( + "net" + + "google.golang.org/grpc/codes" + + "golang.org/x/net/context" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) +} + +// ContextErr converts the error from context package into a StreamError. +func ContextErr(err error) StreamError { + switch err { + case context.DeadlineExceeded: + return streamErrorf(codes.DeadlineExceeded, "%v", err) + case context.Canceled: + return streamErrorf(codes.Canceled, "%v", err) + } + return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) +} diff --git a/vendor/google.golang.org/grpc/transport/go17.go b/vendor/google.golang.org/grpc/transport/go17.go new file mode 100644 index 000000000..2464e69fa --- /dev/null +++ b/vendor/google.golang.org/grpc/transport/go17.go @@ -0,0 +1,46 @@ +// +build go1.7 + +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package transport + +import ( + "context" + "net" + + "google.golang.org/grpc/codes" + + netctx "golang.org/x/net/context" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, network, address) +} + +// ContextErr converts the error from context package into a StreamError. +func ContextErr(err error) StreamError { + switch err { + case context.DeadlineExceeded, netctx.DeadlineExceeded: + return streamErrorf(codes.DeadlineExceeded, "%v", err) + case context.Canceled, netctx.Canceled: + return streamErrorf(codes.Canceled, "%v", err) + } + return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) +} diff --git a/vendor/google.golang.org/grpc/transport/handler_server.go b/vendor/google.golang.org/grpc/transport/handler_server.go index f1f6caf89..7e0fdb359 100644 --- a/vendor/google.golang.org/grpc/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/transport/handler_server.go @@ -123,10 +123,9 @@ type serverHandlerTransport struct { // when WriteStatus is called. writes chan func() - mu sync.Mutex - // streamDone indicates whether WriteStatus has been called and writes channel - // has been closed. - streamDone bool + // block concurrent WriteStatus calls + // e.g. grpc/(*serverStream).SendMsg/RecvMsg + writeStatusMu sync.Mutex } func (ht *serverHandlerTransport) Close() error { @@ -177,13 +176,9 @@ func (ht *serverHandlerTransport) do(fn func()) error { } func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error { - ht.mu.Lock() - if ht.streamDone { - ht.mu.Unlock() - return nil - } - ht.streamDone = true - ht.mu.Unlock() + ht.writeStatusMu.Lock() + defer ht.writeStatusMu.Unlock() + err := ht.do(func() { ht.writeCommonHeaders(s) @@ -222,7 +217,11 @@ func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) erro } } }) - close(ht.writes) + + if err == nil { // transport has not been closed + ht.Close() + close(ht.writes) + } return err } diff --git a/vendor/google.golang.org/grpc/transport/handler_server_test.go b/vendor/google.golang.org/grpc/transport/handler_server_test.go index 06fe813ca..8505e1a7f 100644 --- a/vendor/google.golang.org/grpc/transport/handler_server_test.go +++ b/vendor/google.golang.org/grpc/transport/handler_server_test.go @@ -391,9 +391,10 @@ func TestHandlerTransport_HandleStreams_Timeout(t *testing.T) { } } +// TestHandlerTransport_HandleStreams_MultiWriteStatus ensures that +// concurrent "WriteStatus"s do not panic writing to closed "writes" channel. func TestHandlerTransport_HandleStreams_MultiWriteStatus(t *testing.T) { - st := newHandleStreamTest(t) - handleStream := func(s *Stream) { + testHandlerTransportHandleStreams(t, func(st *handleStreamTest, s *Stream) { if want := "/service/foo.bar"; s.method != want { t.Errorf("stream method = %q; want %q", s.method, want) } @@ -408,9 +409,27 @@ func TestHandlerTransport_HandleStreams_MultiWriteStatus(t *testing.T) { }() } wg.Wait() - } + }) +} + +// TestHandlerTransport_HandleStreams_WriteStatusWrite ensures that "Write" +// following "WriteStatus" does not panic writing to closed "writes" channel. +func TestHandlerTransport_HandleStreams_WriteStatusWrite(t *testing.T) { + testHandlerTransportHandleStreams(t, func(st *handleStreamTest, s *Stream) { + if want := "/service/foo.bar"; s.method != want { + t.Errorf("stream method = %q; want %q", s.method, want) + } + st.bodyw.Close() // no body + + st.ht.WriteStatus(s, status.New(codes.OK, "")) + st.ht.Write(s, []byte("hdr"), []byte("data"), &Options{}) + }) +} + +func testHandlerTransportHandleStreams(t *testing.T, handleStream func(st *handleStreamTest, s *Stream)) { + st := newHandleStreamTest(t) st.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, + func(s *Stream) { go handleStream(st, s) }, func(ctx context.Context, method string) context.Context { return ctx }, ) } diff --git a/vendor/google.golang.org/grpc/transport/http2_client.go b/vendor/google.golang.org/grpc/transport/http2_client.go index 1abb62e6d..0f58a390a 100644 --- a/vendor/google.golang.org/grpc/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/transport/http2_client.go @@ -44,7 +44,6 @@ import ( type http2Client struct { ctx context.Context cancel context.CancelFunc - target string // server name/addr userAgent string md interface{} conn net.Conn // underlying communication channel @@ -69,6 +68,9 @@ type http2Client struct { fc *inFlow // sendQuotaPool provides flow control to outbound message. sendQuotaPool *quotaPool + // localSendQuota limits the amount of data that can be scheduled + // for writing before it is actually written out. + localSendQuota *quotaPool // streamsQuota limits the max number of concurrent streams. streamsQuota *quotaPool @@ -109,7 +111,7 @@ func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error if fn != nil { return fn(ctx, addr) } - return (&net.Dialer{}).DialContext(ctx, "tcp", addr) + return dialContext(ctx, "tcp", addr) } func isTemporary(err error) bool { @@ -148,9 +150,11 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t ctx, cancel := context.WithCancel(ctx) connectCtx, connectCancel := context.WithTimeout(ctx, timeout) defer func() { - connectCancel() if err != nil { cancel() + // Don't call connectCancel in success path due to a race in Go 1.6: + // https://github.com/golang/go/issues/15078. + connectCancel() } }() @@ -173,7 +177,7 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t ) if creds := opts.TransportCredentials; creds != nil { scheme = "https" - conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Addr, conn) + conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Authority, conn) if err != nil { // Credentials handshake errors are typically considered permanent // to avoid retrying on e.g. bad certificates. @@ -208,7 +212,6 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t t := &http2Client{ ctx: ctx, cancel: cancel, - target: addr.Addr, userAgent: opts.UserAgent, md: addr.Metadata, conn: conn, @@ -225,6 +228,7 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t controlBuf: newControlBuffer(), fc: &inFlow{limit: uint32(icwz)}, sendQuotaPool: newQuotaPool(defaultWindowSize), + localSendQuota: newQuotaPool(defaultLocalSendQuota), scheme: scheme, state: reachable, activeStreams: make(map[uint32]*Stream), @@ -307,16 +311,15 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { // TODO(zhaoq): Handle uint32 overflow of Stream.id. s := &Stream{ - id: t.nextID, - done: make(chan struct{}), - goAway: make(chan struct{}), - method: callHdr.Method, - sendCompress: callHdr.SendCompress, - buf: newRecvBuffer(), - fc: &inFlow{limit: uint32(t.initialWindowSize)}, - sendQuotaPool: newQuotaPool(int(t.streamSendQuota)), - localSendQuota: newQuotaPool(defaultLocalSendQuota), - headerChan: make(chan struct{}), + id: t.nextID, + done: make(chan struct{}), + goAway: make(chan struct{}), + method: callHdr.Method, + sendCompress: callHdr.SendCompress, + buf: newRecvBuffer(), + fc: &inFlow{limit: uint32(t.initialWindowSize)}, + sendQuotaPool: newQuotaPool(int(t.streamSendQuota)), + headerChan: make(chan struct{}), } t.nextID += 2 s.requestRead = func(n int) { @@ -336,7 +339,12 @@ func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { t.updateWindow(s, uint32(n)) }, } - + s.waiters = waiters{ + ctx: s.ctx, + tctx: t.ctx, + done: s.done, + goAway: s.goAway, + } return s } @@ -402,22 +410,18 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea } if t.state == draining { t.mu.Unlock() - return nil, ErrStreamDrain + return nil, errStreamDrain } if t.state != reachable { t.mu.Unlock() return nil, ErrConnClosing } t.mu.Unlock() - sq, err := wait(ctx, t.ctx, nil, nil, t.streamsQuota.acquire()) - if err != nil { + // Get a quota of 1 from streamsQuota. + if _, _, err := t.streamsQuota.get(1, waiters{ctx: ctx, tctx: t.ctx}); err != nil { return nil, err } - // Returns the quota balance back. - if sq > 1 { - t.streamsQuota.add(sq - 1) - } - // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields + // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. // Make the slice of certain predictable size to reduce allocations made by append. hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te @@ -477,7 +481,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea if t.state == draining { t.mu.Unlock() t.streamsQuota.add(1) - return nil, ErrStreamDrain + return nil, errStreamDrain } if t.state != reachable { t.mu.Unlock() @@ -505,10 +509,6 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea }) t.mu.Unlock() - s.mu.Lock() - s.bytesSent = true - s.mu.Unlock() - if t.statsHandler != nil { outHeader := &stats.OutHeader{ Client: true, @@ -582,16 +582,16 @@ func (t *http2Client) CloseStream(s *Stream, err error) { // Close kicks off the shutdown process of the transport. This should be called // only once on a transport. Once it is called, the transport should not be // accessed any more. -func (t *http2Client) Close() (err error) { +func (t *http2Client) Close() error { t.mu.Lock() if t.state == closing { t.mu.Unlock() - return + return nil } t.state = closing t.mu.Unlock() t.cancel() - err = t.conn.Close() + err := t.conn.Close() t.mu.Lock() streams := t.activeStreams t.activeStreams = nil @@ -659,44 +659,44 @@ func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) e } hdr = append(hdr, data[:emptyLen]...) data = data[emptyLen:] + var ( + streamQuota int + streamQuotaVer uint32 + err error + ) for idx, r := range [][]byte{hdr, data} { for len(r) > 0 { size := http2MaxFrameLen - // Wait until the stream has some quota to send the data. - quotaChan, quotaVer := s.sendQuotaPool.acquireWithVersion() - sq, err := wait(s.ctx, t.ctx, s.done, s.goAway, quotaChan) - if err != nil { - return err + if size > len(r) { + size = len(r) + } + if streamQuota == 0 { // Used up all the locally cached stream quota. + // Get all the stream quota there is. + streamQuota, streamQuotaVer, err = s.sendQuotaPool.get(math.MaxInt32, s.waiters) + if err != nil { + return err + } + } + if size > streamQuota { + size = streamQuota } - // Wait until the transport has some quota to send the data. - tq, err := wait(s.ctx, t.ctx, s.done, s.goAway, t.sendQuotaPool.acquire()) + + // Get size worth quota from transport. + tq, _, err := t.sendQuotaPool.get(size, s.waiters) if err != nil { return err } - if sq < size { - size = sq - } if tq < size { size = tq } - if size > len(r) { - size = len(r) - } - p := r[:size] - ps := len(p) - if ps < tq { - // Overbooked transport quota. Return it back. - t.sendQuotaPool.add(tq - ps) - } - // Acquire local send quota to be able to write to the controlBuf. - ltq, err := wait(s.ctx, t.ctx, s.done, s.goAway, s.localSendQuota.acquire()) + ltq, _, err := t.localSendQuota.get(size, s.waiters) if err != nil { - if _, ok := err.(ConnectionError); !ok { - t.sendQuotaPool.add(ps) - } return err } - s.localSendQuota.add(ltq - ps) // It's ok if we make it negative. + // even if ltq is smaller than size we don't adjust size since + // ltq is only a soft limit. + streamQuota -= size + p := r[:size] var endStream bool // See if this is the last frame to be written. if opts.Last { @@ -711,21 +711,25 @@ func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) e } } success := func() { - t.controlBuf.put(&dataFrame{streamID: s.id, endStream: endStream, d: p, f: func() { s.localSendQuota.add(ps) }}) - if ps < sq { - s.sendQuotaPool.lockedAdd(sq - ps) - } - r = r[ps:] + ltq := ltq + t.controlBuf.put(&dataFrame{streamID: s.id, endStream: endStream, d: p, f: func() { t.localSendQuota.add(ltq) }}) + r = r[size:] } - failure := func() { - s.sendQuotaPool.lockedAdd(sq) + failure := func() { // The stream quota version must have changed. + // Our streamQuota cache is invalidated now, so give it back. + s.sendQuotaPool.lockedAdd(streamQuota + size) } - if !s.sendQuotaPool.compareAndExecute(quotaVer, success, failure) { - t.sendQuotaPool.add(ps) - s.localSendQuota.add(ps) + if !s.sendQuotaPool.compareAndExecute(streamQuotaVer, success, failure) { + // Couldn't send this chunk out. + t.sendQuotaPool.add(size) + t.localSendQuota.add(ltq) + streamQuota = 0 } } } + if streamQuota > 0 { // Add the left over quota back to stream. + s.sendQuotaPool.add(streamQuota) + } if !opts.Last { return nil } @@ -791,7 +795,6 @@ func (t *http2Client) updateFlowControl(n uint32) { t.mu.Unlock() t.controlBuf.put(&windowUpdate{0, t.fc.newLimit(n)}) t.controlBuf.put(&settings{ - ack: false, ss: []http2.Setting{ { ID: http2.SettingInitialWindowSize, @@ -894,7 +897,13 @@ func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { close(s.headerChan) s.headerDone = true } - statusCode, ok := http2ErrConvTab[http2.ErrCode(f.ErrCode)] + + code := http2.ErrCode(f.ErrCode) + if code == http2.ErrCodeRefusedStream { + // The stream was unprocessed by the server. + s.unprocessed = true + } + statusCode, ok := http2ErrConvTab[code] if !ok { warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode) statusCode = codes.Unknown @@ -904,17 +913,48 @@ func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { s.write(recvMsg{err: io.EOF}) } -func (t *http2Client) handleSettings(f *http2.SettingsFrame) { +func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) { if f.IsAck() { return } - var ss []http2.Setting + var rs []http2.Setting + var ps []http2.Setting + isMaxConcurrentStreamsMissing := true f.ForeachSetting(func(s http2.Setting) error { - ss = append(ss, s) + if s.ID == http2.SettingMaxConcurrentStreams { + isMaxConcurrentStreamsMissing = false + } + if t.isRestrictive(s) { + rs = append(rs, s) + } else { + ps = append(ps, s) + } return nil }) - // The settings will be applied once the ack is sent. - t.controlBuf.put(&settings{ack: true, ss: ss}) + if isFirst && isMaxConcurrentStreamsMissing { + // This means server is imposing no limits on + // maximum number of concurrent streams initiated by client. + // So we must remove our self-imposed limit. + ps = append(ps, http2.Setting{ + ID: http2.SettingMaxConcurrentStreams, + Val: math.MaxUint32, + }) + } + t.applySettings(rs) + t.controlBuf.put(&settingsAck{}) + t.applySettings(ps) +} + +func (t *http2Client) isRestrictive(s http2.Setting) bool { + switch s.ID { + case http2.SettingMaxConcurrentStreams: + return int(s.Val) < t.maxStreams + case http2.SettingInitialWindowSize: + // Note: we don't acquire a lock here to read streamSendQuota + // because the same goroutine updates it later. + return s.Val < t.streamSendQuota + } + return false } func (t *http2Client) handlePing(f *http2.PingFrame) { @@ -945,12 +985,16 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { t.Close() return } - // A client can receive multiple GoAways from server (look at https://github.com/grpc/grpc-go/issues/1387). - // The idea is that the first GoAway will be sent with an ID of MaxInt32 and the second GoAway will be sent after an RTT delay - // with the ID of the last stream the server will process. - // Therefore, when we get the first GoAway we don't really close any streams. While in case of second GoAway we - // close all streams created after the second GoAwayId. This way streams that were in-flight while the GoAway from server - // was being sent don't get killed. + // A client can receive multiple GoAways from the server (see + // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first + // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be + // sent after an RTT delay with the ID of the last stream the server will + // process. + // + // Therefore, when we get the first GoAway we don't necessarily close any + // streams. While in case of second GoAway we close all streams created after + // the GoAwayId. This way streams that were in-flight while the GoAway from + // server was being sent don't get killed. select { case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways). // If there are multiple GoAways the first one should always have an ID greater than the following ones. @@ -972,6 +1016,11 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { } for streamID, stream := range t.activeStreams { if streamID > id && streamID <= upperLimit { + // The stream was unprocessed by the server. + stream.mu.Lock() + stream.unprocessed = true + stream.finish(statusGoAway) + stream.mu.Unlock() close(stream.goAway) } } @@ -988,11 +1037,11 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { // It expects a lock on transport's mutext to be held by // the caller. func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { - t.goAwayReason = NoReason + t.goAwayReason = GoAwayNoReason switch f.ErrCode { case http2.ErrCodeEnhanceYourCalm: if string(f.DebugData()) == "too_many_pings" { - t.goAwayReason = TooManyPings + t.goAwayReason = GoAwayTooManyPings } } } @@ -1111,7 +1160,7 @@ func (t *http2Client) reader() { t.Close() return } - t.handleSettings(sf) + t.handleSettings(sf, true) // loop to keep reading incoming messages on this transport. for { @@ -1144,7 +1193,7 @@ func (t *http2Client) reader() { case *http2.RSTStreamFrame: t.handleRSTStream(frame) case *http2.SettingsFrame: - t.handleSettings(frame) + t.handleSettings(frame, false) case *http2.PingFrame: t.handlePing(frame) case *http2.GoAwayFrame: @@ -1167,10 +1216,8 @@ func (t *http2Client) applySettings(ss []http2.Setting) { if s.Val > math.MaxInt32 { s.Val = math.MaxInt32 } - t.mu.Lock() ms := t.maxStreams t.maxStreams = int(s.Val) - t.mu.Unlock() t.streamsQuota.add(int(s.Val) - ms) case http2.SettingInitialWindowSize: t.mu.Lock() @@ -1189,6 +1236,11 @@ func (t *http2Client) applySettings(ss []http2.Setting) { // The transport layer needs to be refactored to take care of this. func (t *http2Client) itemHandler(i item) error { var err error + defer func() { + if err != nil { + errorf(" error in itemHandler: %v", err) + } + }() switch i := i.(type) { case *dataFrame: err = t.framer.fr.WriteData(i.streamID, i.endStream, i.d) @@ -1231,12 +1283,9 @@ func (t *http2Client) itemHandler(i item) error { case *windowUpdate: err = t.framer.fr.WriteWindowUpdate(i.streamID, i.increment) case *settings: - if i.ack { - t.applySettings(i.ss) - err = t.framer.fr.WriteSettingsAck() - } else { - err = t.framer.fr.WriteSettings(i.ss...) - } + err = t.framer.fr.WriteSettings(i.ss...) + case *settingsAck: + err = t.framer.fr.WriteSettingsAck() case *resetStream: // If the server needs to be to intimated about stream closing, // then we need to make sure the RST_STREAM frame is written to @@ -1253,7 +1302,7 @@ func (t *http2Client) itemHandler(i item) error { } err = t.framer.fr.WritePing(i.ack, i.data) default: - errorf("transport: http2Client.controller got unexpected item type %v\n", i) + errorf("transport: http2Client.controller got unexpected item type %v", i) } return err } diff --git a/vendor/google.golang.org/grpc/transport/http2_server.go b/vendor/google.golang.org/grpc/transport/http2_server.go index bad29b88a..4a95363cc 100644 --- a/vendor/google.golang.org/grpc/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/transport/http2_server.go @@ -70,7 +70,10 @@ type http2Server struct { fc *inFlow // sendQuotaPool provides flow control to outbound message. sendQuotaPool *quotaPool - stats stats.Handler + // localSendQuota limits the amount of data that can be scheduled + // for writing before it is actually written out. + localSendQuota *quotaPool + stats stats.Handler // Flag to keep track of reading activity on transport. // 1 is true and 0 is false. activity uint32 // Accessed atomically. @@ -152,12 +155,12 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err Val: uint32(iwz)}) } if err := framer.fr.WriteSettings(isettings...); err != nil { - return nil, connectionErrorf(true, err, "transport: %v", err) + return nil, connectionErrorf(false, err, "transport: %v", err) } // Adjust the connection flow control window if needed. if delta := uint32(icwz - defaultWindowSize); delta > 0 { if err := framer.fr.WriteWindowUpdate(0, delta); err != nil { - return nil, connectionErrorf(true, err, "transport: %v", err) + return nil, connectionErrorf(false, err, "transport: %v", err) } } kp := config.KeepaliveParams @@ -199,6 +202,7 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err controlBuf: newControlBuffer(), fc: &inFlow{limit: uint32(icwz)}, sendQuotaPool: newQuotaPool(defaultWindowSize), + localSendQuota: newQuotaPool(defaultLocalSendQuota), state: reachable, activeStreams: make(map[uint32]*Stream), streamSendQuota: defaultWindowSize, @@ -223,6 +227,31 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err t.stats.HandleConn(t.ctx, connBegin) } t.framer.writer.Flush() + + // Check the validity of client preface. + preface := make([]byte, len(clientPreface)) + if _, err := io.ReadFull(t.conn, preface); err != nil { + return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) + } + if !bytes.Equal(preface, clientPreface) { + return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams received bogus greeting from client: %q", preface) + } + + frame, err := t.framer.fr.ReadFrame() + if err == io.EOF || err == io.ErrUnexpectedEOF { + t.Close() + return + } + if err != nil { + return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to read initial settings frame: %v", err) + } + atomic.StoreUint32(&t.activity, 1) + sf, ok := frame.(*http2.SettingsFrame) + if !ok { + return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams saw invalid preface type %T from client", frame) + } + t.handleSettings(sf) + go func() { loopyWriter(t.ctx, t.controlBuf, t.itemHandler) t.Close() @@ -316,7 +345,6 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( } t.maxStreamID = streamID s.sendQuotaPool = newQuotaPool(int(t.streamSendQuota)) - s.localSendQuota = newQuotaPool(defaultLocalSendQuota) t.activeStreams[streamID] = s if len(t.activeStreams) == 1 { t.idle = time.Time{} @@ -346,6 +374,10 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( t.updateWindow(s, uint32(n)) }, } + s.waiters = waiters{ + ctx: s.ctx, + tctx: t.ctx, + } handle(s) return } @@ -354,41 +386,6 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( // typically run in a separate goroutine. // traceCtx attaches trace to ctx and returns the new context. func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context.Context, string) context.Context) { - // Check the validity of client preface. - preface := make([]byte, len(clientPreface)) - if _, err := io.ReadFull(t.conn, preface); err != nil { - // Only log if it isn't a simple tcp accept check (ie: tcp balancer doing open/close socket) - if err != io.EOF { - errorf("transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) - } - t.Close() - return - } - if !bytes.Equal(preface, clientPreface) { - errorf("transport: http2Server.HandleStreams received bogus greeting from client: %q", preface) - t.Close() - return - } - - frame, err := t.framer.fr.ReadFrame() - if err == io.EOF || err == io.ErrUnexpectedEOF { - t.Close() - return - } - if err != nil { - errorf("transport: http2Server.HandleStreams failed to read initial settings frame: %v", err) - t.Close() - return - } - atomic.StoreUint32(&t.activity, 1) - sf, ok := frame.(*http2.SettingsFrame) - if !ok { - errorf("transport: http2Server.HandleStreams saw invalid preface type %T from client", frame) - t.Close() - return - } - t.handleSettings(sf) - for { frame, err := t.framer.fr.ReadFrame() atomic.StoreUint32(&t.activity, 1) @@ -496,7 +493,6 @@ func (t *http2Server) updateFlowControl(n uint32) { t.mu.Unlock() t.controlBuf.put(&windowUpdate{0, t.fc.newLimit(n)}) t.controlBuf.put(&settings{ - ack: false, ss: []http2.Setting{ { ID: http2.SettingInitialWindowSize, @@ -594,12 +590,29 @@ func (t *http2Server) handleSettings(f *http2.SettingsFrame) { if f.IsAck() { return } - var ss []http2.Setting + var rs []http2.Setting + var ps []http2.Setting f.ForeachSetting(func(s http2.Setting) error { - ss = append(ss, s) + if t.isRestrictive(s) { + rs = append(rs, s) + } else { + ps = append(ps, s) + } return nil }) - t.controlBuf.put(&settings{ack: true, ss: ss}) + t.applySettings(rs) + t.controlBuf.put(&settingsAck{}) + t.applySettings(ps) +} + +func (t *http2Server) isRestrictive(s http2.Setting) bool { + switch s.ID { + case http2.SettingInitialWindowSize: + // Note: we don't acquire a lock here to read streamSendQuota + // because the same goroutine updates it later. + return s.Val < t.streamSendQuota + } + return false } func (t *http2Server) applySettings(ss []http2.Setting) { @@ -666,7 +679,7 @@ func (t *http2Server) handlePing(f *http2.PingFrame) { if t.pingStrikes > maxPingStrikes { // Send goaway and close the connection. - errorf("transport: Got to too many pings from the client, closing the connection.") + errorf("transport: Got too many pings from the client, closing the connection.") t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: true}) } } @@ -708,7 +721,7 @@ func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { } md = s.header s.mu.Unlock() - // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields + // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. headerFields := make([]hpack.HeaderField, 0, 2) // at least :status, content-type will be there if none else. headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) @@ -769,7 +782,7 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { headersSent = true } - // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields + // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. headerFields := make([]hpack.HeaderField, 0, 2) // grpc-status and grpc-message will be there if none else. if !headersSent { @@ -813,7 +826,7 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { // Write converts the data into HTTP2 data frame and sends it out. Non-nil error // is returns if it fails (e.g., framing error, transport error). -func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) (err error) { +func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { select { case <-s.ctx.Done(): return ContextErr(s.ctx.Err()) @@ -842,66 +855,69 @@ func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) ( } hdr = append(hdr, data[:emptyLen]...) data = data[emptyLen:] + var ( + streamQuota int + streamQuotaVer uint32 + err error + ) for _, r := range [][]byte{hdr, data} { for len(r) > 0 { size := http2MaxFrameLen - // Wait until the stream has some quota to send the data. - quotaChan, quotaVer := s.sendQuotaPool.acquireWithVersion() - sq, err := wait(s.ctx, t.ctx, nil, nil, quotaChan) - if err != nil { - return err + if size > len(r) { + size = len(r) } - // Wait until the transport has some quota to send the data. - tq, err := wait(s.ctx, t.ctx, nil, nil, t.sendQuotaPool.acquire()) + if streamQuota == 0 { // Used up all the locally cached stream quota. + // Get all the stream quota there is. + streamQuota, streamQuotaVer, err = s.sendQuotaPool.get(math.MaxInt32, s.waiters) + if err != nil { + return err + } + } + if size > streamQuota { + size = streamQuota + } + // Get size worth quota from transport. + tq, _, err := t.sendQuotaPool.get(size, s.waiters) if err != nil { return err } - if sq < size { - size = sq - } if tq < size { size = tq } - if size > len(r) { - size = len(r) - } - p := r[:size] - ps := len(p) - if ps < tq { - // Overbooked transport quota. Return it back. - t.sendQuotaPool.add(tq - ps) - } - // Acquire local send quota to be able to write to the controlBuf. - ltq, err := wait(s.ctx, t.ctx, nil, nil, s.localSendQuota.acquire()) + ltq, _, err := t.localSendQuota.get(size, s.waiters) if err != nil { - if _, ok := err.(ConnectionError); !ok { - t.sendQuotaPool.add(ps) - } return err } - s.localSendQuota.add(ltq - ps) // It's ok we make this negative. + // even if ltq is smaller than size we don't adjust size since, + // ltq is only a soft limit. + streamQuota -= size + p := r[:size] // Reset ping strikes when sending data since this might cause // the peer to send ping. atomic.StoreUint32(&t.resetPingStrikes, 1) success := func() { + ltq := ltq t.controlBuf.put(&dataFrame{streamID: s.id, endStream: false, d: p, f: func() { - s.localSendQuota.add(ps) + t.localSendQuota.add(ltq) }}) - if ps < sq { - // Overbooked stream quota. Return it back. - s.sendQuotaPool.lockedAdd(sq - ps) - } - r = r[ps:] + r = r[size:] } - failure := func() { - s.sendQuotaPool.lockedAdd(sq) + failure := func() { // The stream quota version must have changed. + // Our streamQuota cache is invalidated now, so give it back. + s.sendQuotaPool.lockedAdd(streamQuota + size) } - if !s.sendQuotaPool.compareAndExecute(quotaVer, success, failure) { - t.sendQuotaPool.add(ps) - s.localSendQuota.add(ps) + if !s.sendQuotaPool.compareAndExecute(streamQuotaVer, success, failure) { + // Couldn't send this chunk out. + t.sendQuotaPool.add(size) + t.localSendQuota.add(ltq) + streamQuota = 0 } } } + if streamQuota > 0 { + // ADd the left over quota back to stream. + s.sendQuotaPool.add(streamQuota) + } return nil } @@ -1037,11 +1053,9 @@ func (t *http2Server) itemHandler(i item) error { case *windowUpdate: return t.framer.fr.WriteWindowUpdate(i.streamID, i.increment) case *settings: - if i.ack { - t.applySettings(i.ss) - return t.framer.fr.WriteSettingsAck() - } return t.framer.fr.WriteSettings(i.ss...) + case *settingsAck: + return t.framer.fr.WriteSettingsAck() case *resetStream: return t.framer.fr.WriteRSTStream(i.streamID, i.code) case *goAway: diff --git a/vendor/google.golang.org/grpc/transport/transport.go b/vendor/google.golang.org/grpc/transport/transport.go index bde8fa5c3..b7a5dbe42 100644 --- a/vendor/google.golang.org/grpc/transport/transport.go +++ b/vendor/google.golang.org/grpc/transport/transport.go @@ -17,11 +17,11 @@ */ // Package transport defines and implements message oriented communication -// channel to complete various transactions (e.g., an RPC). +// channel to complete various transactions (e.g., an RPC). It is meant for +// grpc-internal usage and is not intended to be imported directly by users. package transport // import "google.golang.org/grpc/transport" import ( - stdctx "context" "fmt" "io" "net" @@ -134,7 +134,7 @@ func (r *recvBufferReader) read(p []byte) (n int, err error) { case <-r.ctx.Done(): return 0, ContextErr(r.ctx.Err()) case <-r.goAway: - return 0, ErrStreamDrain + return 0, errStreamDrain case m := <-r.recv.get(): r.recv.load() if m.err != nil { @@ -211,66 +211,50 @@ const ( // Stream represents an RPC in the transport layer. type Stream struct { - id uint32 - // nil for client side Stream. - st ServerTransport - // ctx is the associated context of the stream. - ctx context.Context - // cancel is always nil for client side Stream. - cancel context.CancelFunc - // done is closed when the final status arrives. - done chan struct{} - // goAway is closed when the server sent GoAways signal before this stream was initiated. - goAway chan struct{} - // method records the associated RPC method of the stream. - method string + id uint32 + st ServerTransport // nil for client side Stream + ctx context.Context // the associated context of the stream + cancel context.CancelFunc // always nil for client side Stream + done chan struct{} // closed when the final status arrives + goAway chan struct{} // closed when a GOAWAY control message is received + method string // the associated RPC method of the stream recvCompress string sendCompress string buf *recvBuffer trReader io.Reader fc *inFlow recvQuota uint32 - - // TODO: Remote this unused variable. - // The accumulated inbound quota pending for window update. - updateQuota uint32 + waiters waiters // Callback to state application's intentions to read data. This - // is used to adjust flow control, if need be. + // is used to adjust flow control, if needed. requestRead func(int) - sendQuotaPool *quotaPool - localSendQuota *quotaPool - // Close headerChan to indicate the end of reception of header metadata. - headerChan chan struct{} - // header caches the received header metadata. - header metadata.MD - // The key-value map of trailer metadata. - trailer metadata.MD - - mu sync.RWMutex // guard the following - // headerOK becomes true from the first header is about to send. - headerOk bool + sendQuotaPool *quotaPool + headerChan chan struct{} // closed to indicate the end of header metadata. + headerDone bool // set when headerChan is closed. Used to avoid closing headerChan multiple times. + header metadata.MD // the received header metadata. + trailer metadata.MD // the key-value map of trailer metadata. + + mu sync.RWMutex // guard the following + headerOk bool // becomes true from the first header is about to send state streamState - // true iff headerChan is closed. Used to avoid closing headerChan - // multiple times. - headerDone bool - // the status error received from the server. - status *status.Status - // rstStream indicates whether a RST_STREAM frame needs to be sent - // to the server to signify that this stream is closing. - rstStream bool - // rstError is the error that needs to be sent along with the RST_STREAM frame. - rstError http2.ErrCode - // bytesSent and bytesReceived indicates whether any bytes have been sent or - // received on this stream. - bytesSent bool - bytesReceived bool + + status *status.Status // the status error received from the server + + rstStream bool // indicates whether a RST_STREAM frame needs to be sent + rstError http2.ErrCode // the error that needs to be sent along with the RST_STREAM frame + + bytesReceived bool // indicates whether any bytes have been received on this stream + unprocessed bool // set if the server sends a refused stream or GOAWAY including this stream } // RecvCompress returns the compression algorithm applied to the inbound // message. It is empty string if there is no compression applied. func (s *Stream) RecvCompress() string { + if s.headerChan != nil { + <-s.headerChan + } return s.recvCompress } @@ -300,7 +284,7 @@ func (s *Stream) Header() (metadata.MD, error) { case <-s.ctx.Done(): err = ContextErr(s.ctx.Err()) case <-s.goAway: - err = ErrStreamDrain + err = errStreamDrain case <-s.headerChan: return s.header.Copy(), nil } @@ -417,18 +401,19 @@ func (s *Stream) finish(st *status.Status) { close(s.done) } -// BytesSent indicates whether any bytes have been sent on this stream. -func (s *Stream) BytesSent() bool { +// BytesReceived indicates whether any bytes have been received on this stream. +func (s *Stream) BytesReceived() bool { s.mu.Lock() - bs := s.bytesSent + br := s.bytesReceived s.mu.Unlock() - return bs + return br } -// BytesReceived indicates whether any bytes have been received on this stream. -func (s *Stream) BytesReceived() bool { +// Unprocessed indicates whether the server did not process this stream -- +// i.e. it sent a refused stream or GOAWAY including this stream ID. +func (s *Stream) Unprocessed() bool { s.mu.Lock() - br := s.bytesReceived + br := s.unprocessed s.mu.Unlock() return br } @@ -514,8 +499,9 @@ type ConnectOptions struct { // TargetInfo contains the information of the target such as network address and metadata. type TargetInfo struct { - Addr string - Metadata interface{} + Addr string + Metadata interface{} + Authority string } // NewClientTransport establishes the transport with the required ConnectOptions @@ -545,10 +531,6 @@ type CallHdr struct { // Method specifies the operation to perform. Method string - // RecvCompress specifies the compression algorithm applied on - // inbound messages. - RecvCompress string - // SendCompress specifies the compression algorithm applied on // outbound message. SendCompress string @@ -686,9 +668,13 @@ func (e ConnectionError) Origin() error { var ( // ErrConnClosing indicates that the transport is closing. ErrConnClosing = connectionErrorf(true, nil, "transport is closing") - // ErrStreamDrain indicates that the stream is rejected by the server because + // errStreamDrain indicates that the stream is rejected by the server because // the server stops accepting new RPCs. - ErrStreamDrain = streamErrorf(codes.Unavailable, "the server stops accepting new RPCs") + // TODO: delete this error; it is no longer necessary. + errStreamDrain = streamErrorf(codes.Unavailable, "the server stops accepting new RPCs") + // StatusGoAway indicates that the server sent a GOAWAY that included this + // stream's ID in unprocessed RPCs. + statusGoAway = status.New(codes.Unavailable, "the server stopped accepting new RPCs") ) // TODO: See if we can replace StreamError with status package errors. @@ -703,44 +689,27 @@ func (e StreamError) Error() string { return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc) } -// wait blocks until it can receive from one of the provided contexts or channels -func wait(ctx, tctx context.Context, done, goAway <-chan struct{}, proceed <-chan int) (int, error) { - select { - case <-ctx.Done(): - return 0, ContextErr(ctx.Err()) - case <-done: - return 0, io.EOF - case <-goAway: - return 0, ErrStreamDrain - case <-tctx.Done(): - return 0, ErrConnClosing - case i := <-proceed: - return i, nil - } -} - -// ContextErr converts the error from context package into a StreamError. -func ContextErr(err error) StreamError { - switch err { - case context.DeadlineExceeded, stdctx.DeadlineExceeded: - return streamErrorf(codes.DeadlineExceeded, "%v", err) - case context.Canceled, stdctx.Canceled: - return streamErrorf(codes.Canceled, "%v", err) - } - return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) +// waiters are passed to quotaPool get methods to +// wait on in addition to waiting on quota. +type waiters struct { + ctx context.Context + tctx context.Context + done chan struct{} + goAway chan struct{} } // GoAwayReason contains the reason for the GoAway frame received. type GoAwayReason uint8 const ( - // Invalid indicates that no GoAway frame is received. - Invalid GoAwayReason = 0 - // NoReason is the default value when GoAway frame is received. - NoReason GoAwayReason = 1 - // TooManyPings indicates that a GoAway frame with ErrCodeEnhanceYourCalm - // was received and that the debug data said "too_many_pings". - TooManyPings GoAwayReason = 2 + // GoAwayInvalid indicates that no GoAway frame is received. + GoAwayInvalid GoAwayReason = 0 + // GoAwayNoReason is the default value when GoAway frame is received. + GoAwayNoReason GoAwayReason = 1 + // GoAwayTooManyPings indicates that a GoAway frame with + // ErrCodeEnhanceYourCalm was received and that the debug data said + // "too_many_pings". + GoAwayTooManyPings GoAwayReason = 2 ) // loopyWriter is run in a separate go routine. It is the single code path that will @@ -751,6 +720,7 @@ func loopyWriter(ctx context.Context, cbuf *controlBuffer, handler func(item) er case i := <-cbuf.get(): cbuf.load() if err := handler(i); err != nil { + errorf("transport: Error while handling item. Err: %v", err) return } case <-ctx.Done(): @@ -762,12 +732,14 @@ func loopyWriter(ctx context.Context, cbuf *controlBuffer, handler func(item) er case i := <-cbuf.get(): cbuf.load() if err := handler(i); err != nil { + errorf("transport: Error while handling item. Err: %v", err) return } case <-ctx.Done(): return default: if err := handler(&flushIO{}); err != nil { + errorf("transport: Error while flushing. Err: %v", err) return } break hasData diff --git a/vendor/google.golang.org/grpc/transport/transport_test.go b/vendor/google.golang.org/grpc/transport/transport_test.go index e1dd080a1..3e29c9179 100644 --- a/vendor/google.golang.org/grpc/transport/transport_test.go +++ b/vendor/google.golang.org/grpc/transport/transport_test.go @@ -115,8 +115,12 @@ func (h *testStreamHandler) handleStream(t *testing.T, s *Stream) { func (h *testStreamHandler) handleStreamPingPong(t *testing.T, s *Stream) { header := make([]byte, 5) - for i := 0; i < 10; i++ { + for { if _, err := s.Read(header); err != nil { + if err == io.EOF { + h.t.WriteStatus(s, status.New(codes.OK, "")) + return + } t.Fatalf("Error on server while reading data header: %v", err) } sz := binary.BigEndian.Uint32(header[1:]) @@ -529,8 +533,18 @@ func TestKeepaliveServer(t *testing.T) { t.Fatalf("Failed to dial: %v", err) } defer client.Close() + // Set read deadline on client conn so that it doesn't block forever in errorsome cases. - client.SetReadDeadline(time.Now().Add(10 * time.Second)) + client.SetDeadline(time.Now().Add(10 * time.Second)) + + if n, err := client.Write(clientPreface); err != nil || n != len(clientPreface) { + t.Fatalf("Error writing client preface; n=%v, err=%v", n, err) + } + framer := newFramer(client, defaultWriteBufSize, defaultReadBufSize) + if err := framer.fr.WriteSettings(http2.Setting{}); err != nil { + t.Fatal("Error writing settings frame:", err) + } + framer.writer.Flush() // Wait for keepalive logic to close the connection. time.Sleep(4 * time.Second) b := make([]byte, 24) @@ -1005,8 +1019,8 @@ func TestGracefulClose(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - if _, err := ct.NewStream(context.Background(), callHdr); err != ErrStreamDrain { - t.Errorf("%v.NewStream(_, _) = _, %v, want _, %v", ct, err, ErrStreamDrain) + if _, err := ct.NewStream(context.Background(), callHdr); err != errStreamDrain { + t.Errorf("%v.NewStream(_, _) = _, %v, want _, %v", ct, err, errStreamDrain) } }() } @@ -1089,43 +1103,29 @@ func TestMaxStreams(t *testing.T) { } } }() + // Test these conditions until they pass or + // we reach the deadline (failure case). for { select { case <-ch: case <-done: - t.Fatalf("Client has not received the max stream setting in 5 seconds.") + t.Fatalf("streamsQuota.quota shouldn't be non-zero.") } - cc.mu.Lock() - // cc.maxStreams should be equal to 1 after having received settings frame from - // server. - if cc.maxStreams == 1 { - cc.mu.Unlock() - select { - case <-cc.streamsQuota.acquire(): - t.Fatalf("streamsQuota.acquire() becomes readable mistakenly.") - default: - cc.streamsQuota.mu.Lock() - quota := cc.streamsQuota.quota - cc.streamsQuota.mu.Unlock() - if quota != 0 { - t.Fatalf("streamsQuota.quota got non-zero quota mistakenly.") - } - } + cc.streamsQuota.mu.Lock() + sq := cc.streamsQuota.quota + cc.streamsQuota.mu.Unlock() + if sq == 0 { break } - cc.mu.Unlock() } close(ready) // Close the pending stream so that the streams quota becomes available for the next new stream. ct.CloseStream(s, nil) - select { - case i := <-cc.streamsQuota.acquire(): - if i != 1 { - t.Fatalf("streamsQuota.acquire() got %d quota, want 1.", i) - } - cc.streamsQuota.add(i) - default: - t.Fatalf("streamsQuota.acquire() is not readable.") + cc.streamsQuota.mu.Lock() + i := cc.streamsQuota.quota + cc.streamsQuota.mu.Unlock() + if i != 1 { + t.Fatalf("streamsQuota is %d, want 1.", i) } if _, err := ct.NewStream(context.Background(), callHdr); err != nil { t.Fatalf("Failed to open stream: %v", err) @@ -1680,7 +1680,12 @@ func testAccountCheckWindowSize(t *testing.T, wc windowSizeConfig) { }) ctx, cancel := context.WithTimeout(context.Background(), time.Second) - serverSendQuota, err := wait(ctx, context.Background(), nil, nil, st.sendQuotaPool.acquire()) + serverSendQuota, _, err := st.sendQuotaPool.get(math.MaxInt32, waiters{ + ctx: ctx, + tctx: st.ctx, + done: nil, + goAway: nil, + }) if err != nil { t.Fatalf("Error while acquiring sendQuota on server. Err: %v", err) } @@ -1702,7 +1707,12 @@ func testAccountCheckWindowSize(t *testing.T, wc windowSizeConfig) { t.Fatalf("Client transport flow control window size is %v, want %v", limit, connectOptions.InitialConnWindowSize) } ctx, cancel = context.WithTimeout(context.Background(), time.Second) - clientSendQuota, err := wait(ctx, context.Background(), nil, nil, ct.sendQuotaPool.acquire()) + clientSendQuota, _, err := ct.sendQuotaPool.get(math.MaxInt32, waiters{ + ctx: ctx, + tctx: ct.ctx, + done: nil, + goAway: nil, + }) if err != nil { t.Fatalf("Error while acquiring sendQuota on client. Err: %v", err) } @@ -1786,6 +1796,12 @@ func TestAccountCheckExpandingWindow(t *testing.T) { t.Fatalf("Length of message received by client: %v, want: %v", len(recvMsg), len(msg)) } } + defer func() { + ct.Write(cstream, nil, nil, &Options{Last: true}) // Close the stream. + if _, err := cstream.Read(header); err != io.EOF { + t.Fatalf("Client expected an EOF from the server. Got: %v", err) + } + }() var sstream *Stream st.mu.Lock() for _, v := range st.activeStreams { @@ -1838,7 +1854,12 @@ func TestAccountCheckExpandingWindow(t *testing.T) { // Check flow conrtrol window on client stream is equal to out flow on server stream. ctx, cancel := context.WithTimeout(context.Background(), time.Second) - serverStreamSendQuota, err := wait(ctx, context.Background(), nil, nil, sstream.sendQuotaPool.acquire()) + serverStreamSendQuota, _, err := sstream.sendQuotaPool.get(math.MaxInt32, waiters{ + ctx: ctx, + tctx: context.Background(), + done: nil, + goAway: nil, + }) cancel() if err != nil { return true, fmt.Errorf("error while acquiring server stream send quota. Err: %v", err) @@ -1853,7 +1874,12 @@ func TestAccountCheckExpandingWindow(t *testing.T) { // Check flow control window on server stream is equal to out flow on client stream. ctx, cancel = context.WithTimeout(context.Background(), time.Second) - clientStreamSendQuota, err := wait(ctx, context.Background(), nil, nil, cstream.sendQuotaPool.acquire()) + clientStreamSendQuota, _, err := cstream.sendQuotaPool.get(math.MaxInt32, waiters{ + ctx: ctx, + tctx: context.Background(), + done: nil, + goAway: nil, + }) cancel() if err != nil { return true, fmt.Errorf("error while acquiring client stream send quota. Err: %v", err) @@ -1868,7 +1894,12 @@ func TestAccountCheckExpandingWindow(t *testing.T) { // Check flow control window on client transport is equal to out flow of server transport. ctx, cancel = context.WithTimeout(context.Background(), time.Second) - serverTrSendQuota, err := wait(ctx, context.Background(), nil, nil, st.sendQuotaPool.acquire()) + serverTrSendQuota, _, err := st.sendQuotaPool.get(math.MaxInt32, waiters{ + ctx: ctx, + tctx: st.ctx, + done: nil, + goAway: nil, + }) cancel() if err != nil { return true, fmt.Errorf("error while acquring server transport send quota. Err: %v", err) @@ -1883,7 +1914,12 @@ func TestAccountCheckExpandingWindow(t *testing.T) { // Check flow control window on server transport is equal to out flow of client transport. ctx, cancel = context.WithTimeout(context.Background(), time.Second) - clientTrSendQuota, err := wait(ctx, context.Background(), nil, nil, ct.sendQuotaPool.acquire()) + clientTrSendQuota, _, err := ct.sendQuotaPool.get(math.MaxInt32, waiters{ + ctx: ctx, + tctx: ct.ctx, + done: nil, + goAway: nil, + }) cancel() if err != nil { return true, fmt.Errorf("error while acquiring client transport send quota. Err: %v", err) @@ -2156,3 +2192,73 @@ func TestReadGivesSameErrorAfterAnyErrorOccurs(t *testing.T) { } } } + +func TestPingPong1B(t *testing.T) { + runPingPongTest(t, 1) +} + +func TestPingPong1KB(t *testing.T) { + runPingPongTest(t, 1024) +} + +func TestPingPong64KB(t *testing.T) { + runPingPongTest(t, 65536) +} + +func TestPingPong1MB(t *testing.T) { + runPingPongTest(t, 1048576) +} + +//This is a stress-test of flow control logic. +func runPingPongTest(t *testing.T, msgSize int) { + server, client := setUp(t, 0, 0, pingpong) + defer server.stop() + defer client.Close() + waitWhileTrue(t, func() (bool, error) { + server.mu.Lock() + defer server.mu.Unlock() + if len(server.conns) == 0 { + return true, fmt.Errorf("timed out while waiting for server transport to be created") + } + return false, nil + }) + ct := client.(*http2Client) + stream, err := client.NewStream(context.Background(), &CallHdr{}) + if err != nil { + t.Fatalf("Failed to create stream. Err: %v", err) + } + msg := make([]byte, msgSize) + outgoingHeader := make([]byte, 5) + outgoingHeader[0] = byte(0) + binary.BigEndian.PutUint32(outgoingHeader[1:], uint32(msgSize)) + opts := &Options{} + incomingHeader := make([]byte, 5) + done := make(chan struct{}) + go func() { + timer := time.NewTimer(time.Second * 5) + <-timer.C + close(done) + }() + for { + select { + case <-done: + ct.Write(stream, nil, nil, &Options{Last: true}) + if _, err := stream.Read(incomingHeader); err != io.EOF { + t.Fatalf("Client expected EOF from the server. Got: %v", err) + } + return + default: + if err := ct.Write(stream, outgoingHeader, msg, opts); err != nil { + t.Fatalf("Error on client while writing message. Err: %v", err) + } + if _, err := stream.Read(incomingHeader); err != nil { + t.Fatalf("Error on client while reading data header. Err: %v", err) + } + sz := binary.BigEndian.Uint32(incomingHeader[1:]) + recvMsg := make([]byte, int(sz)) + if _, err := stream.Read(recvMsg); err != nil { + t.Fatalf("Error on client while reading data. Err: %v", err) + } + } + } +} diff --git a/vendor/google.golang.org/grpc/vet.sh b/vendor/google.golang.org/grpc/vet.sh index 72ef3290a..02d4bae39 100755 --- a/vendor/google.golang.org/grpc/vet.sh +++ b/vendor/google.golang.org/grpc/vet.sh @@ -8,12 +8,6 @@ die() { exit 1 } -# TODO: Remove this check and the mangling below once "context" is imported -# directly. -if git status --porcelain | read; then - die "Uncommitted or untracked files found; commit changes first" -fi - PATH="$GOPATH/bin:$GOROOT/bin:$PATH" # Check proto in manual runs or cron runs. @@ -28,6 +22,7 @@ if [ "$1" = "-install" ]; then github.com/golang/lint/golint \ golang.org/x/tools/cmd/goimports \ honnef.co/go/tools/cmd/staticcheck \ + github.com/client9/misspell/cmd/misspell \ github.com/golang/protobuf/protoc-gen-go \ golang.org/x/tools/cmd/stringer if [[ "$check_proto" = "true" ]]; then @@ -48,6 +43,12 @@ elif [[ "$#" -ne 0 ]]; then die "Unknown argument(s): $*" fi +# TODO: Remove this check and the mangling below once "context" is imported +# directly. +if git status --porcelain | read; then + die "Uncommitted or untracked files found; commit changes first" +fi + git ls-files "*.go" | xargs grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" 2>&1 | tee /dev/stderr | (! read) gofmt -s -d -l . 2>&1 | tee /dev/stderr | (! read) goimports -l . 2>&1 | tee /dev/stderr | (! read) @@ -75,4 +76,10 @@ if [[ "$check_proto" = "true" ]]; then fi # TODO(menghanl): fix errors in transport_test. -staticcheck -ignore google.golang.org/grpc/transport/transport_test.go:SA2002 ./... +staticcheck -ignore ' +google.golang.org/grpc/transport/transport_test.go:SA2002 +google.golang.org/grpc/benchmark/benchmain/main.go:SA1019 +google.golang.org/grpc/stats/stats_test.go:SA1019 +google.golang.org/grpc/test/end2end_test.go:SA1019 +' ./... +misspell -error . |