/
TelemetrySession.jsm
executable file
·1371 lines (1207 loc) · 46 KB
/
TelemetrySession.jsm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
Cu.import("resource://gre/modules/debug.js", this);
Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://gre/modules/Services.jsm", this);
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
Cu.import("resource://gre/modules/Promise.jsm", this);
Cu.import("resource://gre/modules/DeferredTask.jsm", this);
Cu.import("resource://gre/modules/Preferences.jsm");
Cu.import("resource://gre/modules/Timer.jsm");
const IS_CONTENT_PROCESS = (function() {
// We cannot use Services.appinfo here because in telemetry xpcshell tests,
// appinfo is initially unavailable, and becomes available only later on.
let runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
return runtime.processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
})();
// When modifying the payload in incompatible ways, please bump this version number
const PAYLOAD_VERSION = 1;
const PING_TYPE_MAIN = "main";
const RETENTION_DAYS = 14;
const REASON_DAILY = "daily";
const REASON_SAVED_SESSION = "saved-session";
const REASON_IDLE_DAILY = "idle-daily";
const REASON_GATHER_PAYLOAD = "gather-payload";
const REASON_TEST_PING = "test-ping";
const SEC_IN_ONE_DAY = 24 * 60 * 60;
const MS_IN_ONE_DAY = SEC_IN_ONE_DAY * 1000;
const MIN_SUBSESSION_LENGTH_MS = 10 * 60 * 1000;
// This is the HG changeset of the Histogram.json file, used to associate
// submitted ping data with its histogram definition (bug 832007)
#expand const HISTOGRAMS_FILE_VERSION = "__HISTOGRAMS_FILE_VERSION__";
const LOGGER_NAME = "Toolkit.Telemetry";
const LOGGER_PREFIX = "TelemetrySession::";
const PREF_BRANCH = "toolkit.telemetry.";
const PREF_SERVER = PREF_BRANCH + "server";
const PREF_ENABLED = PREF_BRANCH + "enabled";
const PREF_PREVIOUS_BUILDID = PREF_BRANCH + "previousBuildID";
const PREF_CACHED_CLIENTID = PREF_BRANCH + "cachedClientID"
const PREF_FHR_UPLOAD_ENABLED = "datareporting.healthreport.uploadEnabled";
const PREF_ASYNC_PLUGIN_INIT = "dom.ipc.plugins.asyncInit";
const MESSAGE_TELEMETRY_PAYLOAD = "Telemetry:Payload";
// Do not gather data more than once a minute
const TELEMETRY_INTERVAL = 60000;
// Delay before intializing telemetry (ms)
const TELEMETRY_DELAY = 60000;
// Delay before initializing telemetry if we're testing (ms)
const TELEMETRY_TEST_DELAY = 100;
// Seconds of idle time before pinging.
// On idle-daily a gather-telemetry notification is fired, during it probes can
// start asynchronous tasks to gather data. On the next idle the data is sent.
const IDLE_TIMEOUT_SECONDS = 5 * 60;
var gLastMemoryPoll = null;
let gWasDebuggerAttached = false;
function getLocale() {
return Cc["@mozilla.org/chrome/chrome-registry;1"].
getService(Ci.nsIXULChromeRegistry).
getSelectedLocale('global');
}
XPCOMUtils.defineLazyServiceGetter(this, "Telemetry",
"@mozilla.org/base/telemetry;1",
"nsITelemetry");
XPCOMUtils.defineLazyServiceGetter(this, "idleService",
"@mozilla.org/widget/idleservice;1",
"nsIIdleService");
XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
"@mozilla.org/childprocessmessagemanager;1",
"nsIMessageSender");
XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
"@mozilla.org/parentprocessmessagemanager;1",
"nsIMessageListenerManager");
XPCOMUtils.defineLazyModuleGetter(this, "AddonManagerPrivate",
"resource://gre/modules/AddonManager.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
"resource://gre/modules/AsyncShutdown.jsm");
#ifndef MOZ_WIDGET_GONK
XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeManager",
"resource://gre/modules/LightweightThemeManager.jsm");
#endif
XPCOMUtils.defineLazyModuleGetter(this, "TelemetryPing",
"resource://gre/modules/TelemetryPing.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "TelemetryFile",
"resource://gre/modules/TelemetryFile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "TelemetryLog",
"resource://gre/modules/TelemetryLog.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ThirdPartyCookieProbe",
"resource://gre/modules/ThirdPartyCookieProbe.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "UITelemetry",
"resource://gre/modules/UITelemetry.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "UpdateChannel",
"resource://gre/modules/UpdateChannel.jsm");
function generateUUID() {
let str = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator).generateUUID().toString();
// strip {}
return str.substring(1, str.length - 1);
}
/**
* This is a policy object used to override behavior for testing.
*/
let Policy = {
now: () => new Date(),
setDailyTimeout: (callback, delayMs) => setTimeout(callback, delayMs),
clearDailyTimeout: (id) => clearTimeout(id),
};
/**
* Takes a date and returns it trunctated to a date with daily precision.
*/
function truncateToDays(date) {
return new Date(date.getFullYear(),
date.getMonth(),
date.getDate(),
0, 0, 0, 0);
}
/**
* Date.toISOString() gives us UTC times, this gives us local times in the ISO date format.
* http://www.w3.org/TR/NOTE-datetime
*/
function toLocalTimeISOString(date) {
function padNumber(number, places) {
number = number.toString();
while (number.length < places) {
number = "0" + number;
}
return number;
}
let sign = (n) => n >= 0 ? "+" : "-";
let tzOffset = date.getTimezoneOffset();
// YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
return padNumber(date.getFullYear(), 4)
+ "-" + padNumber(date.getMonth() + 1, 2)
+ "-" + padNumber(date.getDate(), 2)
+ "T" + padNumber(date.getHours(), 2)
+ ":" + padNumber(date.getMinutes(), 2)
+ ":" + padNumber(date.getSeconds(), 2);
+ "." + date.getMilliseconds()
+ sign(tzOffset) + Math.abs(Math.floor(tzOffset / 60))
+ ":" + Math.abs(tzOffset % 60);
}
/**
* Read current process I/O counters.
*/
let processInfo = {
_initialized: false,
_IO_COUNTERS: null,
_kernel32: null,
_GetProcessIoCounters: null,
_GetCurrentProcess: null,
getCounters: function() {
let isWindows = ("@mozilla.org/windows-registry-key;1" in Components.classes);
if (isWindows)
return this.getCounters_Windows();
return null;
},
getCounters_Windows: function() {
if (!this._initialized){
Cu.import("resource://gre/modules/ctypes.jsm");
this._IO_COUNTERS = new ctypes.StructType("IO_COUNTERS", [
{'readOps': ctypes.unsigned_long_long},
{'writeOps': ctypes.unsigned_long_long},
{'otherOps': ctypes.unsigned_long_long},
{'readBytes': ctypes.unsigned_long_long},
{'writeBytes': ctypes.unsigned_long_long},
{'otherBytes': ctypes.unsigned_long_long} ]);
try {
this._kernel32 = ctypes.open("Kernel32.dll");
this._GetProcessIoCounters = this._kernel32.declare("GetProcessIoCounters",
ctypes.winapi_abi,
ctypes.bool, // return
ctypes.voidptr_t, // hProcess
this._IO_COUNTERS.ptr); // lpIoCounters
this._GetCurrentProcess = this._kernel32.declare("GetCurrentProcess",
ctypes.winapi_abi,
ctypes.voidptr_t); // return
this._initialized = true;
} catch (err) {
return null;
}
}
let io = new this._IO_COUNTERS();
if(!this._GetProcessIoCounters(this._GetCurrentProcess(), io.address()))
return null;
return [parseInt(io.readBytes), parseInt(io.writeBytes)];
}
};
this.EXPORTED_SYMBOLS = ["TelemetrySession"];
this.TelemetrySession = Object.freeze({
Constants: Object.freeze({
PREF_ENABLED: PREF_ENABLED,
PREF_SERVER: PREF_SERVER,
PREF_PREVIOUS_BUILDID: PREF_PREVIOUS_BUILDID,
}),
/**
* Send a ping to a test server. Used only for testing.
*/
testPing: function() {
return Impl.testPing();
},
/**
* Returns the current telemetry payload.
* @param reason Optional, the reason to trigger the payload.
* @param clearSubsession Optional, whether to clear subsession specific data.
* @returns Object
*/
getPayload: function(reason, clearSubsession = false) {
return Impl.getPayload(reason, clearSubsession);
},
/**
* Save histograms to a file.
* Used only for testing purposes.
*
* @param {nsIFile} aFile The file to load from.
*/
testSaveHistograms: function(aFile) {
return Impl.testSaveHistograms(aFile);
},
/**
* Collect and store information about startup.
*/
gatherStartup: function() {
return Impl.gatherStartup();
},
/**
* Inform the ping which AddOns are installed.
*
* @param aAddOns - The AddOns.
*/
setAddOns: function(aAddOns) {
return Impl.setAddOns(aAddOns);
},
/**
* Descriptive metadata
*
* @param reason
* The reason for the telemetry ping, this will be included in the
* returned metadata,
* @return The metadata as a JS object
*/
getMetadata: function(reason) {
return Impl.getMetadata(reason);
},
/**
* Used only for testing purposes.
*/
reset: function() {
this.uninstall();
return this.setup();
},
/**
* Used only for testing purposes.
* @param {Boolean} [aForceSavePending=true] If true, always saves the ping whether Telemetry
* can send pings or not, which is used for testing.
*/
shutdown: function(aForceSavePending = true) {
return Impl.shutdown(aForceSavePending);
},
/**
* Used only for testing purposes.
*/
setup: function() {
return Impl.setupChromeProcess(true);
},
/**
* Used only for testing purposes.
*/
uninstall: function() {
try {
Impl.uninstall();
} catch (ex) {
// Ignore errors
}
},
/**
* Send a notification.
*/
observe: function (aSubject, aTopic, aData) {
return Impl.observe(aSubject, aTopic, aData);
},
/**
* The client id send with the telemetry ping.
*
* @return The client id as string, or null.
*/
get clientID() {
return Impl.clientID;
},
});
let Impl = {
_histograms: {},
_initialized: false,
_log: null,
_prevValues: {},
// Generate a unique id once per session so the server can cope with
// duplicate submissions.
_uuid: generateUUID(),
// Regex that matches histograms we care about during startup.
// Keep this in sync with gen-histogram-bucket-ranges.py.
_startupHistogramRegex: /SQLITE|HTTP|SPDY|CACHE|DNS/,
_slowSQLStartup: {},
_prevSession: null,
_hasWindowRestoredObserver: false,
_hasXulWindowVisibleObserver: false,
_startupIO : {},
// The previous build ID, if this is the first run with a new build.
// Undefined if this is not the first run, or the previous build ID is unknown.
_previousBuildID: undefined,
// Telemetry payloads sent by child processes.
// Each element is in the format {source: <weak-ref>, payload: <object>},
// where source is a weak reference to the child process,
// and payload is the telemetry payload from that child process.
_childTelemetry: [],
// Date of the last session split
_subsessionStartDate: null,
// The timer used for daily collections.
_dailyTimerId: null,
/**
* Gets a series of simple measurements (counters). At the moment, this
* only returns startup data from nsIAppStartup.getStartupInfo().
*
* @return simple measurements as a dictionary.
*/
getSimpleMeasurements: function getSimpleMeasurements(forSavedSession) {
this._log.trace("getSimpleMeasurements");
let si = Services.startup.getStartupInfo();
// Measurements common to chrome and content processes.
var ret = {
// uptime in minutes
uptime: Math.round((new Date() - si.process) / 60000)
}
// Look for app-specific timestamps
var appTimestamps = {};
try {
let o = {};
Cu.import("resource://gre/modules/TelemetryTimestamps.jsm", o);
appTimestamps = o.TelemetryTimestamps.get();
} catch (ex) {}
try {
if (!IS_CONTENT_PROCESS) {
ret.addonManager = AddonManagerPrivate.getSimpleMeasures();
}
} catch (ex) {}
try {
if (!IS_CONTENT_PROCESS) {
ret.UITelemetry = UITelemetry.getSimpleMeasures();
}
} catch (ex) {}
if (si.process) {
for each (let field in Object.keys(si)) {
if (field == "process")
continue;
ret[field] = si[field] - si.process
}
for (let p in appTimestamps) {
if (!(p in ret) && appTimestamps[p])
ret[p] = appTimestamps[p] - si.process;
}
}
ret.startupInterrupted = Number(Services.startup.interrupted);
ret.js = Cu.getJSEngineTelemetryValue();
let maximalNumberOfConcurrentThreads = Telemetry.maximalNumberOfConcurrentThreads;
if (maximalNumberOfConcurrentThreads) {
ret.maximalNumberOfConcurrentThreads = maximalNumberOfConcurrentThreads;
}
if (IS_CONTENT_PROCESS) {
return ret;
}
// Measurements specific to chrome process
// Update debuggerAttached flag
let debugService = Cc["@mozilla.org/xpcom/debug;1"].getService(Ci.nsIDebug2);
let isDebuggerAttached = debugService.isDebuggerAttached;
gWasDebuggerAttached = gWasDebuggerAttached || isDebuggerAttached;
ret.debuggerAttached = Number(gWasDebuggerAttached);
let shutdownDuration = Telemetry.lastShutdownDuration;
if (shutdownDuration)
ret.shutdownDuration = shutdownDuration;
let failedProfileLockCount = Telemetry.failedProfileLockCount;
if (failedProfileLockCount)
ret.failedProfileLockCount = failedProfileLockCount;
for (let ioCounter in this._startupIO)
ret[ioCounter] = this._startupIO[ioCounter];
let hasPingBeenSent = false;
try {
hasPingBeenSent = Telemetry.getHistogramById("TELEMETRY_SUCCESS").snapshot().sum > 0;
} catch(e) {
}
if (!forSavedSession || hasPingBeenSent) {
ret.savedPings = TelemetryFile.pingsLoaded;
}
ret.activeTicks = -1;
if ("@mozilla.org/datareporting/service;1" in Cc) {
let drs = Cc["@mozilla.org/datareporting/service;1"]
.getService(Ci.nsISupports)
.wrappedJSObject;
let sr = drs.getSessionRecorder();
if (sr) {
ret.activeTicks = sr.activeTicks;
}
}
ret.pingsOverdue = TelemetryFile.pingsOverdue;
ret.pingsDiscarded = TelemetryFile.pingsDiscarded;
return ret;
},
/**
* When reflecting a histogram into JS, Telemetry hands us an object
* with the following properties:
*
* - min, max, histogram_type, sum, sum_squares_{lo,hi}: simple integers;
* - log_sum, log_sum_squares: doubles;
* - counts: array of counts for histogram buckets;
* - ranges: array of calculated bucket sizes.
*
* This format is not straightforward to read and potentially bulky
* with lots of zeros in the counts array. Packing histograms makes
* raw histograms easier to read and compresses the data a little bit.
*
* Returns an object:
* { range: [min, max], bucket_count: <number of buckets>,
* histogram_type: <histogram_type>, sum: <sum>,
* sum_squares_lo: <sum_squares_lo>,
* sum_squares_hi: <sum_squares_hi>,
* log_sum: <log_sum>, log_sum_squares: <log_sum_squares>,
* values: { bucket1: count1, bucket2: count2, ... } }
*/
packHistogram: function packHistogram(hgram) {
let r = hgram.ranges;;
let c = hgram.counts;
let retgram = {
range: [r[1], r[r.length - 1]],
bucket_count: r.length,
histogram_type: hgram.histogram_type,
values: {},
sum: hgram.sum
};
if (hgram.histogram_type == Telemetry.HISTOGRAM_EXPONENTIAL) {
retgram.log_sum = hgram.log_sum;
retgram.log_sum_squares = hgram.log_sum_squares;
} else {
retgram.sum_squares_lo = hgram.sum_squares_lo;
retgram.sum_squares_hi = hgram.sum_squares_hi;
}
let first = true;
let last = 0;
for (let i = 0; i < c.length; i++) {
let value = c[i];
if (!value)
continue;
// add a lower bound
if (i && first) {
retgram.values[r[i - 1]] = 0;
}
first = false;
last = i + 1;
retgram.values[r[i]] = value;
}
// add an upper bound
if (last && last < c.length)
retgram.values[r[last]] = 0;
return retgram;
},
getHistograms: function getHistograms(subsession, clearSubsession) {
this._log.trace("getHistograms - subsession: " + subsession + ", clearSubsession: " + clearSubsession);
let registered =
Telemetry.registeredHistograms(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, []);
let hls = subsession ? Telemetry.snapshotSubsessionHistograms(clearSubsession)
: Telemetry.histogramSnapshots;
let ret = {};
for (let name of registered) {
for (let n of [name, "STARTUP_" + name]) {
if (n in hls) {
ret[n] = this.packHistogram(hls[n]);
}
}
}
return ret;
},
getAddonHistograms: function getAddonHistograms() {
this._log.trace("getAddonHistograms");
let ahs = Telemetry.addonHistogramSnapshots;
let ret = {};
for (let addonName in ahs) {
let addonHistograms = ahs[addonName];
let packedHistograms = {};
for (let name in addonHistograms) {
packedHistograms[name] = this.packHistogram(addonHistograms[name]);
}
if (Object.keys(packedHistograms).length != 0)
ret[addonName] = packedHistograms;
}
return ret;
},
getKeyedHistograms: function(subsession, clearSubsession) {
this._log.trace("getKeyedHistograms - subsession: " + subsession + ", clearSubsession: " + clearSubsession);
let registered =
Telemetry.registeredKeyedHistograms(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, []);
let ret = {};
for (let id of registered) {
ret[id] = {};
let keyed = Telemetry.getKeyedHistogramById(id);
let snapshot = null;
if (subsession) {
snapshot = clearSubsession ? keyed.snapshotSubsessionAndClear()
: keyed.subsessionSnapshot();
} else {
snapshot = keyed.snapshot();
}
for (let key of Object.keys(snapshot)) {
ret[id][key] = this.packHistogram(snapshot[key]);
}
}
return ret;
},
/**
* Descriptive metadata
*
* @param reason
* The reason for the telemetry ping, this will be included in the
* returned metadata,
* @return The metadata as a JS object
*/
getMetadata: function getMetadata(reason) {
this._log.trace("getMetadata - Reason " + reason);
let subsessionStartDate = toLocalTimeISOString(truncateToDays(this._subsessionStartDate));
let ai = Services.appinfo;
let ret = {
reason: reason,
OS: ai.OS,
appID: ai.ID,
appVersion: ai.version,
appName: ai.name,
appBuildID: ai.appBuildID,
appUpdateChannel: UpdateChannel.get(),
platformBuildID: ai.platformBuildID,
revision: HISTOGRAMS_FILE_VERSION,
locale: getLocale(),
asyncPluginInit: Preferences.get(PREF_ASYNC_PLUGIN_INIT, false)
subsessionStartDate: subsessionStartDate,
};
// In order to share profile data, the appName used for Metro Firefox is "Firefox",
// (the same as desktop Firefox). We set it to "MetroFirefox" here in order to
// differentiate telemetry pings sent by desktop vs. metro Firefox.
if(Services.metro && Services.metro.immersive) {
ret.appName = "MetroFirefox";
}
if (this._previousBuildID) {
ret.previousBuildID = this._previousBuildID;
}
// sysinfo fields are not always available, get what we can.
let sysInfo = Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2);
let fields = ["cpucount", "memsize", "arch", "version", "kernel_version",
"device", "manufacturer", "hardware", "tablet",
"hasMMX", "hasSSE", "hasSSE2", "hasSSE3",
"hasSSSE3", "hasSSE4A", "hasSSE4_1", "hasSSE4_2",
"hasEDSP", "hasARMv6", "hasARMv7", "hasNEON", "isWow64",
"profileHDDModel", "profileHDDRevision", "binHDDModel",
"binHDDRevision", "winHDDModel", "winHDDRevision"];
for each (let field in fields) {
let value;
try {
value = sysInfo.getProperty(field);
} catch (e) {
continue;
}
if (field == "memsize") {
// Send RAM size in megabytes. Rounding because sysinfo doesn't
// always provide RAM in multiples of 1024.
value = Math.round(value / 1024 / 1024);
}
ret[field] = value;
}
// gfxInfo fields are not always available, get what we can.
let gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo);
let gfxfields = ["adapterDescription", "adapterVendorID", "adapterDeviceID",
"adapterSubsysID", "adapterRAM", "adapterDriver",
"adapterDriverVersion", "adapterDriverDate",
"adapterDescription2", "adapterVendorID2",
"adapterDeviceID2", "adapterSubsysID2", "adapterRAM2",
"adapterDriver2", "adapterDriverVersion2",
"adapterDriverDate2", "isGPU2Active", "D2DEnabled",
"DWriteEnabled", "DWriteVersion"
];
if (gfxInfo) {
for each (let field in gfxfields) {
try {
let value = gfxInfo[field];
// bug 940806: We need to do a strict equality comparison here,
// otherwise a type conversion will occur and boolean false values
// will get filtered out
if (value !== "") {
ret[field] = value;
}
} catch (e) {
continue
}
}
}
#ifndef MOZ_WIDGET_GONK
let theme = LightweightThemeManager.currentTheme;
if (theme) {
ret.persona = theme.id;
}
#endif
if (this._addons)
ret.addons = this._addons;
let flashVersion = this.getFlashVersion();
if (flashVersion)
ret.flashVersion = flashVersion;
try {
let scope = {};
Cu.import("resource:///modules/experiments/Experiments.jsm", scope);
let experiments = scope.Experiments.instance()
let activeExperiment = experiments.getActiveExperimentID();
if (activeExperiment) {
ret.activeExperiment = activeExperiment;
ret.activeExperimentBranch = experiments.getActiveExperimentBranch();
}
} catch(e) {
// If this is not Firefox, the import will fail.
}
return ret;
},
/**
* Pull values from about:memory into corresponding histograms
*/
gatherMemory: function gatherMemory() {
this._log.trace("gatherMemory");
let mgr;
try {
mgr = Cc["@mozilla.org/memory-reporter-manager;1"].
getService(Ci.nsIMemoryReporterManager);
} catch (e) {
// OK to skip memory reporters in xpcshell
return;
}
let histogram = Telemetry.getHistogramById("TELEMETRY_MEMORY_REPORTER_MS");
let startTime = new Date();
// Get memory measurements from distinguished amount attributes. We used
// to measure "explicit" too, but it could cause hangs, and the data was
// always really noisy anyway. See bug 859657.
//
// test_TelemetryPing.js relies on some of these histograms being
// here. If you remove any of the following histograms from here, you'll
// have to modify test_TelemetryPing.js:
//
// * MEMORY_JS_GC_HEAP, and
// * MEMORY_JS_COMPARTMENTS_SYSTEM.
//
// The distinguished amount attribute names don't match the telemetry id
// names in some cases due to a combination of (a) historical reasons, and
// (b) the fact that we can't change telemetry id names without breaking
// data continuity.
//
let boundHandleMemoryReport = this.handleMemoryReport.bind(this);
function h(id, units, amountName) {
try {
// If mgr[amountName] throws an exception, just move on -- some amounts
// aren't available on all platforms. But if the attribute simply
// isn't present, that indicates the distinguished amounts have changed
// and this file hasn't been updated appropriately.
let amount = mgr[amountName];
NS_ASSERT(amount !== undefined,
"telemetry accessed an unknown distinguished amount");
boundHandleMemoryReport(id, units, amount);
} catch (e) {
};
}
let b = (id, n) => h(id, Ci.nsIMemoryReporter.UNITS_BYTES, n);
let c = (id, n) => h(id, Ci.nsIMemoryReporter.UNITS_COUNT, n);
let cc= (id, n) => h(id, Ci.nsIMemoryReporter.UNITS_COUNT_CUMULATIVE, n);
let p = (id, n) => h(id, Ci.nsIMemoryReporter.UNITS_PERCENTAGE, n);
b("MEMORY_VSIZE", "vsize");
b("MEMORY_VSIZE_MAX_CONTIGUOUS", "vsizeMaxContiguous");
b("MEMORY_RESIDENT", "residentFast");
b("MEMORY_HEAP_ALLOCATED", "heapAllocated");
p("MEMORY_HEAP_COMMITTED_UNUSED_RATIO", "heapOverheadRatio");
b("MEMORY_JS_GC_HEAP", "JSMainRuntimeGCHeap");
b("MEMORY_JS_MAIN_RUNTIME_TEMPORARY_PEAK", "JSMainRuntimeTemporaryPeak");
c("MEMORY_JS_COMPARTMENTS_SYSTEM", "JSMainRuntimeCompartmentsSystem");
c("MEMORY_JS_COMPARTMENTS_USER", "JSMainRuntimeCompartmentsUser");
b("MEMORY_IMAGES_CONTENT_USED_UNCOMPRESSED", "imagesContentUsedUncompressed");
b("MEMORY_STORAGE_SQLITE", "storageSQLite");
cc("MEMORY_EVENTS_VIRTUAL", "lowMemoryEventsVirtual");
cc("MEMORY_EVENTS_PHYSICAL", "lowMemoryEventsPhysical");
c("GHOST_WINDOWS", "ghostWindows");
cc("PAGE_FAULTS_HARD", "pageFaultsHard");
histogram.add(new Date() - startTime);
},
handleMemoryReport: function(id, units, amount) {
let val;
if (units == Ci.nsIMemoryReporter.UNITS_BYTES) {
val = Math.floor(amount / 1024);
}
else if (units == Ci.nsIMemoryReporter.UNITS_PERCENTAGE) {
// UNITS_PERCENTAGE amounts are 100x greater than their raw value.
val = Math.floor(amount / 100);
}
else if (units == Ci.nsIMemoryReporter.UNITS_COUNT) {
val = amount;
}
else if (units == Ci.nsIMemoryReporter.UNITS_COUNT_CUMULATIVE) {
// If the reporter gives us a cumulative count, we'll report the
// difference in its value between now and our previous ping.
if (!(id in this._prevValues)) {
// If this is the first time we're reading this reporter, store its
// current value but don't report it in the telemetry ping, so we
// ignore the effect startup had on the reporter.
this._prevValues[id] = amount;
return;
}
val = amount - this._prevValues[id];
this._prevValues[id] = amount;
}
else {
NS_ASSERT(false, "Can't handle memory reporter with units " + units);
return;
}
let h = this._histograms[id];
if (!h) {
h = Telemetry.getHistogramById(id);
this._histograms[id] = h;
}
h.add(val);
},
/**
* Return true if we're interested in having a STARTUP_* histogram for
* the given histogram name.
*/
isInterestingStartupHistogram: function isInterestingStartupHistogram(name) {
return this._startupHistogramRegex.test(name);
},
getChildPayloads: function getChildPayloads() {
return [for (child of this._childTelemetry) child.payload];
},
/**
* Make a copy of interesting histograms at startup.
*/
gatherStartupHistograms: function gatherStartupHistograms() {
this._log.trace("gatherStartupHistograms");
let info =
Telemetry.registeredHistograms(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, []);
let snapshots = Telemetry.histogramSnapshots;
for (let name of info) {
// Only duplicate histograms with actual data.
if (this.isInterestingStartupHistogram(name) && name in snapshots) {
Telemetry.histogramFrom("STARTUP_" + name, name);
}
}
},
/**
* Get the current session's payload using the provided
* simpleMeasurements and info, which are typically obtained by a call
* to |this.getSimpleMeasurements| and |this.getMetadata|,
* respectively.
*/
assemblePayloadWithMeasurements: function(simpleMeasurements, info, reason, clearSubsession) {
const isSubsession = !this._isClassicReason(reason);
this._log.trace("assemblePayloadWithMeasurements - reason: " + reason +
", submitting subsession data: " + isSubsession);
// Payload common to chrome and content processes.
let payloadObj = {
ver: PAYLOAD_VERSION,
simpleMeasurements: simpleMeasurements,
histograms: this.getHistograms(isSubsession, clearSubsession),
keyedHistograms: this.getKeyedHistograms(isSubsession, clearSubsession),
chromeHangs: Telemetry.chromeHangs,
log: TelemetryLog.entries(),
};
if (IS_CONTENT_PROCESS) {
return payloadObj;
}
// Additional payload for chrome process.
payloadObj.info = info;
payloadObj.slowSQL = Telemetry.slowSQL;
payloadObj.fileIOReports = Telemetry.fileIOReports;
payloadObj.lateWrites = Telemetry.lateWrites;
payloadObj.addonHistograms = this.getAddonHistograms();
payloadObj.addonDetails = AddonManagerPrivate.getTelemetryDetails();
payloadObj.UIMeasurements = UITelemetry.getUIMeasurements();
if (Object.keys(this._slowSQLStartup).length != 0 &&
(Object.keys(this._slowSQLStartup.mainThread).length ||
Object.keys(this._slowSQLStartup.otherThreads).length)) {
payloadObj.slowSQLStartup = this._slowSQLStartup;
}
let clientID = TelemetryPing.clientID;
if (clientID && Preferences.get(PREF_FHR_UPLOAD_ENABLED, false)) {
payloadObj.clientID = clientID;
}
if (this._childTelemetry.length) {
payloadObj.childPayloads = this.getChildPayloads();
}
return payloadObj;
},
getSessionPayload: function getSessionPayload(reason, clearSubsession) {
this._log.trace("getSessionPayload - reason: " + reason + ", clearSubsession: " + clearSubsession);
let measurements = this.getSimpleMeasurements(reason == REASON_SAVED_SESSION);
let info = !IS_CONTENT_PROCESS ? this.getMetadata(reason) : null;
let payload = this.assemblePayloadWithMeasurements(measurements, info, reason, clearSubsession);
if (clearSubsession) {
this._subsessionStartDate = Policy.now();
this._rescheduleDailyTimer();
}
return payload;
},
/**
* Send data to the server. Record success/send-time in histograms
*/
send: function send(reason) {
this._log.trace("send - Reason " + reason);
// populate histograms one last time
this.gatherMemory();
const isSubsession = !this._isClassicReason(reason);
let payload = this.getSessionPayload(reason, isSubsession);
let options = {
retentionDays: RETENTION_DAYS,
addClientId: true,
addEnvironment: true,
};
return TelemetryPing.send(PING_TYPE_MAIN, payload, options);
},
attachObservers: function attachObservers() {
if (!this._initialized)
return;
Services.obs.addObserver(this, "cycle-collector-begin", false);
Services.obs.addObserver(this, "idle-daily", false);
},
detachObservers: function detachObservers() {
if (!this._initialized)
return;
Services.obs.removeObserver(this, "idle-daily");
Services.obs.removeObserver(this, "cycle-collector-begin");
if (this._isIdleObserver) {
idleService.removeIdleObserver(this, IDLE_TIMEOUT_SECONDS);
this._isIdleObserver = false;
}
},
/**
* Perform telemetry initialization for either chrome or content process.
*/
enableTelemetryRecording: function enableTelemetryRecording(testing) {
#ifdef MOZILLA_OFFICIAL
if (!Telemetry.canSend && !testing) {
// We can't send data; no point in initializing observers etc.
// Only do this for official builds so that e.g. developer builds
// still enable Telemetry based on prefs.
Telemetry.canRecord = false;
this._log.config("enableTelemetryRecording - Can't send data, disabling Telemetry recording.");
return false;
}
#endif
let enabled = Preferences.get(PREF_ENABLED, false);
this._server = Preferences.get(PREF_SERVER, undefined);
if (!enabled) {
// Turn off local telemetry if telemetry is disabled.
// This may change once about:telemetry is added.
Telemetry.canRecord = false;
this._log.config("enableTelemetryRecording - Telemetry is disabled, turning off Telemetry recording.");
return false;
}
return true;
},
/**
* Initializes telemetry within a timer. If there is no PREF_SERVER set, don't turn on telemetry.
*/
setupChromeProcess: function setupChromeProcess(testing) {
if (testing && !this._log) {
this._log = Log.repository.getLoggerWithMessagePrefix(LOGGER_NAME, LOGGER_PREFIX);
}
this._log.trace("setupChromeProcess");
this._sessionStartDate = Policy.now();
this._subsessionStartDate = this._sessionStartDate;
// Initialize some probes that are kept in their own modules
this._thirdPartyCookies = new ThirdPartyCookieProbe();
this._thirdPartyCookies.init();
// Record old value and update build ID preference if this is the first
// run with a new build ID.
let previousBuildID = Preferences.get(PREF_PREVIOUS_BUILDID, undefined);