Bug 1667155 [wpt PR 25777] - [AspectRatio] Fix bug in flex-aspect-ratio-024 test...
[gecko.git] / browser / modules / AsanReporter.jsm
blobdec1088e3f685bd2dd6c54f0b1ef76d650ee7dea
1 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 this.EXPORTED_SYMBOLS = ["AsanReporter"];
8 const { XPCOMUtils } = ChromeUtils.import(
9   "resource://gre/modules/XPCOMUtils.jsm"
12 XPCOMUtils.defineLazyModuleGetters(this, {
13   AppConstants: "resource://gre/modules/AppConstants.jsm",
14   Log: "resource://gre/modules/Log.jsm",
15   OS: "resource://gre/modules/osfile.jsm",
16   Services: "resource://gre/modules/Services.jsm",
17 });
19 XPCOMUtils.defineLazyGlobalGetters(this, ["TextDecoder", "XMLHttpRequest"]);
21 // Define our prefs
22 const PREF_CLIENT_ID = "asanreporter.clientid";
23 const PREF_API_URL = "asanreporter.apiurl";
24 const PREF_AUTH_TOKEN = "asanreporter.authtoken";
25 const PREF_LOG_LEVEL = "asanreporter.loglevel";
27 const LOGGER_NAME = "asanreporter";
29 let logger;
31 XPCOMUtils.defineLazyGetter(this, "asanDumpDir", () => {
32   let profileDir = Services.dirsvc.get("ProfD", Ci.nsIFile);
33   return OS.Path.join(profileDir.path, "asan");
34 });
36 this.AsanReporter = {
37   init() {
38     if (this.initialized) {
39       return;
40     }
41     this.initialized = true;
43     // Setup logging
44     logger = Log.repository.getLogger(LOGGER_NAME);
45     logger.addAppender(new Log.ConsoleAppender(new Log.BasicFormatter()));
46     logger.addAppender(new Log.DumpAppender(new Log.BasicFormatter()));
47     logger.level = Services.prefs.getIntPref(PREF_LOG_LEVEL, Log.Level.Info);
49     logger.info("Starting up...");
51     // Install a handler to observe tab crashes, so we can report those right
52     // after they happen instead of relying on the user to restart the browser.
53     Services.obs.addObserver(this, "ipc:content-shutdown");
55     processDirectory();
56   },
58   observe(aSubject, aTopic, aData) {
59     if (aTopic == "ipc:content-shutdown") {
60       aSubject.QueryInterface(Ci.nsIPropertyBag2);
61       if (!aSubject.get("abnormal")) {
62         return;
63       }
64       processDirectory();
65     }
66   },
69 function processDirectory() {
70   let iterator = new OS.File.DirectoryIterator(asanDumpDir);
71   let results = [];
73   // Scan the directory for any ASan logs that we haven't
74   // submitted yet. Store the filenames in an array so we
75   // can close the iterator early.
76   iterator
77     .forEach(entry => {
78       if (
79         entry.name.indexOf("ff_asan_log.") == 0 &&
80         !entry.name.includes("submitted")
81       ) {
82         results.push(entry);
83       }
84     })
85     .then(
86       () => {
87         iterator.close();
88         logger.info("Processing " + results.length + " reports...");
90         // Sequentially submit all reports that we found. Note that doing this
91         // with Promise.all would not result in a sequential ordering and would
92         // cause multiple requests to be sent to the server at once.
93         let requests = Promise.resolve();
94         results.forEach(result => {
95           requests = requests.then(
96             // We return a promise here that already handles any submit failures
97             // so our chain is not interrupted if one of the reports couldn't
98             // be submitted for some reason.
99             () =>
100               submitReport(result.path).then(
101                 () => {
102                   logger.info("Successfully submitted " + result.path);
103                 },
104                 e => {
105                   logger.error(
106                     "Failed to submit " + result.path + ". Reason: " + e
107                   );
108                 }
109               )
110           );
111         });
113         requests.then(() => logger.info("Done processing reports."));
114       },
115       e => {
116         iterator.close();
117         logger.error("Error while iterating over report files: " + e);
118       }
119     );
122 function submitReport(reportFile) {
123   logger.info("Processing " + reportFile);
124   return OS.File.read(reportFile)
125     .then(submitToServer)
126     .then(() => {
127       // Mark as submitted only if we successfully submitted it to the server.
128       return OS.File.move(reportFile, reportFile + ".submitted");
129     });
132 function submitToServer(data) {
133   return new Promise(function(resolve, reject) {
134     logger.debug("Setting up XHR request");
135     let client = Services.prefs.getStringPref(PREF_CLIENT_ID);
136     let api_url = Services.prefs.getStringPref(PREF_API_URL);
137     let auth_token = Services.prefs.getStringPref(PREF_AUTH_TOKEN, null);
139     let decoder = new TextDecoder();
141     if (!client) {
142       client = "unknown";
143     }
145     let versionArr = [
146       Services.appinfo.version,
147       Services.appinfo.appBuildID,
148       AppConstants.SOURCE_REVISION_URL || "unknown",
149     ];
151     // Concatenate all relevant information as our server only
152     // has one field available for version information.
153     let product_version = versionArr.join("-");
154     let os = AppConstants.platform;
156     let reportObj = {
157       rawStdout: "",
158       rawStderr: "",
159       rawCrashData: decoder.decode(data),
160       // Hardcode platform as there is no other reasonable platform for ASan
161       platform: "x86-64",
162       product: "mozilla-central-asan-nightly",
163       product_version,
164       os,
165       client,
166       tool: "asan-nightly-program",
167     };
169     var xhr = new XMLHttpRequest();
170     xhr.open("POST", api_url, true);
171     xhr.setRequestHeader("Content-Type", "application/json");
173     // For internal testing purposes, an auth_token can be specified
174     if (auth_token) {
175       xhr.setRequestHeader("Authorization", "Token " + auth_token);
176     } else {
177       // Prevent privacy leaks
178       xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS;
179     }
181     xhr.onreadystatechange = function() {
182       if (xhr.readyState == 4) {
183         if (xhr.status == "201") {
184           logger.debug("XHR: OK");
185           resolve(xhr);
186         } else {
187           logger.debug(
188             "XHR: Status: " + xhr.status + " Response: " + xhr.responseText
189           );
190           reject(xhr);
191         }
192       }
193     };
195     xhr.send(JSON.stringify(reportObj));
196   });