benchmark_client.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. *
  3. * Copyright 2015, 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. * Benchmark client module
  35. * @module
  36. */
  37. 'use strict';
  38. var fs = require('fs');
  39. var path = require('path');
  40. var util = require('util');
  41. var EventEmitter = require('events');
  42. var async = require('async');
  43. var _ = require('lodash');
  44. var PoissonProcess = require('poisson-process');
  45. var Histogram = require('./histogram');
  46. var genericService = require('./generic_service');
  47. var grpc = require('../../../');
  48. var serviceProto = grpc.load({
  49. root: __dirname + '/../../..',
  50. file: 'src/proto/grpc/testing/services.proto'}).grpc.testing;
  51. /**
  52. * Create a buffer filled with size zeroes
  53. * @param {number} size The length of the buffer
  54. * @return {Buffer} The new buffer
  55. */
  56. function zeroBuffer(size) {
  57. var zeros = new Buffer(size);
  58. zeros.fill(0);
  59. return zeros;
  60. }
  61. /**
  62. * Convert a time difference, as returned by process.hrtime, to a number of
  63. * nanoseconds.
  64. * @param {Array.<number>} time_diff The time diff, represented as
  65. * [seconds, nanoseconds]
  66. * @return {number} The total number of nanoseconds
  67. */
  68. function timeDiffToNanos(time_diff) {
  69. return time_diff[0] * 1e9 + time_diff[1];
  70. }
  71. /**
  72. * The BenchmarkClient class. Opens channels to servers and makes RPCs based on
  73. * parameters from the driver, and records statistics about those RPCs.
  74. * @param {Array.<string>} server_targets List of servers to connect to
  75. * @param {number} channels The total number of channels to open
  76. * @param {Object} histogram_params Options for setting up the histogram
  77. * @param {Object=} security_params Options for TLS setup. If absent, don't use
  78. * TLS
  79. */
  80. function BenchmarkClient(server_targets, channels, histogram_params,
  81. security_params) {
  82. var options = {};
  83. var creds;
  84. if (security_params) {
  85. var ca_path;
  86. if (security_params.use_test_ca) {
  87. ca_path = path.join(__dirname, '../test/data/ca.pem');
  88. var ca_data = fs.readFileSync(ca_path);
  89. creds = grpc.credentials.createSsl(ca_data);
  90. } else {
  91. creds = grpc.credentials.createSsl();
  92. }
  93. if (security_params.server_host_override) {
  94. var host_override = security_params.server_host_override;
  95. options['grpc.ssl_target_name_override'] = host_override;
  96. options['grpc.default_authority'] = host_override;
  97. }
  98. } else {
  99. creds = grpc.credentials.createInsecure();
  100. }
  101. this.clients = [];
  102. var GenericClient = grpc.makeGenericClientConstructor(genericService);
  103. this.genericClients = [];
  104. for (var i = 0; i < channels; i++) {
  105. this.clients[i] = new serviceProto.BenchmarkService(
  106. server_targets[i % server_targets.length], creds, options);
  107. this.genericClients[i] = new GenericClient(
  108. server_targets[i % server_targets.length], creds, options);
  109. }
  110. this.histogram = new Histogram(histogram_params.resolution,
  111. histogram_params.max_possible);
  112. this.running = false;
  113. this.pending_calls = 0;
  114. };
  115. util.inherits(BenchmarkClient, EventEmitter);
  116. /**
  117. * Start every client in the list of clients by waiting for each to be ready,
  118. * then starting outstanding_rpcs_per_channel calls on each of them
  119. * @param {Array<grpc.Client>} client_list The list of clients
  120. * @param {Number} outstanding_rpcs_per_channel The number of calls to start
  121. * on each client
  122. * @param {function(grpc.Client)} makeCall Function to make a single call on
  123. * a single client
  124. * @param {EventEmitter} emitter The event emitter to send errors on, if
  125. * necessary
  126. */
  127. function startAllClients(client_list, outstanding_rpcs_per_channel, makeCall,
  128. emitter) {
  129. var ready_wait_funcs = _.map(client_list, function(client) {
  130. return _.partial(grpc.waitForClientReady, client, Infinity);
  131. });
  132. async.parallel(ready_wait_funcs, function(err) {
  133. if (err) {
  134. emitter.emit('error', err);
  135. return;
  136. }
  137. _.each(client_list, function(client) {
  138. _.times(outstanding_rpcs_per_channel, function() {
  139. makeCall(client);
  140. });
  141. });
  142. });
  143. }
  144. /**
  145. * Start a closed-loop test. For each channel, start
  146. * outstanding_rpcs_per_channel RPCs. Then, whenever an RPC finishes, start
  147. * another one.
  148. * @param {number} outstanding_rpcs_per_channel Number of RPCs to start per
  149. * channel
  150. * @param {string} rpc_type Which method to call. Should be 'UNARY' or
  151. * 'STREAMING'
  152. * @param {number} req_size The size of the payload to send with each request
  153. * @param {number} resp_size The size of payload to request be sent in responses
  154. * @param {boolean} generic Indicates that the generic (non-proto) clients
  155. * should be used
  156. */
  157. BenchmarkClient.prototype.startClosedLoop = function(
  158. outstanding_rpcs_per_channel, rpc_type, req_size, resp_size, generic) {
  159. var self = this;
  160. self.running = true;
  161. self.last_wall_time = process.hrtime();
  162. var makeCall;
  163. var argument;
  164. var client_list;
  165. if (generic) {
  166. argument = zeroBuffer(req_size);
  167. client_list = self.genericClients;
  168. } else {
  169. argument = {
  170. response_size: resp_size,
  171. payload: {
  172. body: zeroBuffer(req_size)
  173. }
  174. };
  175. client_list = self.clients;
  176. }
  177. if (rpc_type == 'UNARY') {
  178. makeCall = function(client) {
  179. if (self.running) {
  180. self.pending_calls++;
  181. var start_time = process.hrtime();
  182. client.unaryCall(argument, function(error, response) {
  183. if (error) {
  184. self.emit('error', new Error('Client error: ' + error.message));
  185. self.running = false;
  186. return;
  187. }
  188. var time_diff = process.hrtime(start_time);
  189. self.histogram.add(timeDiffToNanos(time_diff));
  190. makeCall(client);
  191. self.pending_calls--;
  192. if ((!self.running) && self.pending_calls == 0) {
  193. self.emit('finished');
  194. }
  195. });
  196. }
  197. };
  198. } else {
  199. makeCall = function(client) {
  200. if (self.running) {
  201. self.pending_calls++;
  202. var start_time = process.hrtime();
  203. var call = client.streamingCall();
  204. call.write(argument);
  205. call.on('data', function() {
  206. });
  207. call.on('end', function() {
  208. var time_diff = process.hrtime(start_time);
  209. self.histogram.add(timeDiffToNanos(time_diff));
  210. makeCall(client);
  211. self.pending_calls--;
  212. if ((!self.running) && self.pending_calls == 0) {
  213. self.emit('finished');
  214. }
  215. });
  216. call.on('error', function(error) {
  217. self.emit('error', new Error('Client error: ' + error.message));
  218. self.running = false;
  219. });
  220. }
  221. };
  222. }
  223. startAllClients(client_list, outstanding_rpcs_per_channel, makeCall, self);
  224. };
  225. /**
  226. * Start a poisson test. For each channel, this initiates a number of Poisson
  227. * processes equal to outstanding_rpcs_per_channel, where each Poisson process
  228. * has the load parameter offered_load.
  229. * @param {number} outstanding_rpcs_per_channel Number of RPCs to start per
  230. * channel
  231. * @param {string} rpc_type Which method to call. Should be 'UNARY' or
  232. * 'STREAMING'
  233. * @param {number} req_size The size of the payload to send with each request
  234. * @param {number} resp_size The size of payload to request be sent in responses
  235. * @param {number} offered_load The load parameter for the Poisson process
  236. * @param {boolean} generic Indicates that the generic (non-proto) clients
  237. * should be used
  238. */
  239. BenchmarkClient.prototype.startPoisson = function(
  240. outstanding_rpcs_per_channel, rpc_type, req_size, resp_size, offered_load,
  241. generic) {
  242. var self = this;
  243. self.running = true;
  244. self.last_wall_time = process.hrtime();
  245. var makeCall;
  246. var argument;
  247. var client_list;
  248. if (generic) {
  249. argument = zeroBuffer(req_size);
  250. client_list = self.genericClients;
  251. } else {
  252. argument = {
  253. response_size: resp_size,
  254. payload: {
  255. body: zeroBuffer(req_size)
  256. }
  257. };
  258. client_list = self.clients;
  259. }
  260. if (rpc_type == 'UNARY') {
  261. makeCall = function(client, poisson) {
  262. if (self.running) {
  263. self.pending_calls++;
  264. var start_time = process.hrtime();
  265. client.unaryCall(argument, function(error, response) {
  266. if (error) {
  267. self.emit('error', new Error('Client error: ' + error.message));
  268. self.running = false;
  269. return;
  270. }
  271. var time_diff = process.hrtime(start_time);
  272. self.histogram.add(timeDiffToNanos(time_diff));
  273. self.pending_calls--;
  274. if ((!self.running) && self.pending_calls == 0) {
  275. self.emit('finished');
  276. }
  277. });
  278. } else {
  279. poisson.stop();
  280. }
  281. };
  282. } else {
  283. makeCall = function(client, poisson) {
  284. if (self.running) {
  285. self.pending_calls++;
  286. var start_time = process.hrtime();
  287. var call = client.streamingCall();
  288. call.write(argument);
  289. call.on('data', function() {
  290. });
  291. call.on('end', function() {
  292. var time_diff = process.hrtime(start_time);
  293. self.histogram.add(timeDiffToNanos(time_diff));
  294. self.pending_calls--;
  295. if ((!self.running) && self.pending_calls == 0) {
  296. self.emit('finished');
  297. }
  298. });
  299. call.on('error', function(error) {
  300. self.emit('error', new Error('Client error: ' + error.message));
  301. self.running = false;
  302. });
  303. } else {
  304. poisson.stop();
  305. }
  306. };
  307. }
  308. var averageIntervalMs = (1 / offered_load) * 1000;
  309. startAllClients(client_list, outstanding_rpcs_per_channel, function(client){
  310. var p = PoissonProcess.create(averageIntervalMs, function() {
  311. makeCall(client, p);
  312. });
  313. p.start();
  314. }, self);
  315. };
  316. /**
  317. * Return curent statistics for the client. If reset is set, restart
  318. * statistic collection.
  319. * @param {boolean} reset Indicates that statistics should be reset
  320. * @return {object} Client statistics
  321. */
  322. BenchmarkClient.prototype.mark = function(reset) {
  323. var wall_time_diff = process.hrtime(this.last_wall_time);
  324. var histogram = this.histogram;
  325. if (reset) {
  326. this.last_wall_time = process.hrtime();
  327. this.histogram = new Histogram(histogram.resolution,
  328. histogram.max_possible);
  329. }
  330. return {
  331. latencies: {
  332. bucket: histogram.getContents(),
  333. min_seen: histogram.minimum(),
  334. max_seen: histogram.maximum(),
  335. sum: histogram.getSum(),
  336. sum_of_squares: histogram.sumOfSquares(),
  337. count: histogram.getCount()
  338. },
  339. time_elapsed: wall_time_diff[0] + wall_time_diff[1] / 1e9,
  340. // Not sure how to measure these values
  341. time_user: 0,
  342. time_system: 0
  343. };
  344. };
  345. /**
  346. * Stop the clients.
  347. * @param {function} callback Called when the clients have finished shutting
  348. * down
  349. */
  350. BenchmarkClient.prototype.stop = function(callback) {
  351. this.running = false;
  352. this.on('finished', callback);
  353. };
  354. module.exports = BenchmarkClient;