github.com/stackdocker/rkt@v0.10.1-0.20151109095037-1aa827478248/Godeps/_workspace/src/google.golang.org/grpc/interop/client/client.go (about)

     1  /*
     2   *
     3   * Copyright 2014, Google Inc.
     4   * All rights reserved.
     5   *
     6   * Redistribution and use in source and binary forms, with or without
     7   * modification, are permitted provided that the following conditions are
     8   * met:
     9   *
    10   *     * Redistributions of source code must retain the above copyright
    11   * notice, this list of conditions and the following disclaimer.
    12   *     * Redistributions in binary form must reproduce the above
    13   * copyright notice, this list of conditions and the following disclaimer
    14   * in the documentation and/or other materials provided with the
    15   * distribution.
    16   *     * Neither the name of Google Inc. nor the names of its
    17   * contributors may be used to endorse or promote products derived from
    18   * this software without specific prior written permission.
    19   *
    20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    21   * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    22   * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    23   * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    24   * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    25   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    26   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    27   * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    28   * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    29   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    30   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    31   *
    32   */
    33  
    34  package main
    35  
    36  import (
    37  	"flag"
    38  	"io"
    39  	"io/ioutil"
    40  	"net"
    41  	"strconv"
    42  	"strings"
    43  	"time"
    44  
    45  	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/golang/protobuf/proto"
    46  	"github.com/coreos/rkt/Godeps/_workspace/src/golang.org/x/net/context"
    47  	"github.com/coreos/rkt/Godeps/_workspace/src/google.golang.org/grpc"
    48  	"github.com/coreos/rkt/Godeps/_workspace/src/google.golang.org/grpc/codes"
    49  	"github.com/coreos/rkt/Godeps/_workspace/src/google.golang.org/grpc/credentials"
    50  	"github.com/coreos/rkt/Godeps/_workspace/src/google.golang.org/grpc/credentials/oauth"
    51  	"github.com/coreos/rkt/Godeps/_workspace/src/google.golang.org/grpc/grpclog"
    52  	testpb "github.com/coreos/rkt/Godeps/_workspace/src/google.golang.org/grpc/interop/grpc_testing"
    53  	"github.com/coreos/rkt/Godeps/_workspace/src/google.golang.org/grpc/metadata"
    54  	"golang.org/x/oauth2"
    55  	"golang.org/x/oauth2/google"
    56  )
    57  
    58  var (
    59  	useTLS                = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP")
    60  	caFile                = flag.String("tls_ca_file", "testdata/ca.pem", "The file containning the CA root cert file")
    61  	serviceAccountKeyFile = flag.String("service_account_key_file", "", "Path to service account json key file")
    62  	oauthScope            = flag.String("oauth_scope", "", "The scope for OAuth2 tokens")
    63  	defaultServiceAccount = flag.String("default_service_account", "", "Email of GCE default service account")
    64  	serverHost            = flag.String("server_host", "127.0.0.1", "The server host name")
    65  	serverPort            = flag.Int("server_port", 10000, "The server port number")
    66  	tlsServerName         = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.")
    67  	testCase              = flag.String("test_case", "large_unary",
    68  		`Configure different test cases. Valid options are:
    69          empty_unary : empty (zero bytes) request and response;
    70          large_unary : single request and (large) response;
    71          client_streaming : request streaming with single response;
    72          server_streaming : single request with response streaming;
    73          ping_pong : full-duplex streaming;
    74          empty_stream : full-duplex streaming with zero message;
    75          timeout_on_sleeping_server: fullduplex streaming;
    76          compute_engine_creds: large_unary with compute engine auth;
    77          service_account_creds: large_unary with service account auth;
    78          jwt_token_creds: large_unary with jwt token auth;
    79          per_rpc_creds: large_unary with per rpc token;
    80          oauth2_auth_token: large_unary with oauth2 token auth;
    81          cancel_after_begin: cancellation after metadata has been sent but before payloads are sent;
    82          cancel_after_first_response: cancellation after receiving 1st message from the server.`)
    83  )
    84  
    85  var (
    86  	reqSizes      = []int{27182, 8, 1828, 45904}
    87  	respSizes     = []int{31415, 9, 2653, 58979}
    88  	largeReqSize  = 271828
    89  	largeRespSize = 314159
    90  )
    91  
    92  func newPayload(t testpb.PayloadType, size int) *testpb.Payload {
    93  	if size < 0 {
    94  		grpclog.Fatalf("Requested a response with invalid length %d", size)
    95  	}
    96  	body := make([]byte, size)
    97  	switch t {
    98  	case testpb.PayloadType_COMPRESSABLE:
    99  	case testpb.PayloadType_UNCOMPRESSABLE:
   100  		grpclog.Fatalf("PayloadType UNCOMPRESSABLE is not supported")
   101  	default:
   102  		grpclog.Fatalf("Unsupported payload type: %d", t)
   103  	}
   104  	return &testpb.Payload{
   105  		Type: t.Enum(),
   106  		Body: body,
   107  	}
   108  }
   109  
   110  func doEmptyUnaryCall(tc testpb.TestServiceClient) {
   111  	reply, err := tc.EmptyCall(context.Background(), &testpb.Empty{})
   112  	if err != nil {
   113  		grpclog.Fatal("/TestService/EmptyCall RPC failed: ", err)
   114  	}
   115  	if !proto.Equal(&testpb.Empty{}, reply) {
   116  		grpclog.Fatalf("/TestService/EmptyCall receives %v, want %v", reply, testpb.Empty{})
   117  	}
   118  	grpclog.Println("EmptyUnaryCall done")
   119  }
   120  
   121  func doLargeUnaryCall(tc testpb.TestServiceClient) {
   122  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
   123  	req := &testpb.SimpleRequest{
   124  		ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
   125  		ResponseSize: proto.Int32(int32(largeRespSize)),
   126  		Payload:      pl,
   127  	}
   128  	reply, err := tc.UnaryCall(context.Background(), req)
   129  	if err != nil {
   130  		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
   131  	}
   132  	t := reply.GetPayload().GetType()
   133  	s := len(reply.GetPayload().GetBody())
   134  	if t != testpb.PayloadType_COMPRESSABLE || s != largeRespSize {
   135  		grpclog.Fatalf("Got the reply with type %d len %d; want %d, %d", t, s, testpb.PayloadType_COMPRESSABLE, largeRespSize)
   136  	}
   137  	grpclog.Println("LargeUnaryCall done")
   138  }
   139  
   140  func doClientStreaming(tc testpb.TestServiceClient) {
   141  	stream, err := tc.StreamingInputCall(context.Background())
   142  	if err != nil {
   143  		grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err)
   144  	}
   145  	var sum int
   146  	for _, s := range reqSizes {
   147  		pl := newPayload(testpb.PayloadType_COMPRESSABLE, s)
   148  		req := &testpb.StreamingInputCallRequest{
   149  			Payload: pl,
   150  		}
   151  		if err := stream.Send(req); err != nil {
   152  			grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
   153  		}
   154  		sum += s
   155  		grpclog.Printf("Sent a request of size %d, aggregated size %d", s, sum)
   156  
   157  	}
   158  	reply, err := stream.CloseAndRecv()
   159  	if err != nil {
   160  		grpclog.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil)
   161  	}
   162  	if reply.GetAggregatedPayloadSize() != int32(sum) {
   163  		grpclog.Fatalf("%v.CloseAndRecv().GetAggregatePayloadSize() = %v; want %v", stream, reply.GetAggregatedPayloadSize(), sum)
   164  	}
   165  	grpclog.Println("ClientStreaming done")
   166  }
   167  
   168  func doServerStreaming(tc testpb.TestServiceClient) {
   169  	respParam := make([]*testpb.ResponseParameters, len(respSizes))
   170  	for i, s := range respSizes {
   171  		respParam[i] = &testpb.ResponseParameters{
   172  			Size: proto.Int32(int32(s)),
   173  		}
   174  	}
   175  	req := &testpb.StreamingOutputCallRequest{
   176  		ResponseType:       testpb.PayloadType_COMPRESSABLE.Enum(),
   177  		ResponseParameters: respParam,
   178  	}
   179  	stream, err := tc.StreamingOutputCall(context.Background(), req)
   180  	if err != nil {
   181  		grpclog.Fatalf("%v.StreamingOutputCall(_) = _, %v", tc, err)
   182  	}
   183  	var rpcStatus error
   184  	var respCnt int
   185  	var index int
   186  	for {
   187  		reply, err := stream.Recv()
   188  		if err != nil {
   189  			rpcStatus = err
   190  			break
   191  		}
   192  		t := reply.GetPayload().GetType()
   193  		if t != testpb.PayloadType_COMPRESSABLE {
   194  			grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE)
   195  		}
   196  		size := len(reply.GetPayload().GetBody())
   197  		if size != int(respSizes[index]) {
   198  			grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index])
   199  		}
   200  		index++
   201  		respCnt++
   202  	}
   203  	if rpcStatus != io.EOF {
   204  		grpclog.Fatalf("Failed to finish the server streaming rpc: %v", err)
   205  	}
   206  	if respCnt != len(respSizes) {
   207  		grpclog.Fatalf("Got %d reply, want %d", len(respSizes), respCnt)
   208  	}
   209  	grpclog.Println("ServerStreaming done")
   210  }
   211  
   212  func doPingPong(tc testpb.TestServiceClient) {
   213  	stream, err := tc.FullDuplexCall(context.Background())
   214  	if err != nil {
   215  		grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
   216  	}
   217  	var index int
   218  	for index < len(reqSizes) {
   219  		respParam := []*testpb.ResponseParameters{
   220  			{
   221  				Size: proto.Int32(int32(respSizes[index])),
   222  			},
   223  		}
   224  		pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSizes[index])
   225  		req := &testpb.StreamingOutputCallRequest{
   226  			ResponseType:       testpb.PayloadType_COMPRESSABLE.Enum(),
   227  			ResponseParameters: respParam,
   228  			Payload:            pl,
   229  		}
   230  		if err := stream.Send(req); err != nil {
   231  			grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
   232  		}
   233  		reply, err := stream.Recv()
   234  		if err != nil {
   235  			grpclog.Fatalf("%v.Recv() = %v", stream, err)
   236  		}
   237  		t := reply.GetPayload().GetType()
   238  		if t != testpb.PayloadType_COMPRESSABLE {
   239  			grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE)
   240  		}
   241  		size := len(reply.GetPayload().GetBody())
   242  		if size != int(respSizes[index]) {
   243  			grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index])
   244  		}
   245  		index++
   246  	}
   247  	if err := stream.CloseSend(); err != nil {
   248  		grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
   249  	}
   250  	if _, err := stream.Recv(); err != io.EOF {
   251  		grpclog.Fatalf("%v failed to complele the ping pong test: %v", stream, err)
   252  	}
   253  	grpclog.Println("Pingpong done")
   254  }
   255  
   256  func doEmptyStream(tc testpb.TestServiceClient) {
   257  	stream, err := tc.FullDuplexCall(context.Background())
   258  	if err != nil {
   259  		grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
   260  	}
   261  	if err := stream.CloseSend(); err != nil {
   262  		grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil)
   263  	}
   264  	if _, err := stream.Recv(); err != io.EOF {
   265  		grpclog.Fatalf("%v failed to complete the empty stream test: %v", stream, err)
   266  	}
   267  	grpclog.Println("Emptystream done")
   268  }
   269  
   270  func doTimeoutOnSleepingServer(tc testpb.TestServiceClient) {
   271  	ctx, _ := context.WithTimeout(context.Background(), 1*time.Millisecond)
   272  	stream, err := tc.FullDuplexCall(ctx)
   273  	if err != nil {
   274  		if grpc.Code(err) == codes.DeadlineExceeded {
   275  			grpclog.Println("TimeoutOnSleepingServer done")
   276  			return
   277  		}
   278  		grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
   279  	}
   280  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, 27182)
   281  	req := &testpb.StreamingOutputCallRequest{
   282  		ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
   283  		Payload:      pl,
   284  	}
   285  	if err := stream.Send(req); err != nil {
   286  		grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
   287  	}
   288  	if _, err := stream.Recv(); grpc.Code(err) != codes.DeadlineExceeded {
   289  		grpclog.Fatalf("%v.Recv() = _, %v, want error code %d", stream, err, codes.DeadlineExceeded)
   290  	}
   291  	grpclog.Println("TimeoutOnSleepingServer done")
   292  }
   293  
   294  func doComputeEngineCreds(tc testpb.TestServiceClient) {
   295  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
   296  	req := &testpb.SimpleRequest{
   297  		ResponseType:   testpb.PayloadType_COMPRESSABLE.Enum(),
   298  		ResponseSize:   proto.Int32(int32(largeRespSize)),
   299  		Payload:        pl,
   300  		FillUsername:   proto.Bool(true),
   301  		FillOauthScope: proto.Bool(true),
   302  	}
   303  	reply, err := tc.UnaryCall(context.Background(), req)
   304  	if err != nil {
   305  		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
   306  	}
   307  	user := reply.GetUsername()
   308  	scope := reply.GetOauthScope()
   309  	if user != *defaultServiceAccount {
   310  		grpclog.Fatalf("Got user name %q, want %q.", user, *defaultServiceAccount)
   311  	}
   312  	if !strings.Contains(*oauthScope, scope) {
   313  		grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
   314  	}
   315  	grpclog.Println("ComputeEngineCreds done")
   316  }
   317  
   318  func getServiceAccountJSONKey() []byte {
   319  	jsonKey, err := ioutil.ReadFile(*serviceAccountKeyFile)
   320  	if err != nil {
   321  		grpclog.Fatalf("Failed to read the service account key file: %v", err)
   322  	}
   323  	return jsonKey
   324  }
   325  
   326  func doServiceAccountCreds(tc testpb.TestServiceClient) {
   327  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
   328  	req := &testpb.SimpleRequest{
   329  		ResponseType:   testpb.PayloadType_COMPRESSABLE.Enum(),
   330  		ResponseSize:   proto.Int32(int32(largeRespSize)),
   331  		Payload:        pl,
   332  		FillUsername:   proto.Bool(true),
   333  		FillOauthScope: proto.Bool(true),
   334  	}
   335  	reply, err := tc.UnaryCall(context.Background(), req)
   336  	if err != nil {
   337  		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
   338  	}
   339  	jsonKey := getServiceAccountJSONKey()
   340  	user := reply.GetUsername()
   341  	scope := reply.GetOauthScope()
   342  	if !strings.Contains(string(jsonKey), user) {
   343  		grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
   344  	}
   345  	if !strings.Contains(*oauthScope, scope) {
   346  		grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
   347  	}
   348  	grpclog.Println("ServiceAccountCreds done")
   349  }
   350  
   351  func doJWTTokenCreds(tc testpb.TestServiceClient) {
   352  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
   353  	req := &testpb.SimpleRequest{
   354  		ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
   355  		ResponseSize: proto.Int32(int32(largeRespSize)),
   356  		Payload:      pl,
   357  		FillUsername: proto.Bool(true),
   358  	}
   359  	reply, err := tc.UnaryCall(context.Background(), req)
   360  	if err != nil {
   361  		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
   362  	}
   363  	jsonKey := getServiceAccountJSONKey()
   364  	user := reply.GetUsername()
   365  	if !strings.Contains(string(jsonKey), user) {
   366  		grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
   367  	}
   368  	grpclog.Println("JWTtokenCreds done")
   369  }
   370  
   371  func getToken() *oauth2.Token {
   372  	jsonKey := getServiceAccountJSONKey()
   373  	config, err := google.JWTConfigFromJSON(jsonKey, *oauthScope)
   374  	if err != nil {
   375  		grpclog.Fatalf("Failed to get the config: %v", err)
   376  	}
   377  	token, err := config.TokenSource(context.Background()).Token()
   378  	if err != nil {
   379  		grpclog.Fatalf("Failed to get the token: %v", err)
   380  	}
   381  	return token
   382  }
   383  
   384  func doOauth2TokenCreds(tc testpb.TestServiceClient) {
   385  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
   386  	req := &testpb.SimpleRequest{
   387  		ResponseType:   testpb.PayloadType_COMPRESSABLE.Enum(),
   388  		ResponseSize:   proto.Int32(int32(largeRespSize)),
   389  		Payload:        pl,
   390  		FillUsername:   proto.Bool(true),
   391  		FillOauthScope: proto.Bool(true),
   392  	}
   393  	reply, err := tc.UnaryCall(context.Background(), req)
   394  	if err != nil {
   395  		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
   396  	}
   397  	jsonKey := getServiceAccountJSONKey()
   398  	user := reply.GetUsername()
   399  	scope := reply.GetOauthScope()
   400  	if !strings.Contains(string(jsonKey), user) {
   401  		grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
   402  	}
   403  	if !strings.Contains(*oauthScope, scope) {
   404  		grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
   405  	}
   406  	grpclog.Println("Oauth2TokenCreds done")
   407  }
   408  
   409  func doPerRPCCreds(tc testpb.TestServiceClient) {
   410  	jsonKey := getServiceAccountJSONKey()
   411  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize)
   412  	req := &testpb.SimpleRequest{
   413  		ResponseType:   testpb.PayloadType_COMPRESSABLE.Enum(),
   414  		ResponseSize:   proto.Int32(int32(largeRespSize)),
   415  		Payload:        pl,
   416  		FillUsername:   proto.Bool(true),
   417  		FillOauthScope: proto.Bool(true),
   418  	}
   419  	token := getToken()
   420  	kv := map[string]string{"authorization": token.TokenType + " " + token.AccessToken}
   421  	ctx := metadata.NewContext(context.Background(), metadata.MD{"authorization": []string{kv["authorization"]}})
   422  	reply, err := tc.UnaryCall(ctx, req)
   423  	if err != nil {
   424  		grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err)
   425  	}
   426  	user := reply.GetUsername()
   427  	scope := reply.GetOauthScope()
   428  	if !strings.Contains(string(jsonKey), user) {
   429  		grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey)
   430  	}
   431  	if !strings.Contains(*oauthScope, scope) {
   432  		grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, *oauthScope)
   433  	}
   434  	grpclog.Println("PerRPCCreds done")
   435  }
   436  
   437  var (
   438  	testMetadata = metadata.MD{
   439  		"key1": []string{"value1"},
   440  		"key2": []string{"value2"},
   441  	}
   442  )
   443  
   444  func doCancelAfterBegin(tc testpb.TestServiceClient) {
   445  	ctx, cancel := context.WithCancel(metadata.NewContext(context.Background(), testMetadata))
   446  	stream, err := tc.StreamingInputCall(ctx)
   447  	if err != nil {
   448  		grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err)
   449  	}
   450  	cancel()
   451  	_, err = stream.CloseAndRecv()
   452  	if grpc.Code(err) != codes.Canceled {
   453  		grpclog.Fatalf("%v.CloseAndRecv() got error code %d, want %d", stream, grpc.Code(err), codes.Canceled)
   454  	}
   455  	grpclog.Println("CancelAfterBegin done")
   456  }
   457  
   458  func doCancelAfterFirstResponse(tc testpb.TestServiceClient) {
   459  	ctx, cancel := context.WithCancel(context.Background())
   460  	stream, err := tc.FullDuplexCall(ctx)
   461  	if err != nil {
   462  		grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
   463  	}
   464  	respParam := []*testpb.ResponseParameters{
   465  		{
   466  			Size: proto.Int32(31415),
   467  		},
   468  	}
   469  	pl := newPayload(testpb.PayloadType_COMPRESSABLE, 27182)
   470  	req := &testpb.StreamingOutputCallRequest{
   471  		ResponseType:       testpb.PayloadType_COMPRESSABLE.Enum(),
   472  		ResponseParameters: respParam,
   473  		Payload:            pl,
   474  	}
   475  	if err := stream.Send(req); err != nil {
   476  		grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
   477  	}
   478  	if _, err := stream.Recv(); err != nil {
   479  		grpclog.Fatalf("%v.Recv() = %v", stream, err)
   480  	}
   481  	cancel()
   482  	if _, err := stream.Recv(); grpc.Code(err) != codes.Canceled {
   483  		grpclog.Fatalf("%v compleled with error code %d, want %d", stream, grpc.Code(err), codes.Canceled)
   484  	}
   485  	grpclog.Println("CancelAfterFirstResponse done")
   486  }
   487  
   488  func main() {
   489  	flag.Parse()
   490  	serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort))
   491  	var opts []grpc.DialOption
   492  	if *useTLS {
   493  		var sn string
   494  		if *tlsServerName != "" {
   495  			sn = *tlsServerName
   496  		}
   497  		var creds credentials.TransportAuthenticator
   498  		if *caFile != "" {
   499  			var err error
   500  			creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
   501  			if err != nil {
   502  				grpclog.Fatalf("Failed to create TLS credentials %v", err)
   503  			}
   504  		} else {
   505  			creds = credentials.NewClientTLSFromCert(nil, sn)
   506  		}
   507  		opts = append(opts, grpc.WithTransportCredentials(creds))
   508  		if *testCase == "compute_engine_creds" {
   509  			opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine()))
   510  		} else if *testCase == "service_account_creds" {
   511  			jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
   512  			if err != nil {
   513  				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
   514  			}
   515  			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
   516  		} else if *testCase == "jwt_token_creds" {
   517  			jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile)
   518  			if err != nil {
   519  				grpclog.Fatalf("Failed to create JWT credentials: %v", err)
   520  			}
   521  			opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds))
   522  		} else if *testCase == "oauth2_auth_token" {
   523  			opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(getToken())))
   524  		}
   525  	} else {
   526  		opts = append(opts, grpc.WithInsecure())
   527  	}
   528  	conn, err := grpc.Dial(serverAddr, opts...)
   529  	if err != nil {
   530  		grpclog.Fatalf("Fail to dial: %v", err)
   531  	}
   532  	defer conn.Close()
   533  	tc := testpb.NewTestServiceClient(conn)
   534  	switch *testCase {
   535  	case "empty_unary":
   536  		doEmptyUnaryCall(tc)
   537  	case "large_unary":
   538  		doLargeUnaryCall(tc)
   539  	case "client_streaming":
   540  		doClientStreaming(tc)
   541  	case "server_streaming":
   542  		doServerStreaming(tc)
   543  	case "ping_pong":
   544  		doPingPong(tc)
   545  	case "empty_stream":
   546  		doEmptyStream(tc)
   547  	case "timeout_on_sleeping_server":
   548  		doTimeoutOnSleepingServer(tc)
   549  	case "compute_engine_creds":
   550  		if !*useTLS {
   551  			grpclog.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.")
   552  		}
   553  		doComputeEngineCreds(tc)
   554  	case "service_account_creds":
   555  		if !*useTLS {
   556  			grpclog.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.")
   557  		}
   558  		doServiceAccountCreds(tc)
   559  	case "jwt_token_creds":
   560  		if !*useTLS {
   561  			grpclog.Fatalf("TLS is not enabled. TLS is required to execute jwt_token_creds test case.")
   562  		}
   563  		doJWTTokenCreds(tc)
   564  	case "per_rpc_creds":
   565  		if !*useTLS {
   566  			grpclog.Fatalf("TLS is not enabled. TLS is required to execute per_rpc_creds test case.")
   567  		}
   568  		doPerRPCCreds(tc)
   569  	case "oauth2_auth_token":
   570  		if !*useTLS {
   571  			grpclog.Fatalf("TLS is not enabled. TLS is required to execute oauth2_auth_token test case.")
   572  		}
   573  		doOauth2TokenCreds(tc)
   574  	case "cancel_after_begin":
   575  		doCancelAfterBegin(tc)
   576  	case "cancel_after_first_response":
   577  		doCancelAfterFirstResponse(tc)
   578  	default:
   579  		grpclog.Fatal("Unsupported test case: ", *testCase)
   580  	}
   581  }