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 19KB

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