XdsInteropClient.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. #region Copyright notice and license
  2. // Copyright 2020 The 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.Generic;
  18. using System.Diagnostics;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using CommandLine;
  22. using Grpc.Core;
  23. using Grpc.Core.Logging;
  24. using Grpc.Core.Internal;
  25. using Grpc.Testing;
  26. namespace Grpc.IntegrationTesting
  27. {
  28. public class XdsInteropClient
  29. {
  30. internal class ClientOptions
  31. {
  32. [Option("num_channels", Default = 1)]
  33. public int NumChannels { get; set; }
  34. [Option("qps", Default = 1)]
  35. // The desired QPS per channel, for each type of RPC.
  36. public int Qps { get; set; }
  37. [Option("server", Default = "localhost:8080")]
  38. public string Server { get; set; }
  39. [Option("stats_port", Default = 8081)]
  40. public int StatsPort { get; set; }
  41. [Option("rpc_timeout_sec", Default = 30)]
  42. public int RpcTimeoutSec { get; set; }
  43. [Option("print_response", Default = false)]
  44. public bool PrintResponse { get; set; }
  45. // Types of RPCs to make, ',' separated string. RPCs can be EmptyCall or UnaryCall
  46. [Option("rpc", Default = "UnaryCall")]
  47. public string Rpc { get; set; }
  48. // The metadata to send with each RPC, in the format EmptyCall:key1:value1,UnaryCall:key2:value2
  49. [Option("metadata", Default = null)]
  50. public string Metadata { get; set; }
  51. }
  52. internal enum RpcType
  53. {
  54. UnaryCall,
  55. EmptyCall
  56. }
  57. ClientOptions options;
  58. StatsWatcher statsWatcher = new StatsWatcher();
  59. List<RpcType> rpcs;
  60. Dictionary<RpcType, Metadata> metadata;
  61. // make watcher accessible by tests
  62. internal StatsWatcher StatsWatcher => statsWatcher;
  63. internal XdsInteropClient(ClientOptions options)
  64. {
  65. this.options = options;
  66. this.rpcs = ParseRpcArgument(this.options.Rpc);
  67. this.metadata = ParseMetadataArgument(this.options.Metadata);
  68. }
  69. public static void Run(string[] args)
  70. {
  71. GrpcEnvironment.SetLogger(new ConsoleLogger());
  72. var parserResult = Parser.Default.ParseArguments<ClientOptions>(args)
  73. .WithNotParsed(errors => Environment.Exit(1))
  74. .WithParsed(options =>
  75. {
  76. var xdsInteropClient = new XdsInteropClient(options);
  77. xdsInteropClient.RunAsync().Wait();
  78. });
  79. }
  80. private async Task RunAsync()
  81. {
  82. var server = new Server
  83. {
  84. Services = { LoadBalancerStatsService.BindService(new LoadBalancerStatsServiceImpl(statsWatcher)) }
  85. };
  86. string host = "0.0.0.0";
  87. server.Ports.Add(host, options.StatsPort, ServerCredentials.Insecure);
  88. Console.WriteLine($"Running server on {host}:{options.StatsPort}");
  89. server.Start();
  90. var cancellationTokenSource = new CancellationTokenSource();
  91. await RunChannelsAsync(cancellationTokenSource.Token);
  92. await server.ShutdownAsync();
  93. }
  94. // method made internal to make it runnable by tests
  95. internal async Task RunChannelsAsync(CancellationToken cancellationToken)
  96. {
  97. var channelTasks = new List<Task>();
  98. for (int channelId = 0; channelId < options.NumChannels; channelId++)
  99. {
  100. var channelTask = RunSingleChannelAsync(channelId, cancellationToken);
  101. channelTasks.Add(channelTask);
  102. }
  103. for (int channelId = 0; channelId < options.NumChannels; channelId++)
  104. {
  105. await channelTasks[channelId];
  106. }
  107. }
  108. private async Task RunSingleChannelAsync(int channelId, CancellationToken cancellationToken)
  109. {
  110. Console.WriteLine($"Starting channel {channelId}");
  111. var channel = new Channel(options.Server, ChannelCredentials.Insecure);
  112. var client = new TestService.TestServiceClient(channel);
  113. var inflightTasks = new List<Task>();
  114. long rpcsStarted = 0;
  115. var stopwatch = Stopwatch.StartNew();
  116. while (!cancellationToken.IsCancellationRequested)
  117. {
  118. foreach (var rpcType in rpcs)
  119. {
  120. inflightTasks.Add(RunSingleRpcAsync(client, cancellationToken, rpcType));
  121. rpcsStarted++;
  122. }
  123. // only cleanup calls that have already completed, calls that are still inflight will be cleaned up later.
  124. await CleanupCompletedTasksAsync(inflightTasks);
  125. // if needed, wait a bit before we start the next RPC.
  126. int nextDueInMillis = (int) Math.Max(0, (1000 * rpcsStarted / options.Qps / rpcs.Count) - stopwatch.ElapsedMilliseconds);
  127. if (nextDueInMillis > 0)
  128. {
  129. await Task.Delay(nextDueInMillis);
  130. }
  131. }
  132. stopwatch.Stop();
  133. Console.WriteLine($"Shutting down channel {channelId}");
  134. await channel.ShutdownAsync();
  135. Console.WriteLine($"Channel shutdown {channelId}");
  136. }
  137. private async Task RunSingleRpcAsync(TestService.TestServiceClient client, CancellationToken cancellationToken, RpcType rpcType)
  138. {
  139. long rpcId = statsWatcher.RpcIdGenerator.Increment();
  140. try
  141. {
  142. // metadata to send with the RPC
  143. var headers = new Metadata();
  144. if (metadata.ContainsKey(rpcType))
  145. {
  146. headers = metadata[rpcType];
  147. if (headers.Count > 0)
  148. {
  149. var printableHeaders = "[" + string.Join(", ", headers) + "]";
  150. }
  151. }
  152. if (rpcType == RpcType.UnaryCall)
  153. {
  154. var call = client.UnaryCallAsync(new SimpleRequest(),
  155. new CallOptions(headers: headers, cancellationToken: cancellationToken, deadline: DateTime.UtcNow.AddSeconds(options.RpcTimeoutSec)));
  156. var response = await call;
  157. var hostname = (await call.ResponseHeadersAsync).GetValue("hostname") ?? response.Hostname;
  158. statsWatcher.OnRpcComplete(rpcId, rpcType, hostname);
  159. if (options.PrintResponse)
  160. {
  161. Console.WriteLine($"Got response {response}");
  162. }
  163. }
  164. else if (rpcType == RpcType.EmptyCall)
  165. {
  166. var call = client.EmptyCallAsync(new Empty(),
  167. new CallOptions(headers: headers, cancellationToken: cancellationToken, deadline: DateTime.UtcNow.AddSeconds(options.RpcTimeoutSec)));
  168. var response = await call;
  169. var hostname = (await call.ResponseHeadersAsync).GetValue("hostname");
  170. statsWatcher.OnRpcComplete(rpcId, rpcType, hostname);
  171. if (options.PrintResponse)
  172. {
  173. Console.WriteLine($"Got response {response}");
  174. }
  175. }
  176. else
  177. {
  178. throw new InvalidOperationException($"Unsupported RPC type ${rpcType}");
  179. }
  180. }
  181. catch (RpcException ex)
  182. {
  183. statsWatcher.OnRpcComplete(rpcId, rpcType, null);
  184. if (options.PrintResponse)
  185. {
  186. Console.WriteLine($"RPC {rpcId} failed: {ex}");
  187. }
  188. }
  189. }
  190. private async Task CleanupCompletedTasksAsync(List<Task> tasks)
  191. {
  192. var toRemove = new List<Task>();
  193. foreach (var task in tasks)
  194. {
  195. if (task.IsCompleted)
  196. {
  197. // awaiting tasks that have already completed should be instantaneous
  198. await task;
  199. }
  200. toRemove.Add(task);
  201. }
  202. foreach (var task in toRemove)
  203. {
  204. tasks.Remove(task);
  205. }
  206. }
  207. private static List<RpcType> ParseRpcArgument(string rpcArg)
  208. {
  209. var result = new List<RpcType>();
  210. foreach (var part in rpcArg.Split(','))
  211. {
  212. result.Add(ParseRpc(part));
  213. }
  214. return result;
  215. }
  216. private static RpcType ParseRpc(string rpc)
  217. {
  218. switch (rpc)
  219. {
  220. case "UnaryCall":
  221. return RpcType.UnaryCall;
  222. case "EmptyCall":
  223. return RpcType.EmptyCall;
  224. default:
  225. throw new ArgumentException($"Unknown RPC: \"{rpc}\"");
  226. }
  227. }
  228. private static Dictionary<RpcType, Metadata> ParseMetadataArgument(string metadataArg)
  229. {
  230. var rpcMetadata = new Dictionary<RpcType, Metadata>();
  231. if (string.IsNullOrEmpty(metadataArg))
  232. {
  233. return rpcMetadata;
  234. }
  235. foreach (var metadata in metadataArg.Split(','))
  236. {
  237. var parts = metadata.Split(':');
  238. if (parts.Length != 3)
  239. {
  240. throw new ArgumentException($"Invalid metadata: \"{metadata}\"");
  241. }
  242. var rpc = ParseRpc(parts[0]);
  243. var key = parts[1];
  244. var value = parts[2];
  245. var md = new Metadata { {key, value} };
  246. if (rpcMetadata.ContainsKey(rpc))
  247. {
  248. var existingMetadata = rpcMetadata[rpc];
  249. foreach (var entry in md)
  250. {
  251. existingMetadata.Add(entry);
  252. }
  253. }
  254. else
  255. {
  256. rpcMetadata.Add(rpc, md);
  257. }
  258. }
  259. return rpcMetadata;
  260. }
  261. }
  262. internal class StatsWatcher
  263. {
  264. private readonly object myLock = new object();
  265. private readonly AtomicCounter rpcIdGenerator = new AtomicCounter(0);
  266. private long? firstAcceptedRpcId;
  267. private int numRpcsWanted;
  268. private int rpcsCompleted;
  269. private int rpcsNoHostname;
  270. private Dictionary<string, int> rpcsByHostname;
  271. private Dictionary<string, Dictionary<string, int>> rpcsByMethod;
  272. public AtomicCounter RpcIdGenerator => rpcIdGenerator;
  273. public StatsWatcher()
  274. {
  275. Reset();
  276. }
  277. public void OnRpcComplete(long rpcId, XdsInteropClient.RpcType rpcType, string responseHostname)
  278. {
  279. lock (myLock)
  280. {
  281. if (!firstAcceptedRpcId.HasValue || rpcId < firstAcceptedRpcId || rpcId >= firstAcceptedRpcId + numRpcsWanted)
  282. {
  283. return;
  284. }
  285. if (string.IsNullOrEmpty(responseHostname))
  286. {
  287. rpcsNoHostname ++;
  288. }
  289. else
  290. {
  291. // update rpcsByHostname
  292. if (!rpcsByHostname.ContainsKey(responseHostname))
  293. {
  294. rpcsByHostname[responseHostname] = 0;
  295. }
  296. rpcsByHostname[responseHostname] += 1;
  297. // update rpcsByMethod
  298. var method = rpcType.ToString();
  299. if (!rpcsByMethod.ContainsKey(method))
  300. {
  301. rpcsByMethod[method] = new Dictionary<string, int>();
  302. }
  303. if (!rpcsByMethod[method].ContainsKey(responseHostname))
  304. {
  305. rpcsByMethod[method][responseHostname] = 0;
  306. }
  307. rpcsByMethod[method][responseHostname] += 1;
  308. }
  309. rpcsCompleted += 1;
  310. if (rpcsCompleted >= numRpcsWanted)
  311. {
  312. Monitor.Pulse(myLock);
  313. }
  314. }
  315. }
  316. public void Reset()
  317. {
  318. lock (myLock)
  319. {
  320. firstAcceptedRpcId = null;
  321. numRpcsWanted = 0;
  322. rpcsCompleted = 0;
  323. rpcsNoHostname = 0;
  324. rpcsByHostname = new Dictionary<string, int>();
  325. rpcsByMethod = new Dictionary<string, Dictionary<string, int>>();
  326. }
  327. }
  328. public LoadBalancerStatsResponse WaitForRpcStatsResponse(int rpcsWanted, int timeoutSec)
  329. {
  330. lock (myLock)
  331. {
  332. if (firstAcceptedRpcId.HasValue)
  333. {
  334. throw new InvalidOperationException("StateWatcher is already collecting stats.");
  335. }
  336. // we are only interested in the next numRpcsWanted RPCs
  337. firstAcceptedRpcId = rpcIdGenerator.Count + 1;
  338. numRpcsWanted = rpcsWanted;
  339. var deadline = DateTime.UtcNow.AddSeconds(timeoutSec);
  340. while (true)
  341. {
  342. var timeoutMillis = Math.Max((int)(deadline - DateTime.UtcNow).TotalMilliseconds, 0);
  343. if (!Monitor.Wait(myLock, timeoutMillis) || rpcsCompleted >= rpcsWanted)
  344. {
  345. // we collected enough RPCs, or timed out waiting
  346. var response = new LoadBalancerStatsResponse { NumFailures = rpcsNoHostname };
  347. response.RpcsByPeer.Add(rpcsByHostname);
  348. response.RpcsByMethod.Clear();
  349. foreach (var methodEntry in rpcsByMethod)
  350. {
  351. var rpcsByPeer = new LoadBalancerStatsResponse.Types.RpcsByPeer();
  352. rpcsByPeer.RpcsByPeer_.Add(methodEntry.Value);
  353. response.RpcsByMethod[methodEntry.Key] = rpcsByPeer;
  354. }
  355. Reset();
  356. return response;
  357. }
  358. }
  359. }
  360. }
  361. }
  362. /// <summary>
  363. /// Implementation of LoadBalancerStatsService server
  364. /// </summary>
  365. internal class LoadBalancerStatsServiceImpl : LoadBalancerStatsService.LoadBalancerStatsServiceBase
  366. {
  367. StatsWatcher statsWatcher;
  368. public LoadBalancerStatsServiceImpl(StatsWatcher statsWatcher)
  369. {
  370. this.statsWatcher = statsWatcher;
  371. }
  372. public override async Task<LoadBalancerStatsResponse> GetClientStats(LoadBalancerStatsRequest request, ServerCallContext context)
  373. {
  374. // run as a task to avoid blocking
  375. var response = await Task.Run(() => statsWatcher.WaitForRpcStatsResponse(request.NumRpcs, request.TimeoutSec));
  376. Console.WriteLine($"Returning stats {response} (num of requested RPCs: {request.NumRpcs})");
  377. return response;
  378. }
  379. }
  380. }