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

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