blob: 3609127edf231b3c6c69446610f5c870fde120c9 [file] [log] [blame]
James Hawkinsabd73e62016-01-19 15:10:38 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// The bootstat command provides options to persist boot events with the current
18// timestamp, dump the persisted events, and log all events to EventLog to be
19// uploaded to Android log storage via Tron.
20
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080021#include <getopt.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070022#include <sys/klog.h>
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070023#include <unistd.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070024
James Hawkinse78ea772017-03-24 11:43:02 -070025#include <chrono>
James Hawkins0660b302016-03-08 16:18:15 -080026#include <cmath>
James Hawkinsabd73e62016-01-19 15:10:38 -080027#include <cstddef>
28#include <cstdio>
James Hawkins500d7152016-02-16 15:05:54 -080029#include <ctime>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080030#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080031#include <memory>
32#include <string>
James Hawkinsbe46fd12017-02-02 16:21:25 -080033#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070034
James Hawkinse78ea772017-03-24 11:43:02 -070035#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070036#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080037#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070038#include <android-base/parseint.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080039#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070040#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070041#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080042#include <cutils/properties.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070043#include <log/logcat.h>
James Hawkins9aec9262017-01-31 11:42:24 -080044#include <metricslogger/metrics_logger.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045
James Hawkinsabd73e62016-01-19 15:10:38 -080046#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080047
48namespace {
49
James Hawkinsabd73e62016-01-19 15:10:38 -080050// Scans the boot event record store for record files and logs each boot event
51// via EventLog.
52void LogBootEvents() {
53 BootEventRecordStore boot_event_store;
54
55 auto events = boot_event_store.GetAllBootEvents();
56 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080057 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080058 }
59}
60
James Hawkinsc6275582016-03-22 10:47:44 -070061// Records the named boot |event| to the record store. If |value| is non-empty
62// and is a proper string representation of an integer value, the converted
63// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070064void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070065 BootEventRecordStore boot_event_store;
66 if (!value_str.empty()) {
67 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070068 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070069 boot_event_store.AddBootEventWithValue(event, value);
70 }
James Hawkinsc6275582016-03-22 10:47:44 -070071 } else {
72 boot_event_store.AddBootEvent(event);
73 }
74}
75
James Hawkinsabd73e62016-01-19 15:10:38 -080076void PrintBootEvents() {
77 printf("Boot events:\n");
78 printf("------------\n");
79
80 BootEventRecordStore boot_event_store;
81 auto events = boot_event_store.GetAllBootEvents();
82 for (auto i = events.cbegin(); i != events.cend(); ++i) {
83 printf("%s\t%d\n", i->first.c_str(), i->second);
84 }
85}
86
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070087void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080088 fprintf(stderr, "Usage: %s [options]\n", cmd);
89 fprintf(stderr,
90 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080091 " -h, --help Show this help\n"
92 " -l, --log Log all metrics to logstorage\n"
93 " -p, --print Dump the boot event records to the console\n"
94 " -r, --record Record the timestamp of a named boot event\n"
95 " --value Optional value to associate with the boot event\n"
96 " --record_boot_complete Record metrics related to the time for the device boot\n"
97 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -080098 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -080099}
100
101// Constructs a readable, printable string from the givencommand line
102// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700103std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800104 std::string cmd;
105 for (int i = 0; i < argc; ++i) {
106 cmd += argv[i];
107 cmd += " ";
108 }
109
110 return cmd;
111}
112
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800113// Convenience wrapper over the property API that returns an
114// std::string.
115std::string GetProperty(const char* key) {
116 std::vector<char> temp(PROPERTY_VALUE_MAX);
117 const int len = property_get(key, &temp[0], nullptr);
118 if (len < 0) {
119 return "";
120 }
121 return std::string(&temp[0], len);
122}
123
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700124void SetProperty(const char* key, const std::string& val) {
125 property_set(key, val.c_str());
126}
127
128void SetProperty(const char* key, const char* val) {
129 property_set(key, val);
130}
131
James Hawkins6f74c0b2016-02-12 15:49:16 -0800132constexpr int32_t kUnknownBootReason = 1;
133
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800134// A mapping from boot reason string, as read from the ro.boot.bootreason
135// system property, to a unique integer ID. Viewers of log data dashboards for
136// the boot_reason metric may refer to this mapping to discern the histogram
137// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800138const std::map<std::string, int32_t> kBootReasonMap = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700139 {"unknown", kUnknownBootReason},
140 {"normal", 2},
141 {"recovery", 3},
142 {"reboot", 4},
143 {"PowerKey", 5},
144 {"hard_reset", 6},
145 {"kernel_panic", 7},
146 {"rpm_err", 8},
147 {"hw_reset", 9},
148 {"tz_err", 10},
149 {"adsp_err", 11},
150 {"modem_err", 12},
151 {"mba_err", 13},
152 {"Watchdog", 14},
153 {"Panic", 15},
154 {"power_key", 16},
155 {"power_on", 17},
156 {"Reboot", 18},
157 {"rtc", 19},
158 {"edl", 20},
159 {"oem_pon1", 21},
160 {"oem_powerkey", 22},
161 {"oem_unknown_reset", 23},
162 {"srto: HWWDT reset SC", 24},
163 {"srto: HWWDT reset platform", 25},
164 {"srto: bootloader", 26},
165 {"srto: kernel panic", 27},
166 {"srto: kernel watchdog reset", 28},
167 {"srto: normal", 29},
168 {"srto: reboot", 30},
169 {"srto: reboot-bootloader", 31},
170 {"srto: security watchdog reset", 32},
171 {"srto: wakesrc", 33},
172 {"srto: watchdog", 34},
173 {"srto:1-1", 35},
174 {"srto:omap_hsmm", 36},
175 {"srto:phy0", 37},
176 {"srto:rtc0", 38},
177 {"srto:touchpad", 39},
178 {"watchdog", 40},
179 {"watchdogr", 41},
180 {"wdog_bark", 42},
181 {"wdog_bite", 43},
182 {"wdog_reset", 44},
183 {"shutdown,", 45}, // Trailing comma is intentional.
184 {"shutdown,userrequested", 46},
185 {"reboot,bootloader", 47},
186 {"reboot,cold", 48},
187 {"reboot,recovery", 49},
188 {"thermal_shutdown", 50},
189 {"s3_wakeup", 51},
190 {"kernel_panic,sysrq", 52},
191 {"kernel_panic,NULL", 53},
192 {"kernel_panic,BUG", 54},
193 {"bootloader", 55},
194 {"cold", 56},
195 {"hard", 57},
196 {"warm", 58},
197 {"recovery", 59},
198 {"thermal-shutdown", 60},
199 {"shutdown,thermal", 61},
200 {"shutdown,battery", 62},
201 {"reboot,ota", 63},
202 {"reboot,factory_reset", 64},
203 {"reboot,", 65},
204 {"reboot,shell", 66},
205 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700206 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700207 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700208 {"cold,powerkey", 70},
209 {"warm,s3_wakeup", 71},
210 {"hard,hw_reset", 72},
211 {"shutdown,suspend", 73}, // Suspend to RAM
212 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800213};
214
215// Converts a string value representing the reason the system booted to an
216// integer representation. This is necessary for logging the boot_reason metric
217// via Tron, which does not accept non-integer buckets in histograms.
218int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800219 auto mapping = kBootReasonMap.find(boot_reason);
220 if (mapping != kBootReasonMap.end()) {
221 return mapping->second;
222 }
223
224 LOG(INFO) << "Unknown boot reason: " << boot_reason;
225 return kUnknownBootReason;
226}
227
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700228// Canonical list of supported primary reboot reasons.
229const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700230 // clang-format off
231 // kernel
232 "watchdog",
233 "kernel_panic",
234 // strong
235 "recovery", // Should not happen from ro.boot.bootreason
236 "bootloader", // Should not happen from ro.boot.bootreason
237 // blunt
238 "cold",
239 "hard",
240 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700241 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700242 "shutdown", // Can not happen from ro.boot.bootreason
243 "reboot", // Default catch-all for anything unknown
244 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700245};
246
247// Returns true if the supplied reason prefix is considered detailed enough.
248bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700249 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700250 if (s == "cold") break;
251 // Prefix defined as terminated by a nul or comma (,).
252 if (android::base::StartsWith(r, s.c_str()) &&
253 ((r.length() == s.length()) || (r[s.length()] == ','))) {
254 return true;
255 }
256 }
257 return false;
258}
259
260// Returns true if the supplied reason prefix is associated with the kernel.
261bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700262 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700263 if (s == "recovery") break;
264 // Prefix defined as terminated by a nul or comma (,).
265 if (android::base::StartsWith(r, s.c_str()) &&
266 ((r.length() == s.length()) || (r[s.length()] == ','))) {
267 return true;
268 }
269 }
270 return false;
271}
272
273// Returns true if the supplied reason prefix is considered known.
274bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700275 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700276 // Prefix defined as terminated by a nul or comma (,).
277 if (android::base::StartsWith(r, s.c_str()) &&
278 ((r.length() == s.length()) || (r[s.length()] == ','))) {
279 return true;
280 }
281 }
282 return false;
283}
284
285// If the reboot reason should be improved, report true if is too blunt.
286bool isBluntRebootReason(const std::string& r) {
287 if (isStrongRebootReason(r)) return false;
288
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700289 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700290
291 size_t pos = 0;
292 while ((pos = r.find(',', pos)) != std::string::npos) {
293 ++pos;
294 std::string next(r.substr(pos));
295 if (next.length() == 0) break;
296 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700297 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
298 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700299 }
300 return true;
301}
302
Mark Salyzyn64610892017-09-18 10:41:14 -0700303bool readPstoreConsole(std::string& console) {
304 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
305 return true;
306 }
307 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
308}
309
310bool addKernelPanicSubReason(const std::string& console, std::string& ret) {
311 // Check for kernel panic types to refine information
312 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
313 // Can not happen, except on userdebug, during testing/debugging.
314 ret = "kernel_panic,sysrq";
315 return true;
316 }
317 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
318 std::string::npos) {
319 ret = "kernel_panic,NULL";
320 return true;
321 }
322 if (console.rfind("Kernel BUG at ") != std::string::npos) {
323 ret = "kernel_panic,BUG";
324 return true;
325 }
326 return false;
327}
328
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700329// std::transform Helper callback functions:
330// Converts a string value representing the reason the system booted to a
331// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700332char tounderline(char c) {
333 return ::isblank(c) ? '_' : c;
334}
335char toprintable(char c) {
336 return ::isprint(c) ? c : '?';
337}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700338
339const char system_reboot_reason_property[] = "sys.boot.reason";
340const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
341const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
342
343// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
344std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700345 static const size_t max_reason_length = 256;
346
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700347 std::string ret(GetProperty(system_reboot_reason_property));
348 std::string reason(boot_reason);
349 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
350 if (reason == ret) ret = "";
351
352 // Cleanup boot_reason regarding acceptable character set
353 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
354 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
355 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
356
357 // Is the current system boot reason sys.boot.reason valid?
358 if (!isKnownRebootReason(ret)) ret = "";
359
360 if (ret == "") {
361 // Is the bootloader boot reason ro.boot.bootreason known?
362 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700363 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700364 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700365 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700366 if (r == s) {
367 if (isBluntRebootReason(s)) {
368 blunt = s;
369 } else {
370 ret = s;
371 break;
372 }
373 }
374 }
375 if (ret == "") ret = blunt;
376 if (ret != "") break;
377 }
378 }
379
380 if (ret == "") {
381 // A series of checks to take some officially unsupported reasons
382 // reported by the bootloader and find some logical and canonical
383 // sense. In an ideal world, we would require those bootloaders
384 // to behave and follow our standards.
385 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700386 {"watchdog", "wdog"},
387 {"cold,powerkey", "powerkey"},
388 {"kernel_panic", "panic"},
389 {"shutdown,thermal", "thermal"},
390 {"warm,s3_wakeup", "s3_wakeup"},
391 {"hard,hw_reset", "hw_reset"},
392 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700393 };
394
395 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700396 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700397 if (reason.find(s.first) != std::string::npos) {
398 ret = s.first;
399 break;
400 }
401 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
402 ret = s.first;
403 break;
404 }
405 }
406 }
407
408 // If watchdog is the reason, see if there is a security angle?
409 if (ret == "watchdog") {
410 if (reason.find("sec") != std::string::npos) {
411 ret += ",security";
412 }
413 }
414
Mark Salyzyn64610892017-09-18 10:41:14 -0700415 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700416 // Check to see if last klog has some refinement hints.
417 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700418 if (readPstoreConsole(content)) {
419 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700420 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700421 } else if (isBluntRebootReason(ret)) {
422 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700423
Mark Salyzyn64610892017-09-18 10:41:14 -0700424 // Check to see if last klog has some refinement hints.
425 std::string content;
426 if (readPstoreConsole(content)) {
427 // The toybox reboot command used directly (unlikely)? But also
428 // catches init's response to Android's more controlled reboot command.
429 if (content.rfind("reboot: Power down") != std::string::npos) {
430 ret = "shutdown"; // Still too blunt, but more accurate.
431 // ToDo: init should record the shutdown reason to kernel messages ala:
432 // init: shutdown system with command 'last_reboot_reason'
433 // so that if pstore has persistence we can get some details
434 // that could be missing in last_reboot_reason_property.
435 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700436
Mark Salyzyn64610892017-09-18 10:41:14 -0700437 static const char cmd[] = "reboot: Restarting system with command '";
438 size_t pos = content.rfind(cmd);
439 if (pos != std::string::npos) {
440 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700441 std::string subReason(content.substr(pos, max_reason_length));
442 for (pos = 0; pos < subReason.length(); ++pos) {
443 char c = tounderline(subReason[pos]);
444 if (!::isprint(c) || (c == '\'')) {
445 subReason.erase(pos);
446 break;
447 }
448 subReason[pos] = ::tolower(c);
449 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700450 if (subReason != "") { // Will not land "reboot" as that is too blunt.
451 if (isKernelRebootReason(subReason)) {
452 ret = "reboot," + subReason; // User space can't talk kernel reasons.
453 } else {
454 ret = subReason;
455 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700456 }
457 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700458
Mark Salyzyn64610892017-09-18 10:41:14 -0700459 // Check for kernel panics, allowed to override reboot command.
460 if (!addKernelPanicSubReason(content, ret) &&
461 // check for long-press power down
462 ((content.rfind("Power held for ") != std::string::npos) ||
463 (content.rfind("charger: [") != std::string::npos))) {
464 ret = "cold";
465 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700466 }
467
468 // The following battery test should migrate to a default system health HAL
469
470 // Let us not worry if the reboot command was issued, for the cases of
471 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
472 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
473 // battery could conceivably lead to these, so worthy of override.
474 if (isBluntRebootReason(ret)) {
475 // Heuristic to determine if shutdown possibly because of a dead battery?
476 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700477 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700478 static const char battery[] = "healthd: battery l=";
Mark Salyzyn64610892017-09-18 10:41:14 -0700479 size_t pos = content.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700480 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700481 if (pos != std::string::npos) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700482 digits = content.substr(pos + strlen(battery));
483 }
484 char* endptr = NULL;
485 unsigned long long level = strtoull(digits.c_str(), &endptr, 10);
486 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700487 LOG(INFO) << "Battery level at shutdown " << level << "%";
488 if (level <= battery_dead_threshold) {
489 ret = "shutdown,battery";
490 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700491 } else { // Most likely
492 digits = ""; // reset digits
493
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700494 // Content buffer no longer will have console data. Beware if more
495 // checks added below, that depend on parsing console content.
496 content = "";
497
498 LOG(DEBUG) << "Can not find last low battery in last console messages";
499 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700500 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700501 if (fp != nullptr) {
502 android::base::ReadFdToString(fileno(fp), &content);
503 }
504 android_logcat_pclose(&ctx, fp);
505 android_logcat_destroy(&ctx);
506 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
507 const char* match = logcat_battery;
508
509 if (content == "") {
510 // Service logd.klog not running, go to smaller buffer in the kernel.
511 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
512 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700513 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700514 std::unique_ptr<char[]> buf(new char[len]);
515 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
516 if (rc < len) {
517 len = rc + 1;
518 }
519 buf[--len] = '\0';
520 content = buf.get();
521 }
522 match = battery;
523 }
524
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700525 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700526 if (pos != std::string::npos) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700527 digits = content.substr(pos + strlen(match));
528 }
529 endptr = NULL;
530 level = strtoull(digits.c_str(), &endptr, 10);
531 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700532 LOG(INFO) << "Battery level at startup " << level << "%";
533 if (level <= battery_dead_threshold) {
534 ret = "shutdown,battery";
535 }
536 } else {
537 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
538 }
539 }
540 }
541
542 // Is there a controlled shutdown hint in last_reboot_reason_property?
543 if (isBluntRebootReason(ret)) {
544 // Content buffer no longer will have console data. Beware if more
545 // checks added below, that depend on parsing console content.
546 content = GetProperty(last_reboot_reason_property);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700547 // Cleanup last_boot_reason regarding acceptable character set
548 std::transform(content.begin(), content.end(), content.begin(), ::tolower);
549 std::transform(content.begin(), content.end(), content.begin(), tounderline);
550 std::transform(content.begin(), content.end(), content.begin(), toprintable);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700551
Mark Salyzyn62909822017-10-09 09:27:16 -0700552 // Anything in last is better than 'super-blunt' reboot or shutdown.
553 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
554 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700555 }
556 }
557
558 // Other System Health HAL reasons?
559
560 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
561 // possibly offer hardware-specific clues from the PMIC.
562 }
563
564 // If unknown left over from above, make it "reboot,<boot_reason>"
565 if (ret == "") {
566 ret = "reboot";
567 if (android::base::StartsWith(reason, "reboot")) {
568 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700569 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700570 reason = reason.substr(1);
571 }
572 }
573 if (reason != "") {
574 ret += ",";
575 ret += reason;
576 }
577 }
578
579 LOG(INFO) << "Canonical boot reason: " << ret;
580 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
581 // Rewrite as it must be old news, kernel reasons trump user space.
582 SetProperty(last_reboot_reason_property, ret);
583 }
584 return ret;
585}
586
James Hawkinsb9cf7712016-04-08 15:32:19 -0700587// Returns the appropriate metric key prefix for the boot_complete metric such
588// that boot metrics after a system update are labeled as ota_boot_complete;
589// otherwise, they are labeled as boot_complete. This method encapsulates the
590// bookkeeping required to track when a system update has occurred by storing
591// the UTC timestamp of the system build date and comparing against the current
592// system build date.
593std::string CalculateBootCompletePrefix() {
594 static const std::string kBuildDateKey = "build_date";
595 std::string boot_complete_prefix = "boot_complete";
596
597 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700598 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700599 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700600 return std::string();
601 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700602
603 BootEventRecordStore boot_event_store;
604 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700605 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
606 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
607 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700608 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700609 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700610 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700611 boot_complete_prefix = "ota_" + boot_complete_prefix;
612 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700613 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700614 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700615 }
616
617 return boot_complete_prefix;
618}
619
James Hawkinsef0a0902017-01-06 14:38:23 -0800620// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700621void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800622 std::string value = GetProperty(property);
623
James Hawkins27c05222017-01-26 11:55:44 -0800624 int32_t time_in_ms;
625 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800626 boot_event_store->AddBootEventWithValue(property, time_in_ms);
627 }
628}
629
James Hawkins1bfcaec2017-05-19 14:27:27 -0700630// A map from bootloader timing stage to the time that stage took during boot.
631typedef std::map<std::string, int32_t> BootloaderTimingMap;
632
633// Returns a mapping from bootloader stage names to the time those stages
634// took to boot.
635const BootloaderTimingMap GetBootLoaderTimings() {
636 BootloaderTimingMap timings;
637
638 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
639 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800640 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800641 if (value.empty()) {
642 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700643 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800644 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800645
646 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700647 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800648 // |stageTiming| is of the form 'stage:time'.
649 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700650 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800651
652 std::string stageName = stageTimingValues[0];
653 int32_t time_ms;
654 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700655 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800656 }
657 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800658
James Hawkins1bfcaec2017-05-19 14:27:27 -0700659 return timings;
660}
661
662// Parses and records the set of bootloader stages and associated boot times
663// from the ro.boot.boottime system property.
664void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
665 const BootloaderTimingMap& bootloader_timings) {
666 int32_t total_time = 0;
667 for (const auto& timing : bootloader_timings) {
668 total_time += timing.second;
669 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
670 }
671
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800672 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800673}
674
James Hawkins1bfcaec2017-05-19 14:27:27 -0700675// Records the closest estimation to the absolute device boot time, i.e.,
676// from power on to boot_complete, including bootloader times.
677void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
678 const BootloaderTimingMap& bootloader_timings,
679 std::chrono::milliseconds uptime) {
680 int32_t bootloader_time_ms = 0;
681
682 for (const auto& timing : bootloader_timings) {
683 if (timing.first.compare("SW") != 0) {
684 bootloader_time_ms += timing.second;
685 }
686 }
687
688 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
689 auto absolute_total =
690 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
691 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
692}
693
James Hawkinsc08e9962016-03-11 14:59:50 -0800694// Records several metrics related to the time it takes to boot the device,
695// including disambiguating boot time on encrypted or non-encrypted devices.
696void RecordBootComplete() {
697 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700698 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700699
James Hawkins1bfcaec2017-05-19 14:27:27 -0700700 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
701 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700702 time_t current_time_utc = time(nullptr);
703
704 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
705 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700706 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
707 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700708 }
709
710 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800711
James Hawkinsb9cf7712016-04-08 15:32:19 -0700712 // The boot_complete metric has two variants: boot_complete and
713 // ota_boot_complete. The latter signifies that the device is booting after
714 // a system update.
715 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700716 if (boot_complete_prefix.empty()) {
717 // The system is hosed because the build date property could not be read.
718 return;
719 }
James Hawkinsc08e9962016-03-11 14:59:50 -0800720
721 // post_decrypt_time_elapsed is only logged on encrypted devices.
722 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
723 // Log the amount of time elapsed until the device is decrypted, which
724 // includes the variable amount of time the user takes to enter the
725 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -0700726 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800727
728 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -0700729 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -0700730 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -0700731 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800732 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700733 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800734 }
735
736 // Record the total time from device startup to boot complete, regardless of
737 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -0700738 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -0800739
740 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
741 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
742 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -0800743
James Hawkins1bfcaec2017-05-19 14:27:27 -0700744 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
745 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
746
747 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
748 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -0800749}
750
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800751// Records the boot_reason metric by querying the ro.boot.bootreason system
752// property.
753void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700754 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins5240f202017-09-15 16:01:57 -0700755 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700756 android::metricslogger::FIELD_PLATFORM_REASON, reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700757
758 // Log the raw bootloader_boot_reason property value.
759 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800760 BootEventRecordStore boot_event_store;
761 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700762
763 // Log the scrubbed system_boot_reason.
764 const std::string system_reason(BootReasonStrToReason(reason));
765 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
766 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
767
768 // Record the scrubbed system_boot_reason to the property
769 SetProperty(system_reboot_reason_property, system_reason);
770 if (reason == "") {
771 SetProperty(bootloader_reboot_reason_property, system_reason);
772 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800773}
774
James Hawkins500d7152016-02-16 15:05:54 -0800775// Records two metrics related to the user resetting a device: the time at
776// which the device is reset, and the time since the user last reset the
777// device. The former is only set once per-factory reset.
778void RecordFactoryReset() {
779 BootEventRecordStore boot_event_store;
780 BootEventRecordStore::BootEventRecord record;
781
782 time_t current_time_utc = time(nullptr);
783
James Hawkins0660b302016-03-08 16:18:15 -0800784 if (current_time_utc < 0) {
785 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700786 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
787 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -0700788
James Hawkins9aec9262017-01-31 11:42:24 -0800789 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700790 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700791 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
792 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -0800793 return;
794 } else {
James Hawkins9aec9262017-01-31 11:42:24 -0800795 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700796
James Hawkins9aec9262017-01-31 11:42:24 -0800797 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700798 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700799 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -0800800 }
801
James Hawkins500d7152016-02-16 15:05:54 -0800802 // The factory_reset boot event does not exist after the device is reset, so
803 // use this signal to mark the time of the factory reset.
804 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
805 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -0800806
807 // Don't log the time_since_factory_reset until some time has elapsed.
808 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -0800809 return;
810 }
811
812 // Calculate and record the difference in time between now and the
813 // factory_reset time.
814 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -0800815 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700816
James Hawkins9aec9262017-01-31 11:42:24 -0800817 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700818 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700819 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700820
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700821 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
822 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -0800823}
824
James Hawkinsabd73e62016-01-19 15:10:38 -0800825} // namespace
826
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700827int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800828 android::base::InitLogging(argv);
829
830 const std::string cmd_line = GetCommandLine(argc, argv);
831 LOG(INFO) << "Service started: " << cmd_line;
832
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800833 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -0700834 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -0800835 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800836 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -0800837 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800838 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700839 // clang-format off
840 { "help", no_argument, NULL, 'h' },
841 { "log", no_argument, NULL, 'l' },
842 { "print", no_argument, NULL, 'p' },
843 { "record", required_argument, NULL, 'r' },
844 { value_str, required_argument, NULL, 0 },
845 { boot_complete_str, no_argument, NULL, 0 },
846 { boot_reason_str, no_argument, NULL, 0 },
847 { factory_reset_str, no_argument, NULL, 0 },
848 { NULL, 0, NULL, 0 }
849 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800850 };
851
James Hawkinsc6275582016-03-22 10:47:44 -0700852 std::string boot_event;
853 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -0800854 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800855 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800856 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800857 // This case handles long options which have no single-character mapping.
858 case 0: {
859 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -0700860 if (option_name == value_str) {
861 // |optarg| is an external variable set by getopt representing
862 // the option argument.
863 value = optarg;
864 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -0800865 RecordBootComplete();
866 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800867 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -0800868 } else if (option_name == factory_reset_str) {
869 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800870 } else {
871 LOG(ERROR) << "Invalid option: " << option_name;
872 }
873 break;
874 }
875
James Hawkinsabd73e62016-01-19 15:10:38 -0800876 case 'h': {
877 ShowHelp(argv[0]);
878 break;
879 }
880
881 case 'l': {
882 LogBootEvents();
883 break;
884 }
885
886 case 'p': {
887 PrintBootEvents();
888 break;
889 }
890
891 case 'r': {
892 // |optarg| is an external variable set by getopt representing
893 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -0700894 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -0800895 break;
896 }
897
898 default: {
899 DCHECK_EQ(opt, '?');
900
901 // |optopt| is an external variable set by getopt representing
902 // the value of the invalid option.
903 LOG(ERROR) << "Invalid option: " << optopt;
904 ShowHelp(argv[0]);
905 return EXIT_FAILURE;
906 }
907 }
908 }
909
James Hawkinsc6275582016-03-22 10:47:44 -0700910 if (!boot_event.empty()) {
911 RecordBootEventFromCommandLine(boot_event, value);
912 }
913
James Hawkinsabd73e62016-01-19 15:10:38 -0800914 return 0;
915}