benchmark_client.js 12 KB

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