google.golang.org/grpc@v1.72.2/interop/xds_federation/client.go (about)

     1  /*
     2   *
     3   * Copyright 2014 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   */
    18  
    19  // Binary client is an interop client.
    20  package main
    21  
    22  import (
    23  	"context"
    24  	"flag"
    25  	"log"
    26  	"strings"
    27  	"sync"
    28  	"time"
    29  
    30  	"google.golang.org/grpc"
    31  	"google.golang.org/grpc/credentials/google"
    32  	"google.golang.org/grpc/credentials/insecure"
    33  	"google.golang.org/grpc/grpclog"
    34  	"google.golang.org/grpc/interop"
    35  
    36  	_ "google.golang.org/grpc/balancer/grpclb"      // Register the grpclb load balancing policy.
    37  	_ "google.golang.org/grpc/balancer/rls"         // Register the RLS load balancing policy.
    38  	_ "google.golang.org/grpc/xds/googledirectpath" // Register xDS resolver required for c2p directpath.
    39  
    40  	testgrpc "google.golang.org/grpc/interop/grpc_testing"
    41  )
    42  
    43  const (
    44  	computeEngineCredsName = "compute_engine_channel_creds"
    45  	insecureCredsName      = "INSECURE_CREDENTIALS"
    46  )
    47  
    48  var (
    49  	serverURIs                             = flag.String("server_uris", "", "Comma-separated list of sever URIs to make RPCs to")
    50  	credentialsTypes                       = flag.String("credentials_types", "", "Comma-separated list of credentials, each entry is used for the server of the corresponding index in server_uris. Supported values: compute_engine_channel_creds, INSECURE_CREDENTIALS")
    51  	soakIterations                         = flag.Int("soak_iterations", 10, "The number of iterations to use for the two soak tests: rpc_soak and channel_soak")
    52  	soakMaxFailures                        = flag.Int("soak_max_failures", 0, "The number of iterations in soak tests that are allowed to fail (either due to non-OK status code or exceeding the per-iteration max acceptable latency).")
    53  	soakPerIterationMaxAcceptableLatencyMs = flag.Int("soak_per_iteration_max_acceptable_latency_ms", 1000, "The number of milliseconds a single iteration in the two soak tests (rpc_soak and channel_soak) should take.")
    54  	soakOverallTimeoutSeconds              = flag.Int("soak_overall_timeout_seconds", 10, "The overall number of seconds after which a soak test should stop and fail, if the desired number of iterations have not yet completed.")
    55  	soakMinTimeMsBetweenRPCs               = flag.Int("soak_min_time_ms_between_rpcs", 0, "The minimum time in milliseconds between consecutive RPCs in a soak test (rpc_soak or channel_soak), useful for limiting QPS")
    56  	soakRequestSize                        = flag.Int("soak_request_size", 271828, "The request size in a soak RPC. The default value is set based on the interop large unary test case.")
    57  	soakResponseSize                       = flag.Int("soak_response_size", 314159, "The response size in a soak RPC. The default value is set based on the interop large unary test case.")
    58  	soakNumThreads                         = flag.Int("soak_num_threads", 1, "The number of threads for concurrent execution of the soak tests (rpc_soak or channel_soak). The default value is set based on the interop large unary test case.")
    59  	testCase                               = flag.String("test_case", "rpc_soak",
    60  		`Configure different test cases. Valid options are:
    61          rpc_soak: sends --soak_iterations large_unary RPCs;
    62          channel_soak: sends --soak_iterations RPCs, rebuilding the channel each time`)
    63  
    64  	logger = grpclog.Component("interop")
    65  )
    66  
    67  type clientConfig struct {
    68  	conn *grpc.ClientConn
    69  	tc   testgrpc.TestServiceClient
    70  	opts []grpc.DialOption
    71  	uri  string
    72  }
    73  
    74  func main() {
    75  	flag.Parse()
    76  	// validate flags
    77  	uris := strings.Split(*serverURIs, ",")
    78  	creds := strings.Split(*credentialsTypes, ",")
    79  	if len(uris) != len(creds) {
    80  		logger.Fatalf("Number of entries in --server_uris (%d) != number of entries in --credentials_types (%d)", len(uris), len(creds))
    81  	}
    82  	for _, c := range creds {
    83  		if c != computeEngineCredsName && c != insecureCredsName {
    84  			logger.Fatalf("Unsupported credentials type: %v", c)
    85  		}
    86  	}
    87  	var clients []clientConfig
    88  	for i := range uris {
    89  		var opts []grpc.DialOption
    90  		switch creds[i] {
    91  		case computeEngineCredsName:
    92  			opts = append(opts, grpc.WithCredentialsBundle(google.NewComputeEngineCredentials()))
    93  		case insecureCredsName:
    94  			opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
    95  		}
    96  		cc, err := grpc.NewClient(uris[i], opts...)
    97  		if err != nil {
    98  			logger.Fatalf("grpc.NewClient(%q) = %v", uris[i], err)
    99  		}
   100  		defer cc.Close()
   101  		clients = append(clients, clientConfig{
   102  			conn: cc,
   103  			tc:   testgrpc.NewTestServiceClient(cc),
   104  			opts: opts,
   105  			uri:  uris[i],
   106  		})
   107  	}
   108  
   109  	// run soak tests with the different clients
   110  	logger.Infof("Clients running with test case %q", *testCase)
   111  	var wg sync.WaitGroup
   112  	var channelForTest func() (*grpc.ClientConn, func())
   113  	ctx := context.Background()
   114  	for i := range clients {
   115  		wg.Add(1)
   116  		go func(c clientConfig) {
   117  			ctxWithDeadline, cancel := context.WithTimeout(ctx, time.Duration(*soakOverallTimeoutSeconds)*time.Second)
   118  			defer cancel()
   119  			switch *testCase {
   120  			case "rpc_soak":
   121  				channelForTest = func() (*grpc.ClientConn, func()) { return c.conn, func() {} }
   122  			case "channel_soak":
   123  				channelForTest = func() (*grpc.ClientConn, func()) {
   124  					cc, err := grpc.NewClient(c.uri, c.opts...)
   125  					if err != nil {
   126  						log.Fatalf("Failed to create shared channel: %v", err)
   127  					}
   128  					return cc, func() { cc.Close() }
   129  				}
   130  			default:
   131  				logger.Fatal("Unsupported test case: ", *testCase)
   132  			}
   133  			soakConfig := interop.SoakTestConfig{
   134  				RequestSize:                      *soakRequestSize,
   135  				ResponseSize:                     *soakResponseSize,
   136  				PerIterationMaxAcceptableLatency: time.Duration(*soakPerIterationMaxAcceptableLatencyMs) * time.Millisecond,
   137  				MinTimeBetweenRPCs:               time.Duration(*soakMinTimeMsBetweenRPCs) * time.Millisecond,
   138  				OverallTimeout:                   time.Duration(*soakOverallTimeoutSeconds) * time.Second,
   139  				ServerAddr:                       c.uri,
   140  				NumWorkers:                       *soakNumThreads,
   141  				Iterations:                       *soakIterations,
   142  				MaxFailures:                      *soakMaxFailures,
   143  				ChannelForTest:                   channelForTest,
   144  			}
   145  			interop.DoSoakTest(ctxWithDeadline, soakConfig)
   146  			logger.Infof("%s test done for server: %s", *testCase, c.uri)
   147  			wg.Done()
   148  		}(clients[i])
   149  	}
   150  	wg.Wait()
   151  	logger.Infoln("All clients done!")
   152  }