Source code

Revision control

Other Tools

1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
* License, v. 2.0. If a copy of the MPL was not distributed with this
3
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5
"use strict";
6
7
var EXPORTED_SYMBOLS = ["ProfileAge"];
8
9
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
10
const { TelemetryUtils } = ChromeUtils.import(
12
);
13
const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm");
14
const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm");
15
const { CommonUtils } = ChromeUtils.import(
17
);
18
19
const FILE_TIMES = "times.json";
20
21
/**
22
* Calculate how many days passed between two dates.
23
* @param {Object} aStartDate The starting date.
24
* @param {Object} aEndDate The ending date.
25
* @return {Integer} The number of days between the two dates.
26
*/
27
function getElapsedTimeInDays(aStartDate, aEndDate) {
28
return TelemetryUtils.millisecondsToDays(aEndDate - aStartDate);
29
}
30
31
/**
32
* Traverse the contents of the profile directory, finding the oldest file
33
* and returning its creation timestamp.
34
*/
35
async function getOldestProfileTimestamp(profilePath, log) {
36
let start = Date.now();
37
let oldest = start + 1000;
38
let iterator = new OS.File.DirectoryIterator(profilePath);
39
log.debug("Iterating over profile " + profilePath);
40
if (!iterator) {
41
throw new Error(
42
"Unable to fetch oldest profile entry: no profile iterator."
43
);
44
}
45
46
Services.telemetry.scalarAdd("telemetry.profile_directory_scans", 1);
47
let histogram = Services.telemetry.getHistogramById(
48
"PROFILE_DIRECTORY_FILE_AGE"
49
);
50
51
try {
52
await iterator.forEach(async entry => {
53
try {
54
let info = await OS.File.stat(entry.path);
55
56
// OS.File doesn't seem to be behaving. See Bug 827148.
57
// Let's do the best we can. This whole function is defensive.
58
let date = info.winBirthDate || info.macBirthDate;
59
if (!date || !date.getTime()) {
60
// OS.File will only return file creation times of any kind on Mac
61
// and Windows, where birthTime is defined.
62
// That means we're unable to function on Linux, so we use mtime
63
// instead.
64
log.debug("No birth date. Using mtime.");
65
date = info.lastModificationDate;
66
}
67
68
if (date) {
69
let timestamp = date.getTime();
70
// Get the age relative to now.
71
// We don't care about dates in the future.
72
let age_in_days = Math.max(0, getElapsedTimeInDays(timestamp, start));
73
histogram.add(age_in_days);
74
75
log.debug("Using date: " + entry.path + " = " + date);
76
if (timestamp < oldest) {
77
oldest = timestamp;
78
}
79
}
80
} catch (e) {
81
// Never mind.
82
log.debug("Stat failure", e);
83
}
84
});
85
} catch (reason) {
86
throw new Error("Unable to fetch oldest profile entry: " + reason);
87
} finally {
88
iterator.close();
89
}
90
91
return oldest;
92
}
93
94
/**
95
* Profile access to times.json (eg, creation/reset time).
96
* This is separate from the provider to simplify testing and enable extraction
97
* to a shared location in the future.
98
*/
99
class ProfileAgeImpl {
100
constructor(profile, times) {
101
this.profilePath = profile || OS.Constants.Path.profileDir;
102
this._times = times;
103
this._log = Log.repository.getLogger("Toolkit.ProfileAge");
104
105
if ("firstUse" in this._times && this._times.firstUse === null) {
106
// Indicates that this is a new profile that needs a first use timestamp.
107
this._times.firstUse = Date.now();
108
this.writeTimes();
109
}
110
}
111
112
/**
113
* There are two ways we can get our creation time:
114
*
115
* 1. From the on-disk JSON file.
116
* 2. By calculating it from the filesystem.
117
*
118
* If we have to calculate, we write out the file; if we have
119
* to touch the file, we persist in-memory.
120
*
121
* @return a promise that resolves to the profile's creation time.
122
*/
123
get created() {
124
// This can be an expensive operation so make sure we only do it once.
125
if (this._created) {
126
return this._created;
127
}
128
129
if (!this._times.created) {
130
this._created = this.computeAndPersistCreated();
131
} else {
132
this._created = Promise.resolve(this._times.created);
133
}
134
135
return this._created;
136
}
137
138
/**
139
* Returns a promise to the time of first use of the profile. This may be
140
* undefined if the first use time is unknown.
141
*/
142
get firstUse() {
143
if ("firstUse" in this._times) {
144
return Promise.resolve(this._times.firstUse);
145
}
146
return Promise.resolve(undefined);
147
}
148
149
/**
150
* Return a promise representing the writing the current times to the profile.
151
*/
152
writeTimes() {
153
return CommonUtils.writeJSON(
154
this._times,
155
OS.Path.join(this.profilePath, FILE_TIMES)
156
);
157
}
158
159
/**
160
* Calculates the created time by scanning the profile directory, sets it in
161
* the current set of times and persists it to the profile. Returns a promise
162
* that resolves when all of that is complete.
163
*/
164
async computeAndPersistCreated() {
165
let oldest = await getOldestProfileTimestamp(this.profilePath, this._log);
166
this._times.created = oldest;
167
Services.telemetry.scalarSet(
168
"telemetry.profile_directory_scan_date",
169
TelemetryUtils.millisecondsToDays(Date.now())
170
);
171
await this.writeTimes();
172
return oldest;
173
}
174
175
/**
176
* Record (and persist) when a profile reset happened. We just store a
177
* single value - the timestamp of the most recent reset - but there is scope
178
* to keep a list of reset times should our health-reporter successor
179
* be able to make use of that.
180
* Returns a promise that is resolved once the file has been written.
181
*/
182
recordProfileReset(time = Date.now()) {
183
this._times.reset = time;
184
return this.writeTimes();
185
}
186
187
/* Returns a promise that resolves to the time the profile was reset,
188
* or undefined if not recorded.
189
*/
190
get reset() {
191
if ("reset" in this._times) {
192
return Promise.resolve(this._times.reset);
193
}
194
return Promise.resolve(undefined);
195
}
196
}
197
198
// A Map from profile directory to a promise that resolves to the ProfileAgeImpl.
199
const PROFILES = new Map();
200
201
async function initProfileAge(profile) {
202
let timesPath = OS.Path.join(profile, FILE_TIMES);
203
204
try {
205
let times = await CommonUtils.readJSON(timesPath);
206
return new ProfileAgeImpl(profile, times || {});
207
} catch (e) {
208
// Indicates that the file was missing or broken. In this case we want to
209
// record the first use time as now. The constructor will set this and write
210
// times.json
211
return new ProfileAgeImpl(profile, { firstUse: null });
212
}
213
}
214
215
/**
216
* Returns a promise that resolves to an instance of ProfileAgeImpl. Will always
217
* return the same instance for every call for the same profile.
218
*
219
* @param {string} profile The path to the profile directory.
220
* @return {Promise<ProfileAgeImpl>} Resolves to the ProfileAgeImpl.
221
*/
222
function ProfileAge(profile = OS.Constants.Path.profileDir) {
223
if (PROFILES.has(profile)) {
224
return PROFILES.get(profile);
225
}
226
227
let promise = initProfileAge(profile);
228
PROFILES.set(profile, promise);
229
return promise;
230
}