Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

statistics.js 20KB

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