toolkit/modules/AsyncShutdown.jsm

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
michael@0 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 /**
michael@0 6 * Managing safe shutdown of asynchronous services.
michael@0 7 *
michael@0 8 * Firefox shutdown is composed of phases that take place
michael@0 9 * sequentially. Typically, each shutdown phase removes some
michael@0 10 * capabilities from the application. For instance, at the end of
michael@0 11 * phase profileBeforeChange, no service is permitted to write to the
michael@0 12 * profile directory (with the exception of Telemetry). Consequently,
michael@0 13 * if any service has requested I/O to the profile directory before or
michael@0 14 * during phase profileBeforeChange, the system must be informed that
michael@0 15 * these requests need to be completed before the end of phase
michael@0 16 * profileBeforeChange. Failing to inform the system of this
michael@0 17 * requirement can (and has been known to) cause data loss.
michael@0 18 *
michael@0 19 * Example: At some point during shutdown, the Add-On Manager needs to
michael@0 20 * ensure that all add-ons have safely written their data to disk,
michael@0 21 * before writing its own data. Since the data is saved to the
michael@0 22 * profile, this must be completed during phase profileBeforeChange.
michael@0 23 *
michael@0 24 * AsyncShutdown.profileBeforeChange.addBlocker(
michael@0 25 * "Add-on manager: shutting down",
michael@0 26 * function condition() {
michael@0 27 * // Do things.
michael@0 28 * // Perform I/O that must take place during phase profile-before-change
michael@0 29 * return promise;
michael@0 30 * }
michael@0 31 * });
michael@0 32 *
michael@0 33 * In this example, function |condition| will be called at some point
michael@0 34 * during phase profileBeforeChange and phase profileBeforeChange
michael@0 35 * itself is guaranteed to not terminate until |promise| is either
michael@0 36 * resolved or rejected.
michael@0 37 */
michael@0 38
michael@0 39 "use strict";
michael@0 40
michael@0 41 const Cu = Components.utils;
michael@0 42 const Cc = Components.classes;
michael@0 43 const Ci = Components.interfaces;
michael@0 44 Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
michael@0 45 Cu.import("resource://gre/modules/Services.jsm", this);
michael@0 46
michael@0 47 XPCOMUtils.defineLazyModuleGetter(this, "Promise",
michael@0 48 "resource://gre/modules/Promise.jsm");
michael@0 49 XPCOMUtils.defineLazyServiceGetter(this, "gDebug",
michael@0 50 "@mozilla.org/xpcom/debug;1", "nsIDebug");
michael@0 51 Object.defineProperty(this, "gCrashReporter", {
michael@0 52 get: function() {
michael@0 53 delete this.gCrashReporter;
michael@0 54 try {
michael@0 55 let reporter = Cc["@mozilla.org/xre/app-info;1"].
michael@0 56 getService(Ci.nsICrashReporter);
michael@0 57 return this.gCrashReporter = reporter;
michael@0 58 } catch (ex) {
michael@0 59 return this.gCrashReporter = null;
michael@0 60 }
michael@0 61 },
michael@0 62 configurable: true
michael@0 63 });
michael@0 64
michael@0 65 // Display timeout warnings after 10 seconds
michael@0 66 const DELAY_WARNING_MS = 10 * 1000;
michael@0 67
michael@0 68
michael@0 69 // Crash the process if shutdown is really too long
michael@0 70 // (allowing for sleep).
michael@0 71 const PREF_DELAY_CRASH_MS = "toolkit.asyncshutdown.crash_timeout";
michael@0 72 let DELAY_CRASH_MS = 60 * 1000; // One minute
michael@0 73 try {
michael@0 74 DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS);
michael@0 75 } catch (ex) {
michael@0 76 // Ignore errors
michael@0 77 }
michael@0 78 Services.prefs.addObserver(PREF_DELAY_CRASH_MS, function() {
michael@0 79 DELAY_CRASH_MS = Services.prefs.getIntPref(PREF_DELAY_CRASH_MS);
michael@0 80 }, false);
michael@0 81
michael@0 82
michael@0 83 /**
michael@0 84 * Display a warning.
michael@0 85 *
michael@0 86 * As this code is generally used during shutdown, there are chances
michael@0 87 * that the UX will not be available to display warnings on the
michael@0 88 * console. We therefore use dump() rather than Cu.reportError().
michael@0 89 */
michael@0 90 function log(msg, prefix = "", error = null) {
michael@0 91 dump(prefix + msg + "\n");
michael@0 92 if (error) {
michael@0 93 dump(prefix + error + "\n");
michael@0 94 if (typeof error == "object" && "stack" in error) {
michael@0 95 dump(prefix + error.stack + "\n");
michael@0 96 }
michael@0 97 }
michael@0 98 }
michael@0 99 function warn(msg, error = null) {
michael@0 100 return log(msg, "WARNING: ", error);
michael@0 101 }
michael@0 102 function err(msg, error = null) {
michael@0 103 return log(msg, "ERROR: ", error);
michael@0 104 }
michael@0 105
michael@0 106 // Utility function designed to get the current state of execution
michael@0 107 // of a blocker.
michael@0 108 // We are a little paranoid here to ensure that in case of evaluation
michael@0 109 // error we do not block the AsyncShutdown.
michael@0 110 function safeGetState(state) {
michael@0 111 if (!state) {
michael@0 112 return "(none)";
michael@0 113 }
michael@0 114 let data, string;
michael@0 115 try {
michael@0 116 // Evaluate state(), normalize the result into something that we can
michael@0 117 // safely stringify or upload.
michael@0 118 string = JSON.stringify(state());
michael@0 119 data = JSON.parse(string);
michael@0 120 // Simplify the rest of the code by ensuring that we can simply
michael@0 121 // concatenate the result to a message.
michael@0 122 if (data && typeof data == "object") {
michael@0 123 data.toString = function() {
michael@0 124 return string;
michael@0 125 };
michael@0 126 }
michael@0 127 return data;
michael@0 128 } catch (ex) {
michael@0 129 if (string) {
michael@0 130 return string;
michael@0 131 }
michael@0 132 try {
michael@0 133 return "Error getting state: " + ex + " at " + ex.stack;
michael@0 134 } catch (ex2) {
michael@0 135 return "Error getting state but could not display error";
michael@0 136 }
michael@0 137 }
michael@0 138 }
michael@0 139
michael@0 140 /**
michael@0 141 * Countdown for a given duration, skipping beats if the computer is too busy,
michael@0 142 * sleeping or otherwise unavailable.
michael@0 143 *
michael@0 144 * @param {number} delay An approximate delay to wait in milliseconds (rounded
michael@0 145 * up to the closest second).
michael@0 146 *
michael@0 147 * @return Deferred
michael@0 148 */
michael@0 149 function looseTimer(delay) {
michael@0 150 let DELAY_BEAT = 1000;
michael@0 151 let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
michael@0 152 let beats = Math.ceil(delay / DELAY_BEAT);
michael@0 153 let deferred = Promise.defer();
michael@0 154 timer.initWithCallback(function() {
michael@0 155 if (beats <= 0) {
michael@0 156 deferred.resolve();
michael@0 157 }
michael@0 158 --beats;
michael@0 159 }, DELAY_BEAT, Ci.nsITimer.TYPE_REPEATING_PRECISE_CAN_SKIP);
michael@0 160 // Ensure that the timer is both canceled once we are done with it
michael@0 161 // and not garbage-collected until then.
michael@0 162 deferred.promise.then(() => timer.cancel(), () => timer.cancel());
michael@0 163 return deferred;
michael@0 164 }
michael@0 165
michael@0 166 this.EXPORTED_SYMBOLS = ["AsyncShutdown"];
michael@0 167
michael@0 168 /**
michael@0 169 * {string} topic -> phase
michael@0 170 */
michael@0 171 let gPhases = new Map();
michael@0 172
michael@0 173 this.AsyncShutdown = {
michael@0 174 /**
michael@0 175 * Access function getPhase. For testing purposes only.
michael@0 176 */
michael@0 177 get _getPhase() {
michael@0 178 let accepted = false;
michael@0 179 try {
michael@0 180 accepted = Services.prefs.getBoolPref("toolkit.asyncshutdown.testing");
michael@0 181 } catch (ex) {
michael@0 182 // Ignore errors
michael@0 183 }
michael@0 184 if (accepted) {
michael@0 185 return getPhase;
michael@0 186 }
michael@0 187 return undefined;
michael@0 188 }
michael@0 189 };
michael@0 190
michael@0 191 /**
michael@0 192 * Register a new phase.
michael@0 193 *
michael@0 194 * @param {string} topic The notification topic for this Phase.
michael@0 195 * @see {https://developer.mozilla.org/en-US/docs/Observer_Notifications}
michael@0 196 */
michael@0 197 function getPhase(topic) {
michael@0 198 let phase = gPhases.get(topic);
michael@0 199 if (phase) {
michael@0 200 return phase;
michael@0 201 }
michael@0 202 let spinner = new Spinner(topic);
michael@0 203 phase = Object.freeze({
michael@0 204 /**
michael@0 205 * Register a blocker for the completion of a phase.
michael@0 206 *
michael@0 207 * @param {string} name The human-readable name of the blocker. Used
michael@0 208 * for debugging/error reporting. Please make sure that the name
michael@0 209 * respects the following model: "Some Service: some action in progress" -
michael@0 210 * for instance "OS.File: flushing all pending I/O";
michael@0 211 * @param {function|promise|*} condition A condition blocking the
michael@0 212 * completion of the phase. Generally, this is a function
michael@0 213 * returning a promise. This function is evaluated during the
michael@0 214 * phase and the phase is guaranteed to not terminate until the
michael@0 215 * resulting promise is either resolved or rejected. If
michael@0 216 * |condition| is not a function but another value |v|, it behaves
michael@0 217 * as if it were a function returning |v|.
michael@0 218 * @param {function*} state Optionally, a function returning
michael@0 219 * information about the current state of the blocker as an
michael@0 220 * object. Used for providing more details when logging errors or
michael@0 221 * crashing.
michael@0 222 *
michael@0 223 * Examples:
michael@0 224 * AsyncShutdown.profileBeforeChange.addBlocker("Module: just a promise",
michael@0 225 * promise); // profileBeforeChange will not complete until
michael@0 226 * // promise is resolved or rejected
michael@0 227 *
michael@0 228 * AsyncShutdown.profileBeforeChange.addBlocker("Module: a callback",
michael@0 229 * function callback() {
michael@0 230 * // ...
michael@0 231 * // Execute this code during profileBeforeChange
michael@0 232 * return promise;
michael@0 233 * // profileBeforeChange will not complete until promise
michael@0 234 * // is resolved or rejected
michael@0 235 * });
michael@0 236 *
michael@0 237 * AsyncShutdown.profileBeforeChange.addBlocker("Module: trivial callback",
michael@0 238 * function callback() {
michael@0 239 * // ...
michael@0 240 * // Execute this code during profileBeforeChange
michael@0 241 * // No specific guarantee about completion of profileBeforeChange
michael@0 242 * });
michael@0 243 *
michael@0 244 */
michael@0 245 addBlocker: function(name, condition, state = null) {
michael@0 246 if (typeof name != "string") {
michael@0 247 throw new TypeError("Expected a human-readable name as first argument");
michael@0 248 }
michael@0 249 if (state && typeof state != "function") {
michael@0 250 throw new TypeError("Expected nothing or a function as third argument");
michael@0 251 }
michael@0 252 spinner.addBlocker({name: name, condition: condition, state: state});
michael@0 253 }
michael@0 254 });
michael@0 255 gPhases.set(topic, phase);
michael@0 256 return phase;
michael@0 257 }
michael@0 258
michael@0 259 /**
michael@0 260 * Utility class used to spin the event loop until all blockers for a
michael@0 261 * Phase are satisfied.
michael@0 262 *
michael@0 263 * @param {string} topic The xpcom notification for that phase.
michael@0 264 */
michael@0 265 function Spinner(topic) {
michael@0 266 this._topic = topic;
michael@0 267 this._conditions = new Set(); // set to |null| once it is too late to register
michael@0 268 Services.obs.addObserver(this, topic, false);
michael@0 269 }
michael@0 270
michael@0 271 Spinner.prototype = {
michael@0 272 /**
michael@0 273 * Register a new condition for this phase.
michael@0 274 *
michael@0 275 * @param {object} condition A Condition that must be fulfilled before
michael@0 276 * we complete this Phase.
michael@0 277 * Must contain fields:
michael@0 278 * - {string} name The human-readable name of the condition. Used
michael@0 279 * for debugging/error reporting.
michael@0 280 * - {function} action An action that needs to be completed
michael@0 281 * before we proceed to the next runstate. If |action| returns a promise,
michael@0 282 * we wait until the promise is resolved/rejected before proceeding
michael@0 283 * to the next runstate.
michael@0 284 */
michael@0 285 addBlocker: function(condition) {
michael@0 286 if (!this._conditions) {
michael@0 287 throw new Error("Phase " + this._topic +
michael@0 288 " has already begun, it is too late to register" +
michael@0 289 " completion condition '" + condition.name + "'.");
michael@0 290 }
michael@0 291 this._conditions.add(condition);
michael@0 292 },
michael@0 293
michael@0 294 observe: function() {
michael@0 295 let topic = this._topic;
michael@0 296 Services.obs.removeObserver(this, topic);
michael@0 297
michael@0 298 let conditions = this._conditions;
michael@0 299 this._conditions = null; // Too late to register
michael@0 300
michael@0 301 if (conditions.size == 0) {
michael@0 302 // No need to spin anything
michael@0 303 return;
michael@0 304 }
michael@0 305
michael@0 306 // The promises for which we are waiting.
michael@0 307 let allPromises = [];
michael@0 308
michael@0 309 // Information to determine and report to the user which conditions
michael@0 310 // are not satisfied yet.
michael@0 311 let allMonitors = [];
michael@0 312
michael@0 313 for (let {condition, name, state} of conditions) {
michael@0 314 // Gather all completion conditions
michael@0 315
michael@0 316 try {
michael@0 317 if (typeof condition == "function") {
michael@0 318 // Normalize |condition| to the result of the function.
michael@0 319 try {
michael@0 320 condition = condition(topic);
michael@0 321 } catch (ex) {
michael@0 322 condition = Promise.reject(ex);
michael@0 323 }
michael@0 324 }
michael@0 325 // Normalize to a promise. Of course, if |condition| was not a
michael@0 326 // promise in the first place (in particular if the above
michael@0 327 // function returned |undefined| or failed), that new promise
michael@0 328 // isn't going to be terribly interesting, but it will behave
michael@0 329 // as a promise.
michael@0 330 condition = Promise.resolve(condition);
michael@0 331
michael@0 332 // If the promise takes too long to be resolved/rejected,
michael@0 333 // we need to notify the user.
michael@0 334 //
michael@0 335 // If it takes way too long, we need to crash.
michael@0 336
michael@0 337 let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
michael@0 338 timer.initWithCallback(function() {
michael@0 339 let msg = "A phase completion condition is" +
michael@0 340 " taking too long to complete." +
michael@0 341 " Condition: " + monitor.name +
michael@0 342 " Phase: " + topic +
michael@0 343 " State: " + safeGetState(state);
michael@0 344 warn(msg);
michael@0 345 }, DELAY_WARNING_MS, Ci.nsITimer.TYPE_ONE_SHOT);
michael@0 346
michael@0 347 let monitor = {
michael@0 348 isFrozen: true,
michael@0 349 name: name,
michael@0 350 state: state
michael@0 351 };
michael@0 352 condition = condition.then(function onSuccess() {
michael@0 353 timer.cancel(); // As a side-effect, this prevents |timer| from
michael@0 354 // being garbage-collected too early.
michael@0 355 monitor.isFrozen = false;
michael@0 356 }, function onError(error) {
michael@0 357 timer.cancel();
michael@0 358 let msg = "A completion condition encountered an error" +
michael@0 359 " while we were spinning the event loop." +
michael@0 360 " Condition: " + name +
michael@0 361 " Phase: " + topic +
michael@0 362 " State: " + safeGetState(state);
michael@0 363 warn(msg, error);
michael@0 364 monitor.isFrozen = false;
michael@0 365 });
michael@0 366 allMonitors.push(monitor);
michael@0 367 allPromises.push(condition);
michael@0 368
michael@0 369 } catch (error) {
michael@0 370 let msg = "A completion condition encountered an error" +
michael@0 371 " while we were initializing the phase." +
michael@0 372 " Condition: " + name +
michael@0 373 " Phase: " + topic +
michael@0 374 " State: " + safeGetState(state);
michael@0 375 warn(msg, error);
michael@0 376 }
michael@0 377
michael@0 378 }
michael@0 379 conditions = null;
michael@0 380
michael@0 381 let promise = Promise.all(allPromises);
michael@0 382 allPromises = null;
michael@0 383
michael@0 384 promise = promise.then(null, function onError(error) {
michael@0 385 // I don't think that this can happen.
michael@0 386 // However, let's be overcautious with async/shutdown error reporting.
michael@0 387 let msg = "An uncaught error appeared while completing the phase." +
michael@0 388 " Phase: " + topic;
michael@0 389 warn(msg, error);
michael@0 390 });
michael@0 391
michael@0 392 let satisfied = false; // |true| once we have satisfied all conditions
michael@0 393
michael@0 394 // If after DELAY_CRASH_MS (approximately one minute, adjusted to take
michael@0 395 // into account sleep and otherwise busy computer) we have not finished
michael@0 396 // this shutdown phase, we assume that the shutdown is somehow frozen,
michael@0 397 // presumably deadlocked. At this stage, the only thing we can do to
michael@0 398 // avoid leaving the user's computer in an unstable (and battery-sucking)
michael@0 399 // situation is report the issue and crash.
michael@0 400 let timeToCrash = looseTimer(DELAY_CRASH_MS);
michael@0 401 timeToCrash.promise.then(
michael@0 402 function onTimeout() {
michael@0 403 // Report the problem as best as we can, then crash.
michael@0 404 let frozen = [];
michael@0 405 let states = [];
michael@0 406 for (let {name, isFrozen, state} of allMonitors) {
michael@0 407 if (isFrozen) {
michael@0 408 frozen.push({name: name, state: safeGetState(state)});
michael@0 409 }
michael@0 410 }
michael@0 411
michael@0 412 let msg = "At least one completion condition failed to complete" +
michael@0 413 " within a reasonable amount of time. Causing a crash to" +
michael@0 414 " ensure that we do not leave the user with an unresponsive" +
michael@0 415 " process draining resources." +
michael@0 416 " Conditions: " + JSON.stringify(frozen) +
michael@0 417 " Phase: " + topic;
michael@0 418 err(msg);
michael@0 419 if (gCrashReporter && gCrashReporter.enabled) {
michael@0 420 let data = {
michael@0 421 phase: topic,
michael@0 422 conditions: frozen
michael@0 423 };
michael@0 424 gCrashReporter.annotateCrashReport("AsyncShutdownTimeout",
michael@0 425 JSON.stringify(data));
michael@0 426 } else {
michael@0 427 warn("No crash reporter available");
michael@0 428 }
michael@0 429
michael@0 430 let error = new Error();
michael@0 431 gDebug.abort(error.fileName, error.lineNumber + 1);
michael@0 432 },
michael@0 433 function onSatisfied() {
michael@0 434 // The promise has been rejected, which means that we have satisfied
michael@0 435 // all completion conditions.
michael@0 436 });
michael@0 437
michael@0 438 promise = promise.then(function() {
michael@0 439 satisfied = true;
michael@0 440 timeToCrash.reject();
michael@0 441 }/* No error is possible here*/);
michael@0 442
michael@0 443 // Now, spin the event loop
michael@0 444 let thread = Services.tm.mainThread;
michael@0 445 while(!satisfied) {
michael@0 446 thread.processNextEvent(true);
michael@0 447 }
michael@0 448 }
michael@0 449 };
michael@0 450
michael@0 451
michael@0 452 // List of well-known runstates
michael@0 453 // Ideally, runstates should be registered from the component that decides
michael@0 454 // when they start/stop. For compatibility with existing startup/shutdown
michael@0 455 // mechanisms, we register a few runstates here.
michael@0 456
michael@0 457 this.AsyncShutdown.profileChangeTeardown = getPhase("profile-change-teardown");
michael@0 458 this.AsyncShutdown.profileBeforeChange = getPhase("profile-before-change");
michael@0 459 this.AsyncShutdown.sendTelemetry = getPhase("profile-before-change2");
michael@0 460 this.AsyncShutdown.webWorkersShutdown = getPhase("web-workers-shutdown");
michael@0 461 Object.freeze(this.AsyncShutdown);

mercurial