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.

statistics.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. import EventEmitter from 'events';
  2. import analytics from './AnalyticsAdapter';
  3. import CallStats from './CallStats';
  4. import LocalStats from './LocalStatsCollector';
  5. import RTPStats from './RTPStatsCollector';
  6. import RTCBrowserType from '../RTC/RTCBrowserType';
  7. import Settings from '../settings/Settings';
  8. import ScriptUtil from '../util/ScriptUtil';
  9. import JitsiTrackError from '../../JitsiTrackError';
  10. import * as StatisticsEvents from '../../service/statistics/Events';
  11. const logger = require('jitsi-meet-logger').getLogger(__filename);
  12. /**
  13. * Stores all active {@link Statistics} instances.
  14. * @type {Set<Statistics>}
  15. */
  16. let _instances;
  17. /**
  18. * True if callstats API is loaded
  19. */
  20. let isCallstatsLoaded = false;
  21. /**
  22. * Since callstats.io is a third party, we cannot guarantee the quality of their
  23. * service. More specifically, their server may take noticeably long time to
  24. * respond. Consequently, it is in our best interest (in the sense that the
  25. * intergration of callstats.io is pretty important to us but not enough to
  26. * allow it to prevent people from joining a conference) to (1) start
  27. * downloading their API as soon as possible and (2) do the downloading
  28. * asynchronously.
  29. *
  30. * @param customScriptUrl
  31. */
  32. function loadCallStatsAPI(customScriptUrl) {
  33. if (!isCallstatsLoaded) {
  34. ScriptUtil.loadScript(
  35. customScriptUrl
  36. || 'https://api.callstats.io/static/callstats-ws.min.js',
  37. /* async */ true,
  38. /* prepend */ true);
  39. isCallstatsLoaded = true;
  40. }
  41. // FIXME At the time of this writing, we hope that the callstats.io API will
  42. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  43. }
  44. /**
  45. * callstats strips any additional fields from Error except for "name", "stack",
  46. * "message" and "constraintName". So we need to bundle additional information
  47. * from JitsiTrackError into error passed to callstats to preserve valuable
  48. * information about error.
  49. * @param {JitsiTrackError} error
  50. */
  51. function formatJitsiTrackErrorForCallStats(error) {
  52. const err = new Error();
  53. // Just copy original stack from error
  54. err.stack = error.stack;
  55. // Combine name from error's name plus (possibly) name of original GUM error
  56. err.name = (error.name || 'Unknown error') + (error.gum && error.gum.error
  57. && error.gum.error.name ? ` - ${error.gum.error.name}` : '');
  58. // Put all constraints into this field. For constraint failed errors we will
  59. // still know which exactly constraint failed as it will be a part of
  60. // message.
  61. err.constraintName = error.gum && error.gum.constraints
  62. ? JSON.stringify(error.gum.constraints) : '';
  63. // Just copy error's message.
  64. err.message = error.message;
  65. return err;
  66. }
  67. /**
  68. * Init statistic options
  69. * @param options
  70. */
  71. Statistics.init = function(options) {
  72. Statistics.audioLevelsEnabled = !options.disableAudioLevels;
  73. if (typeof options.audioLevelsInterval === 'number') {
  74. Statistics.audioLevelsInterval = options.audioLevelsInterval;
  75. }
  76. Statistics.disableThirdPartyRequests = options.disableThirdPartyRequests;
  77. };
  78. /**
  79. *
  80. * @param xmpp
  81. * @param options
  82. */
  83. export default function Statistics(xmpp, options) {
  84. /**
  85. * {@link RTPStats} mapped by {@link TraceablePeerConnection.id} which
  86. * collect RTP statistics for each peerconnection.
  87. * @type {Map<string, RTPStats}
  88. */
  89. this.rtpStatsMap = new Map();
  90. this.eventEmitter = new EventEmitter();
  91. this.xmpp = xmpp;
  92. this.options = options || {};
  93. this.callStatsIntegrationEnabled
  94. = this.options.callStatsID && this.options.callStatsSecret
  95. // Even though AppID and AppSecret may be specified, the integration
  96. // of callstats.io may be disabled because of globally-disallowed
  97. // requests to any third parties.
  98. && (Statistics.disableThirdPartyRequests !== true);
  99. if (this.callStatsIntegrationEnabled) {
  100. if (!RTCBrowserType.isReactNative()) {
  101. loadCallStatsAPI(this.options.callStatsCustomScriptUrl);
  102. }
  103. if (!this.options.callStatsConfIDNamespace) {
  104. logger.warn('"callStatsConfIDNamespace" is not defined');
  105. }
  106. }
  107. /**
  108. * Stores {@link CallStats} instances for each
  109. * {@link TraceablePeerConnection} (one {@link CallStats} instance serves
  110. * one TPC). The instances are mapped by {@link TraceablePeerConnection.id}.
  111. * @type {Map<number, CallStats>}
  112. */
  113. this.callsStatsInstances = new Map();
  114. Statistics.instances.add(this);
  115. }
  116. Statistics.audioLevelsEnabled = false;
  117. Statistics.audioLevelsInterval = 200;
  118. Statistics.disableThirdPartyRequests = false;
  119. Statistics.analytics = analytics;
  120. Object.defineProperty(Statistics, 'instances', {
  121. /**
  122. * Returns the Set holding all active {@link Statistics} instances. Lazily
  123. * initializes the Set to allow any Set polyfills to be applied.
  124. * @type {Set<Statistics>}
  125. */
  126. get() {
  127. if (!_instances) {
  128. _instances = new Set();
  129. }
  130. return _instances;
  131. }
  132. });
  133. /**
  134. * Starts collecting RTP stats for given peerconnection.
  135. * @param {TraceablePeerConnection} peerconnection
  136. */
  137. Statistics.prototype.startRemoteStats = function(peerconnection) {
  138. this.stopRemoteStats(peerconnection);
  139. try {
  140. const rtpStats
  141. = new RTPStats(
  142. peerconnection,
  143. Statistics.audioLevelsInterval,
  144. 2000,
  145. this.eventEmitter);
  146. rtpStats.start(Statistics.audioLevelsEnabled);
  147. this.rtpStatsMap.set(peerconnection.id, rtpStats);
  148. } catch (e) {
  149. logger.error(`Failed to start collecting remote statistics: ${e}`);
  150. }
  151. };
  152. Statistics.localStats = [];
  153. Statistics.startLocalStats = function(stream, callback) {
  154. if (!Statistics.audioLevelsEnabled) {
  155. return;
  156. }
  157. const localStats = new LocalStats(stream, Statistics.audioLevelsInterval,
  158. callback);
  159. this.localStats.push(localStats);
  160. localStats.start();
  161. };
  162. Statistics.prototype.addAudioLevelListener = function(listener) {
  163. if (!Statistics.audioLevelsEnabled) {
  164. return;
  165. }
  166. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  167. };
  168. Statistics.prototype.removeAudioLevelListener = function(listener) {
  169. if (!Statistics.audioLevelsEnabled) {
  170. return;
  171. }
  172. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  173. };
  174. Statistics.prototype.addBeforeDisposedListener = function(listener) {
  175. this.eventEmitter.on(StatisticsEvents.BEFORE_DISPOSED, listener);
  176. };
  177. Statistics.prototype.removeBeforeDisposedListener = function(listener) {
  178. this.eventEmitter.removeListener(
  179. StatisticsEvents.BEFORE_DISPOSED, listener);
  180. };
  181. Statistics.prototype.addConnectionStatsListener = function(listener) {
  182. this.eventEmitter.on(StatisticsEvents.CONNECTION_STATS, listener);
  183. };
  184. Statistics.prototype.removeConnectionStatsListener = function(listener) {
  185. this.eventEmitter.removeListener(
  186. StatisticsEvents.CONNECTION_STATS,
  187. listener);
  188. };
  189. Statistics.prototype.addByteSentStatsListener = function(listener) {
  190. this.eventEmitter.on(StatisticsEvents.BYTE_SENT_STATS, listener);
  191. };
  192. Statistics.prototype.removeByteSentStatsListener = function(listener) {
  193. this.eventEmitter.removeListener(StatisticsEvents.BYTE_SENT_STATS,
  194. listener);
  195. };
  196. Statistics.prototype.dispose = function() {
  197. try {
  198. // NOTE Before reading this please see the comment in stopCallStats...
  199. //
  200. // Here we prevent from emitting the event twice in case it will be
  201. // triggered from stopCallStats.
  202. // If the event is triggered from here it means that the logs will not
  203. // be submitted anyway (because there is no CallStats instance), but
  204. // we're doing that for the sake of some kind of consistency.
  205. if (!this.callsStatsInstances.size) {
  206. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  207. }
  208. for (const callStats of this.callsStatsInstances.values()) {
  209. this.stopCallStats(callStats.tpc);
  210. }
  211. for (const tpcId of this.rtpStatsMap.keys()) {
  212. this._stopRemoteStats(tpcId);
  213. }
  214. if (this.eventEmitter) {
  215. this.eventEmitter.removeAllListeners();
  216. }
  217. } finally {
  218. Statistics.instances.delete(this);
  219. }
  220. };
  221. Statistics.stopLocalStats = function(stream) {
  222. if (!Statistics.audioLevelsEnabled) {
  223. return;
  224. }
  225. for (let i = 0; i < Statistics.localStats.length; i++) {
  226. if (Statistics.localStats[i].stream === stream) {
  227. const localStats = Statistics.localStats.splice(i, 1);
  228. localStats[0].stop();
  229. break;
  230. }
  231. }
  232. };
  233. /**
  234. * Stops remote RTP stats for given peerconnection ID.
  235. * @param {string} tpcId {@link TraceablePeerConnection.id}
  236. * @private
  237. */
  238. Statistics.prototype._stopRemoteStats = function(tpcId) {
  239. const rtpStats = this.rtpStatsMap.get(tpcId);
  240. if (rtpStats) {
  241. rtpStats.stop();
  242. this.rtpStatsMap.delete(tpcId);
  243. }
  244. };
  245. /**
  246. * Stops collecting RTP stats for given peerconnection
  247. * @param {TraceablePeerConnection} tpc
  248. */
  249. Statistics.prototype.stopRemoteStats = function(tpc) {
  250. this._stopRemoteStats(tpc.id);
  251. };
  252. // CALSTATS METHODS
  253. /**
  254. * Initializes the callstats.io API.
  255. * @param {TraceablePeerConnection} tpc the {@link TraceablePeerConnection}
  256. * instance for which CalStats will be started.
  257. * @param {string} remoteUserID
  258. */
  259. Statistics.prototype.startCallStats = function(tpc, remoteUserID) {
  260. if (!this.callStatsIntegrationEnabled) {
  261. return;
  262. } else if (this.callsStatsInstances.has(tpc.id)) {
  263. logger.error('CallStats instance for ${tpc} exists already');
  264. return;
  265. }
  266. if (!CallStats.isBackendInitialized()) {
  267. const userName = Settings.callStatsUserName;
  268. if (!CallStats.initBackend({
  269. callStatsID: this.options.callStatsID,
  270. callStatsSecret: this.options.callStatsSecret,
  271. userName,
  272. aliasName: this.options.callStatsAliasName
  273. })) {
  274. // Backend initialization failed bad
  275. return;
  276. }
  277. }
  278. logger.info(`Starting CallStats for ${tpc}...`);
  279. const newInstance
  280. = new CallStats(
  281. tpc,
  282. {
  283. confID: this._getCallStatsConfID(),
  284. remoteUserID
  285. });
  286. this.callsStatsInstances.set(tpc.id, newInstance);
  287. };
  288. /**
  289. * Obtains the list of *all* {@link CallStats} instances collected from every
  290. * valid {@link Statistics} instance.
  291. * @return {Set<CallStats>}
  292. * @private
  293. */
  294. Statistics._getAllCallStatsInstances = function() {
  295. const csInstances = new Set();
  296. for (const statistics of Statistics.instances) {
  297. for (const cs of statistics.callsStatsInstances.values()) {
  298. csInstances.add(cs);
  299. }
  300. }
  301. return csInstances;
  302. };
  303. /**
  304. * Constructs the CallStats conference ID based on the options currently
  305. * configured in this instance.
  306. * @return {string}
  307. * @private
  308. */
  309. Statistics.prototype._getCallStatsConfID = function() {
  310. // The conference ID is case sensitive!!!
  311. return this.options.callStatsConfIDNamespace
  312. ? `${this.options.callStatsConfIDNamespace}/${this.options.roomName}`
  313. : this.options.roomName;
  314. };
  315. /**
  316. * Removes the callstats.io instances.
  317. */
  318. Statistics.prototype.stopCallStats = function(tpc) {
  319. const callStatsInstance = this.callsStatsInstances.get(tpc.id);
  320. if (callStatsInstance) {
  321. // FIXME the original purpose of adding BEFORE_DISPOSED event was to be
  322. // able to submit the last log batch from jitsi-meet to CallStats. After
  323. // recent changes we dispose the CallStats earlier
  324. // (before Statistics.dispose), so we need to emit this event here to
  325. // give this last chance for final log batch submission.
  326. //
  327. // Eventually there should be a separate module called "log storage"
  328. // which should emit proper events when it's underlying
  329. // CallStats instance is going away.
  330. if (this.callsStatsInstances.size === 1) {
  331. this.eventEmitter.emit(StatisticsEvents.BEFORE_DISPOSED);
  332. }
  333. this.callsStatsInstances.delete(tpc.id);
  334. // The fabric needs to be terminated when being stopped
  335. callStatsInstance.sendTerminateEvent();
  336. }
  337. };
  338. /**
  339. * Returns true if the callstats integration is enabled, otherwise returns
  340. * false.
  341. *
  342. * @returns true if the callstats integration is enabled, otherwise returns
  343. * false.
  344. */
  345. Statistics.prototype.isCallstatsEnabled = function() {
  346. return this.callStatsIntegrationEnabled;
  347. };
  348. /**
  349. * Logs either resume or hold event for the given peer connection.
  350. * @param {TraceablePeerConnection} tpc the connection for which event will be
  351. * reported
  352. * @param {boolean} isResume true for resume or false for hold
  353. */
  354. Statistics.prototype.sendConnectionResumeOrHoldEvent = function(tpc, isResume) {
  355. const instance = this.callsStatsInstances.get(tpc.id);
  356. if (instance) {
  357. instance.sendResumeOrHoldEvent(isResume);
  358. }
  359. };
  360. /**
  361. * Notifies CallStats and analytics(if present) for ice connection failed
  362. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  363. */
  364. Statistics.prototype.sendIceConnectionFailedEvent = function(tpc) {
  365. const instance = this.callsStatsInstances.get(tpc.id);
  366. if (instance) {
  367. instance.sendIceConnectionFailedEvent();
  368. }
  369. Statistics.analytics.sendEvent('connection.ice_failed');
  370. };
  371. /**
  372. * Notifies CallStats for mute events
  373. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  374. * @param {boolean} muted true for muted and false for not muted
  375. * @param {String} type "audio"/"video"
  376. */
  377. Statistics.prototype.sendMuteEvent = function(tpc, muted, type) {
  378. const instance = tpc && this.callsStatsInstances.get(tpc.id);
  379. CallStats.sendMuteEvent(muted, type, instance);
  380. };
  381. /**
  382. * Notifies CallStats for screen sharing events
  383. * @param start {boolean} true for starting screen sharing and
  384. * false for not stopping
  385. */
  386. Statistics.prototype.sendScreenSharingEvent = function(start) {
  387. for (const cs of this.callsStatsInstances.values()) {
  388. cs.sendScreenSharingEvent(start);
  389. }
  390. };
  391. /**
  392. * Notifies the statistics module that we are now the dominant speaker of the
  393. * conference.
  394. */
  395. Statistics.prototype.sendDominantSpeakerEvent = function() {
  396. for (const cs of this.callsStatsInstances.values()) {
  397. cs.sendDominantSpeakerEvent();
  398. }
  399. };
  400. /**
  401. * Notifies about active device.
  402. * @param {{deviceList: {String:String}}} devicesData - list of devices with
  403. * their data
  404. */
  405. Statistics.sendActiveDeviceListEvent = function(devicesData) {
  406. const globalSet = Statistics._getAllCallStatsInstances();
  407. if (globalSet.size) {
  408. for (const cs of globalSet) {
  409. CallStats.sendActiveDeviceListEvent(devicesData, cs);
  410. }
  411. } else {
  412. CallStats.sendActiveDeviceListEvent(devicesData, null);
  413. }
  414. };
  415. /* eslint-disable max-params */
  416. /**
  417. * Lets the underlying statistics module know where is given SSRC rendered by
  418. * providing renderer tag ID.
  419. * @param {TraceablePeerConnection} tpc the connection to which the stream
  420. * belongs to
  421. * @param {number} ssrc the SSRC of the stream
  422. * @param {boolean} isLocal
  423. * @param {string} userId
  424. * @param {string} usageLabel meaningful usage label of this stream like
  425. * 'microphone', 'camera' or 'screen'.
  426. * @param {string} containerId the id of media 'audio' or 'video' tag which
  427. * renders the stream.
  428. */
  429. Statistics.prototype.associateStreamWithVideoTag = function(
  430. tpc,
  431. ssrc,
  432. isLocal,
  433. userId,
  434. usageLabel,
  435. containerId) {
  436. const instance = this.callsStatsInstances.get(tpc.id);
  437. if (instance) {
  438. instance.associateStreamWithVideoTag(
  439. ssrc,
  440. isLocal,
  441. userId,
  442. usageLabel,
  443. containerId);
  444. }
  445. };
  446. /* eslint-enable max-params */
  447. /**
  448. * Notifies CallStats that getUserMedia failed.
  449. *
  450. * @param {Error} e error to send
  451. */
  452. Statistics.sendGetUserMediaFailed = function(e) {
  453. const error
  454. = e instanceof JitsiTrackError
  455. ? formatJitsiTrackErrorForCallStats(e) : e;
  456. const globalSet = Statistics._getAllCallStatsInstances();
  457. if (globalSet.size) {
  458. for (const cs of globalSet) {
  459. CallStats.sendGetUserMediaFailed(error, cs);
  460. }
  461. } else {
  462. CallStats.sendGetUserMediaFailed(error, null);
  463. }
  464. };
  465. /**
  466. * Notifies CallStats that peer connection failed to create offer.
  467. *
  468. * @param {Error} e error to send
  469. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  470. */
  471. Statistics.prototype.sendCreateOfferFailed = function(e, tpc) {
  472. const instance = this.callsStatsInstances.get(tpc.id);
  473. if (instance) {
  474. instance.sendCreateOfferFailed(e);
  475. }
  476. };
  477. /**
  478. * Notifies CallStats that peer connection failed to create answer.
  479. *
  480. * @param {Error} e error to send
  481. * @param {TraceablePeerConnection} tpc connection on which failure occured.
  482. */
  483. Statistics.prototype.sendCreateAnswerFailed = function(e, tpc) {
  484. const instance = this.callsStatsInstances.get(tpc.id);
  485. if (instance) {
  486. instance.sendCreateAnswerFailed(e);
  487. }
  488. };
  489. /**
  490. * Notifies CallStats that peer connection failed to set local description.
  491. *
  492. * @param {Error} e error to send
  493. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  494. */
  495. Statistics.prototype.sendSetLocalDescFailed = function(e, tpc) {
  496. const instance = this.callsStatsInstances.get(tpc.id);
  497. if (instance) {
  498. instance.sendSetLocalDescFailed(e);
  499. }
  500. };
  501. /**
  502. * Notifies CallStats that peer connection failed to set remote description.
  503. *
  504. * @param {Error} e error to send
  505. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  506. */
  507. Statistics.prototype.sendSetRemoteDescFailed = function(e, tpc) {
  508. const instance = this.callsStatsInstances.get(tpc.id);
  509. if (instance) {
  510. instance.sendSetRemoteDescFailed(e);
  511. }
  512. };
  513. /**
  514. * Notifies CallStats that peer connection failed to add ICE candidate.
  515. *
  516. * @param {Error} e error to send
  517. * @param {TraceablePeerConnection} tpc connection on which failure occurred.
  518. */
  519. Statistics.prototype.sendAddIceCandidateFailed = function(e, tpc) {
  520. const instance = this.callsStatsInstances.get(tpc.id);
  521. if (instance) {
  522. instance.sendAddIceCandidateFailed(e);
  523. }
  524. };
  525. /**
  526. * Adds to CallStats an application log.
  527. *
  528. * @param {String} m a log message to send or an {Error} object to be reported
  529. */
  530. Statistics.sendLog = function(m) {
  531. const globalSubSet = new Set();
  532. // FIXME we don't want to duplicate logs over P2P instance, but
  533. // here we should go over instances and call this method for each
  534. // unique conference ID rather than selecting the first one.
  535. // We don't have such use case though, so leaving as is for now.
  536. for (const stats of Statistics.instances) {
  537. if (stats.callsStatsInstances.size) {
  538. globalSubSet.add(stats.callsStatsInstances.values().next().value);
  539. }
  540. }
  541. if (globalSubSet.size) {
  542. for (const csPerStats of globalSubSet) {
  543. CallStats.sendApplicationLog(m, csPerStats);
  544. }
  545. } else {
  546. CallStats.sendApplicationLog(m, null);
  547. }
  548. };
  549. /**
  550. * Sends the given feedback through CallStats.
  551. *
  552. * @param overall an integer between 1 and 5 indicating the user feedback
  553. * @param detailed detailed feedback from the user. Not yet used
  554. */
  555. Statistics.prototype.sendFeedback = function(overall, detailed) {
  556. CallStats.sendFeedback(this._getCallStatsConfID(), overall, detailed);
  557. Statistics.analytics.sendEvent('feedback.rating',
  558. { value: overall,
  559. detailed });
  560. };
  561. Statistics.LOCAL_JID = require('../../service/statistics/constants').LOCAL_JID;
  562. /**
  563. * Reports global error to CallStats.
  564. *
  565. * @param {Error} error
  566. */
  567. Statistics.reportGlobalError = function(error) {
  568. if (error instanceof JitsiTrackError && error.gum) {
  569. Statistics.sendGetUserMediaFailed(error);
  570. } else {
  571. Statistics.sendLog(error);
  572. }
  573. };
  574. /**
  575. * Sends event to analytics and callstats.
  576. * @param {string} eventName the event name.
  577. * @param {Object} data the data to be sent.
  578. */
  579. Statistics.sendEventToAll = function(eventName, data) {
  580. this.analytics.sendEvent(eventName, data);
  581. Statistics.sendLog(JSON.stringify({ name: eventName,
  582. data }));
  583. };