You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rttmonitor.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import browser from '../browser';
  2. import { createRttByRegionEvent }
  3. from '../../service/statistics/AnalyticsEvents';
  4. import { getLogger } from 'jitsi-meet-logger';
  5. import RTCUtils from '../RTC/RTCUtils';
  6. import Statistics from '../statistics/statistics';
  7. const logger = getLogger(__filename);
  8. /**
  9. * The options to pass to createOffer (we need to offer to receive *something*
  10. * for the PC to gather candidates.
  11. */
  12. const offerOptions = {
  13. offerToReceiveAudio: 1,
  14. offerToReceiveVideo: 0
  15. };
  16. /**
  17. * The interval at which the webrtc engine sends STUN keep alive requests.
  18. * @type {number}
  19. */
  20. const stunKeepAliveIntervalMs = 10000;
  21. /**
  22. * Wraps a PeerConnection with one specific STUN server and measures the RTT
  23. * to the STUN server.
  24. */
  25. class PCMonitor {
  26. /* eslint-disable max-params */
  27. /**
  28. *
  29. * @param {String} region - The region of the STUN server.
  30. * @param {String} address - The address of the STUN server.
  31. * @param {number} getStatsIntervalMs how often to call getStats.
  32. * @param {number} delay the delay after which the PeerConnection will be
  33. * started (that is, createOffer and setLocalDescription will be invoked).
  34. *
  35. */
  36. constructor(region, address, getStatsIntervalMs, delay) {
  37. /* eslint-disable max-params */
  38. this.region = region;
  39. this.getStatsIntervalMs = getStatsIntervalMs;
  40. this.getStatsInterval = null;
  41. // What we consider the current RTT. It is Math.min(this.rtts).
  42. this.rtt = Infinity;
  43. // The RTT measurements we've made from the latest getStats() calls.
  44. this.rtts = [];
  45. const iceServers = [ { 'url': `stun:${address}` } ];
  46. this.pc = new RTCUtils.RTCPeerConnectionType(
  47. {
  48. 'iceServers': iceServers
  49. });
  50. // Maps a key consisting of the IP address, port and priority of a
  51. // candidate to some state related to it. If we have more than one
  52. // network interface we will might multiple srflx candidates and this
  53. // helps to distinguish between then.
  54. this.candidates = {};
  55. this.stopped = false;
  56. this.start = this.start.bind(this);
  57. this.stop = this.stop.bind(this);
  58. this.startStatsInterval = this.startStatsInterval.bind(this);
  59. this.handleCandidateRtt = this.handleCandidateRtt.bind(this);
  60. window.setTimeout(this.start, delay);
  61. }
  62. /**
  63. * Starts this PCMonitor. That is, invokes createOffer and
  64. * setLocalDescription on the PeerConnection and starts an interval which
  65. * calls getStats.
  66. */
  67. start() {
  68. if (this.stopped) {
  69. return;
  70. }
  71. this.pc.createOffer(offerOptions).then(offer => {
  72. this.pc.setLocalDescription(
  73. offer,
  74. () => {
  75. logger.info(
  76. `setLocalDescription success for ${this.region}`);
  77. this.startStatsInterval();
  78. },
  79. error => {
  80. logger.warn(
  81. `setLocalDescription failed for ${this.region}: ${
  82. error}`);
  83. }
  84. );
  85. });
  86. }
  87. /**
  88. * Starts an interval which invokes getStats on the PeerConnection and
  89. * measures the RTTs for the different candidates.
  90. */
  91. startStatsInterval() {
  92. this.getStatsInterval = window.setInterval(
  93. () => {
  94. // Note that the data that we use to measure the RTT is only
  95. // available in the legacy (callback based) getStats API.
  96. this.pc.getStats(stats => {
  97. const results = stats.result();
  98. for (let i = 0; i < results.length; ++i) {
  99. const res = results[i];
  100. const rttTotal
  101. = Number(res.stat('stunKeepaliveRttTotal'));
  102. // We recognize the results that we care for (local
  103. // candidates of type srflx) by the existance of the
  104. // stunKeepaliveRttTotal stat.
  105. if (rttTotal > 0) {
  106. const candidateKey
  107. = `${res.stat('ipAddress')}_${
  108. res.stat('portNumber')}_${
  109. res.stat('priority')}`;
  110. this.handleCandidateRtt(
  111. candidateKey,
  112. rttTotal,
  113. Number(
  114. res.stat('stunKeepaliveResponsesReceived')),
  115. Number(
  116. res.stat('stunKeepaliveRequestsSent')));
  117. }
  118. }
  119. // After we've measured the RTT for all candidates we,
  120. // update the state of the PC with the shortest one.
  121. let rtt = Infinity;
  122. for (const key in this.candidates) {
  123. if (this.candidates.hasOwnProperty(key)
  124. && this.candidates[key].rtt > 0) {
  125. rtt = Math.min(rtt, this.candidates[key].rtt);
  126. }
  127. }
  128. // We keep the last 6 measured RTTs and choose the shortest
  129. // one to export to analytics. This is because we often see
  130. // failures get a real measurement which end up as Infinity.
  131. this.rtts.push(rtt);
  132. if (this.rtts.length > 6) {
  133. this.rtts = this.rtts.splice(1, 7);
  134. }
  135. this.rtt = Math.min(...this.rtts);
  136. });
  137. },
  138. this.getStatsIntervalMs
  139. );
  140. }
  141. /* eslint-disable max-params */
  142. /**
  143. * Updates the RTT for a candidate identified by "key" based on the values
  144. * from getStats() and the previously saved state (i.e. old values).
  145. *
  146. * @param {String} key the ID for the candidate
  147. * @param {number} rttTotal the value of the 'stunKeepaliveRttTotal' just
  148. * measured.
  149. * @param {number} responsesReceived the value of the
  150. * 'stunKeepaliveResponsesReceived' stat just measured.
  151. * @param {number} requestsSent the value of the 'stunKeepaliveRequestsSent'
  152. * stat just measured.
  153. */
  154. handleCandidateRtt(key, rttTotal, responsesReceived, requestsSent) {
  155. /* eslist-enable max-params */
  156. if (!this.candidates[key]) {
  157. this.candidates[key] = {
  158. rttTotal: 0,
  159. responsesReceived: 0,
  160. requestsSent: 0,
  161. rtt: NaN
  162. };
  163. }
  164. const rttTotalDiff = rttTotal - this.candidates[key].rttTotal;
  165. const responsesReceivedDiff
  166. = responsesReceived - this.candidates[key].responsesReceived;
  167. // We observe that when the difference between the number of requests
  168. // and responses has grown (i.q. when the value below is positive), the
  169. // the RTT measurements are incorrect (too low). For this reason we
  170. // ignore these measurement (setting rtt=NaN), but update our state.
  171. const requestsResponsesDiff
  172. = (requestsSent - responsesReceived)
  173. - (this.candidates[key].requestsSent
  174. - this.candidates[key].responsesReceived);
  175. let rtt = NaN;
  176. if (responsesReceivedDiff > 0 && requestsResponsesDiff === 0) {
  177. rtt = rttTotalDiff / responsesReceivedDiff;
  178. }
  179. this.candidates[key].rttTotal = rttTotal;
  180. this.candidates[key].responsesReceived = responsesReceived;
  181. this.candidates[key].requestsSent = requestsSent;
  182. this.candidates[key].rtt = rtt;
  183. }
  184. /**
  185. * Stops this PCMonitor, clearing its intervals and stopping the
  186. * PeerConnection.
  187. */
  188. stop() {
  189. if (this.getStatsInterval) {
  190. window.clearInterval(this.getStatsInterval);
  191. }
  192. this.pc.close();
  193. this.stopped = true;
  194. }
  195. }
  196. /**
  197. * A class which monitors the round-trip time (RTT) to a set of STUN servers.
  198. * The measured RTTs are sent as analytics events. It uses a separate
  199. * PeerConnection (represented as a PCMonitor) for each STUN server.
  200. */
  201. export default class RttMonitor {
  202. /**
  203. * Initializes a new RttMonitor.
  204. * @param {Object} config the object holding the configuration.
  205. */
  206. constructor(config) {
  207. if (!config || !config.enabled
  208. || !browser.supportsLocalCandidateRttStatistics()) {
  209. return;
  210. }
  211. // Maps a region to the PCMonitor instance for that region.
  212. this.pcMonitors = {};
  213. this.startPCMonitors = this.startPCMonitors.bind(this);
  214. this.sendAnalytics = this.sendAnalytics.bind(this);
  215. this.stop = this.stop.bind(this);
  216. this.analyticsInterval = null;
  217. this.stopped = false;
  218. const initialDelay = config.initialDelay || 60000;
  219. logger.info(
  220. `Starting RTT monitor with an initial delay of ${initialDelay}`);
  221. window.setTimeout(
  222. () => this.startPCMonitors(config),
  223. initialDelay);
  224. }
  225. /**
  226. * Starts the PCMonitors according to the configuration.
  227. */
  228. startPCMonitors(config) {
  229. if (!config.stunServers) {
  230. logger.warn('No stun servers configured.');
  231. return;
  232. }
  233. if (this.stopped) {
  234. return;
  235. }
  236. const getStatsIntervalMs
  237. = config.getStatsInterval || stunKeepAliveIntervalMs;
  238. const analyticsIntervalMs
  239. = config.analyticsInterval || getStatsIntervalMs;
  240. const count = Object.keys(config.stunServers).length;
  241. const offset = getStatsIntervalMs / count;
  242. // We delay the initialization of each PC so that they are uniformly
  243. // distributed across the getStatsIntervalMs.
  244. let i = 0;
  245. for (const region in config.stunServers) {
  246. if (config.stunServers.hasOwnProperty(region)) {
  247. const address = config.stunServers[region];
  248. this.pcMonitors[region]
  249. = new PCMonitor(
  250. region,
  251. address,
  252. getStatsIntervalMs,
  253. offset * i);
  254. i++;
  255. }
  256. }
  257. window.setTimeout(
  258. () => {
  259. if (!this.stopped) {
  260. this.analyticsInterval
  261. = window.setInterval(
  262. this.sendAnalytics, analyticsIntervalMs);
  263. }
  264. },
  265. 1000);
  266. }
  267. /**
  268. * Sends an analytics event with the measured RTT to each region/STUN
  269. * server.
  270. */
  271. sendAnalytics() {
  272. const rtts = {};
  273. for (const region in this.pcMonitors) {
  274. if (this.pcMonitors.hasOwnProperty(region)) {
  275. const rtt = this.pcMonitors[region].rtt;
  276. if (!isNaN(rtt) && rtt !== Infinity) {
  277. rtts[region.replace('-', '_')] = rtt;
  278. }
  279. }
  280. }
  281. if (rtts) {
  282. Statistics.sendAnalytics(createRttByRegionEvent(rtts));
  283. }
  284. }
  285. /**
  286. * Stops this RttMonitor, clearing all intervals and closing all
  287. * PeerConnections.
  288. */
  289. stop() {
  290. logger.info('Stopping RttMonitor.');
  291. this.stopped = true;
  292. for (const region in this.pcMonitors) {
  293. if (this.pcMonitors.hasOwnProperty(region)) {
  294. this.pcMonitors[region].stop();
  295. }
  296. }
  297. this.pcMonitors = {};
  298. if (this.analyticsInterval) {
  299. window.clearInterval(this.analyticsInterval);
  300. }
  301. }
  302. }