ClientRunners.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #region Copyright notice and license
  2. // Copyright 2015 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Collections.Concurrent;
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Text.RegularExpressions;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. using Google.Protobuf;
  26. using Grpc.Core;
  27. using Grpc.Core.Internal;
  28. using Grpc.Core.Logging;
  29. using Grpc.Core.Profiling;
  30. using Grpc.Core.Utils;
  31. using NUnit.Framework;
  32. using Grpc.Testing;
  33. namespace Grpc.IntegrationTesting
  34. {
  35. /// <summary>
  36. /// Helper methods to start client runners for performance testing.
  37. /// </summary>
  38. public class ClientRunners
  39. {
  40. static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientRunners>();
  41. // Profilers to use for clients.
  42. static readonly BlockingCollection<BasicProfiler> profilers = new BlockingCollection<BasicProfiler>();
  43. internal static void AddProfiler(BasicProfiler profiler)
  44. {
  45. GrpcPreconditions.CheckNotNull(profiler);
  46. profilers.Add(profiler);
  47. }
  48. /// <summary>
  49. /// Creates a started client runner.
  50. /// </summary>
  51. public static IClientRunner CreateStarted(ClientConfig config)
  52. {
  53. Logger.Debug("ClientConfig: {0}", config);
  54. if (config.AsyncClientThreads != 0)
  55. {
  56. Logger.Warning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value");
  57. }
  58. if (config.CoreLimit != 0)
  59. {
  60. Logger.Warning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value");
  61. }
  62. if (config.CoreList.Count > 0)
  63. {
  64. Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value");
  65. }
  66. var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams, config.ChannelArgs);
  67. return new ClientRunnerImpl(channels,
  68. config.ClientType,
  69. config.RpcType,
  70. config.OutstandingRpcsPerChannel,
  71. config.LoadParams,
  72. config.PayloadConfig,
  73. config.HistogramParams,
  74. () => GetNextProfiler());
  75. }
  76. private static List<Channel> CreateChannels(int clientChannels, IEnumerable<string> serverTargets, SecurityParams securityParams, IEnumerable<ChannelArg> channelArguments)
  77. {
  78. GrpcPreconditions.CheckArgument(clientChannels > 0, "clientChannels needs to be at least 1.");
  79. GrpcPreconditions.CheckArgument(serverTargets.Count() > 0, "at least one serverTarget needs to be specified.");
  80. var credentials = securityParams != null ? TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure;
  81. var channelOptions = new List<ChannelOption>();
  82. if (securityParams != null && securityParams.ServerHostOverride != "")
  83. {
  84. channelOptions.Add(new ChannelOption(ChannelOptions.SslTargetNameOverride, securityParams.ServerHostOverride));
  85. }
  86. foreach (var channelArgument in channelArguments)
  87. {
  88. channelOptions.Add(channelArgument.ToChannelOption());
  89. }
  90. var result = new List<Channel>();
  91. for (int i = 0; i < clientChannels; i++)
  92. {
  93. var target = serverTargets.ElementAt(i % serverTargets.Count());
  94. var channel = new Channel(target, credentials, channelOptions);
  95. result.Add(channel);
  96. }
  97. return result;
  98. }
  99. private static BasicProfiler GetNextProfiler()
  100. {
  101. BasicProfiler result = null;
  102. profilers.TryTake(out result);
  103. return result;
  104. }
  105. }
  106. internal class ClientRunnerImpl : IClientRunner
  107. {
  108. const double SecondsToNanos = 1e9;
  109. readonly List<Channel> channels;
  110. readonly ClientType clientType;
  111. readonly RpcType rpcType;
  112. readonly PayloadConfig payloadConfig;
  113. readonly Lazy<byte[]> cachedByteBufferRequest;
  114. readonly ThreadLocal<Histogram> threadLocalHistogram;
  115. readonly List<Task> runnerTasks;
  116. readonly CancellationTokenSource stoppedCts = new CancellationTokenSource();
  117. readonly TimeStats timeStats = new TimeStats();
  118. readonly AtomicCounter statsResetCount = new AtomicCounter();
  119. public ClientRunnerImpl(List<Channel> channels, ClientType clientType, RpcType rpcType, int outstandingRpcsPerChannel, LoadParams loadParams, PayloadConfig payloadConfig, HistogramParams histogramParams, Func<BasicProfiler> profilerFactory)
  120. {
  121. GrpcPreconditions.CheckArgument(outstandingRpcsPerChannel > 0, "outstandingRpcsPerChannel");
  122. GrpcPreconditions.CheckNotNull(histogramParams, "histogramParams");
  123. this.channels = new List<Channel>(channels);
  124. this.clientType = clientType;
  125. this.rpcType = rpcType;
  126. this.payloadConfig = payloadConfig;
  127. this.cachedByteBufferRequest = new Lazy<byte[]>(() => new byte[payloadConfig.BytebufParams.ReqSize]);
  128. this.threadLocalHistogram = new ThreadLocal<Histogram>(() => new Histogram(histogramParams.Resolution, histogramParams.MaxPossible), true);
  129. this.runnerTasks = new List<Task>();
  130. foreach (var channel in this.channels)
  131. {
  132. for (int i = 0; i < outstandingRpcsPerChannel; i++)
  133. {
  134. var timer = CreateTimer(loadParams, 1.0 / this.channels.Count / outstandingRpcsPerChannel);
  135. var optionalProfiler = profilerFactory();
  136. this.runnerTasks.Add(RunClientAsync(channel, timer, optionalProfiler));
  137. }
  138. }
  139. }
  140. public ClientStats GetStats(bool reset)
  141. {
  142. var histogramData = new HistogramData();
  143. foreach (var hist in threadLocalHistogram.Values)
  144. {
  145. hist.GetSnapshot(histogramData, reset);
  146. }
  147. var timeSnapshot = timeStats.GetSnapshot(reset);
  148. if (reset)
  149. {
  150. statsResetCount.Increment();
  151. }
  152. GrpcEnvironment.Logger.Info("[ClientRunnerImpl.GetStats] GC collection counts: gen0 {0}, gen1 {1}, gen2 {2}, (histogram reset count:{3}, seconds since reset: {4})",
  153. GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), statsResetCount.Count, timeSnapshot.WallClockTime.TotalSeconds);
  154. return new ClientStats
  155. {
  156. Latencies = histogramData,
  157. TimeElapsed = timeSnapshot.WallClockTime.TotalSeconds,
  158. TimeUser = timeSnapshot.UserProcessorTime.TotalSeconds,
  159. TimeSystem = timeSnapshot.PrivilegedProcessorTime.TotalSeconds
  160. };
  161. }
  162. public async Task StopAsync()
  163. {
  164. stoppedCts.Cancel();
  165. foreach (var runnerTask in runnerTasks)
  166. {
  167. await runnerTask;
  168. }
  169. foreach (var channel in channels)
  170. {
  171. await channel.ShutdownAsync();
  172. }
  173. }
  174. private void RunUnary(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler)
  175. {
  176. if (optionalProfiler != null)
  177. {
  178. Profilers.SetForCurrentThread(optionalProfiler);
  179. }
  180. bool profilerReset = false;
  181. var client = new BenchmarkService.BenchmarkServiceClient(channel);
  182. var request = CreateSimpleRequest();
  183. var stopwatch = new Stopwatch();
  184. while (!stoppedCts.Token.IsCancellationRequested)
  185. {
  186. // after the first stats reset, also reset the profiler.
  187. if (optionalProfiler != null && !profilerReset && statsResetCount.Count > 0)
  188. {
  189. optionalProfiler.Reset();
  190. profilerReset = true;
  191. }
  192. stopwatch.Restart();
  193. client.UnaryCall(request);
  194. stopwatch.Stop();
  195. // spec requires data point in nanoseconds.
  196. threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
  197. timer.WaitForNext();
  198. }
  199. }
  200. private async Task RunUnaryAsync(Channel channel, IInterarrivalTimer timer)
  201. {
  202. var client = new BenchmarkService.BenchmarkServiceClient(channel);
  203. var request = CreateSimpleRequest();
  204. var stopwatch = new Stopwatch();
  205. while (!stoppedCts.Token.IsCancellationRequested)
  206. {
  207. stopwatch.Restart();
  208. await client.UnaryCallAsync(request);
  209. stopwatch.Stop();
  210. // spec requires data point in nanoseconds.
  211. threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
  212. await timer.WaitForNextAsync();
  213. }
  214. }
  215. private async Task RunStreamingPingPongAsync(Channel channel, IInterarrivalTimer timer)
  216. {
  217. var client = new BenchmarkService.BenchmarkServiceClient(channel);
  218. var request = CreateSimpleRequest();
  219. var stopwatch = new Stopwatch();
  220. using (var call = client.StreamingCall())
  221. {
  222. while (!stoppedCts.Token.IsCancellationRequested)
  223. {
  224. stopwatch.Restart();
  225. await call.RequestStream.WriteAsync(request);
  226. await call.ResponseStream.MoveNext();
  227. stopwatch.Stop();
  228. // spec requires data point in nanoseconds.
  229. threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
  230. await timer.WaitForNextAsync();
  231. }
  232. // finish the streaming call
  233. await call.RequestStream.CompleteAsync();
  234. Assert.IsFalse(await call.ResponseStream.MoveNext());
  235. }
  236. }
  237. private async Task RunGenericStreamingAsync(Channel channel, IInterarrivalTimer timer)
  238. {
  239. var request = cachedByteBufferRequest.Value;
  240. var stopwatch = new Stopwatch();
  241. var callDetails = new CallInvocationDetails<byte[], byte[]>(channel, GenericService.StreamingCallMethod, new CallOptions());
  242. using (var call = Calls.AsyncDuplexStreamingCall(callDetails))
  243. {
  244. while (!stoppedCts.Token.IsCancellationRequested)
  245. {
  246. stopwatch.Restart();
  247. await call.RequestStream.WriteAsync(request);
  248. await call.ResponseStream.MoveNext();
  249. stopwatch.Stop();
  250. // spec requires data point in nanoseconds.
  251. threadLocalHistogram.Value.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos);
  252. await timer.WaitForNextAsync();
  253. }
  254. // finish the streaming call
  255. await call.RequestStream.CompleteAsync();
  256. Assert.IsFalse(await call.ResponseStream.MoveNext());
  257. }
  258. }
  259. private Task RunClientAsync(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler)
  260. {
  261. if (payloadConfig.PayloadCase == PayloadConfig.PayloadOneofCase.BytebufParams)
  262. {
  263. GrpcPreconditions.CheckArgument(clientType == ClientType.AsyncClient, "Generic client only supports async API");
  264. GrpcPreconditions.CheckArgument(rpcType == RpcType.Streaming, "Generic client only supports streaming calls");
  265. return RunGenericStreamingAsync(channel, timer);
  266. }
  267. GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams);
  268. if (clientType == ClientType.SyncClient)
  269. {
  270. GrpcPreconditions.CheckArgument(rpcType == RpcType.Unary, "Sync client can only be used for Unary calls in C#");
  271. // create a dedicated thread for the synchronous client
  272. return Task.Factory.StartNew(() => RunUnary(channel, timer, optionalProfiler), TaskCreationOptions.LongRunning);
  273. }
  274. else if (clientType == ClientType.AsyncClient)
  275. {
  276. switch (rpcType)
  277. {
  278. case RpcType.Unary:
  279. return RunUnaryAsync(channel, timer);
  280. case RpcType.Streaming:
  281. return RunStreamingPingPongAsync(channel, timer);
  282. }
  283. }
  284. throw new ArgumentException("Unsupported configuration.");
  285. }
  286. private SimpleRequest CreateSimpleRequest()
  287. {
  288. GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams);
  289. return new SimpleRequest
  290. {
  291. Payload = CreateZerosPayload(payloadConfig.SimpleParams.ReqSize),
  292. ResponseSize = payloadConfig.SimpleParams.RespSize
  293. };
  294. }
  295. private static Payload CreateZerosPayload(int size)
  296. {
  297. return new Payload { Body = ByteString.CopyFrom(new byte[size]) };
  298. }
  299. private static IInterarrivalTimer CreateTimer(LoadParams loadParams, double loadMultiplier)
  300. {
  301. switch (loadParams.LoadCase)
  302. {
  303. case LoadParams.LoadOneofCase.ClosedLoop:
  304. return new ClosedLoopInterarrivalTimer();
  305. case LoadParams.LoadOneofCase.Poisson:
  306. return new PoissonInterarrivalTimer(loadParams.Poisson.OfferedLoad * loadMultiplier);
  307. default:
  308. throw new ArgumentException("Unknown load type");
  309. }
  310. }
  311. }
  312. }