BootReceiver.java revision 289e58051dd575cee601c38d6816b9ecd745b505
1/*
2 * Copyright (C) 2009 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
17package com.android.server;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.SharedPreferences;
24import android.os.Build;
25import android.os.DropBoxManager;
26import android.os.FileObserver;
27import android.os.FileUtils;
28import android.os.RecoverySystem;
29import android.os.SystemProperties;
30import android.provider.Settings;
31import android.util.Log;
32
33import java.io.File;
34import java.io.IOException;
35
36/**
37 * Performs a number of miscellaneous, non-system-critical actions
38 * after the system has finished booting.
39 */
40public class BootReceiver extends BroadcastReceiver {
41    private static final String TAG = "BootReceiver";
42
43    // Maximum size of a logged event (files get truncated if they're longer)
44    private static final int LOG_SIZE = 65536;
45
46    private static final File TOMBSTONE_DIR = new File("/data/tombstones");
47
48    // Keep a reference to the observer so the finalizer doesn't disable it.
49    private static FileObserver sTombstoneObserver = null;
50
51    @Override
52    public void onReceive(Context context, Intent intent) {
53        try {
54            logBootEvents(context);
55        } catch (Exception e) {
56            Log.e(TAG, "Can't log boot events", e);
57        }
58
59        try {
60            RecoverySystem.handleAftermath();
61        } catch (Exception e) {
62            Log.e(TAG, "Can't handle recovery aftermath", e);
63        }
64
65        try {
66            // Start the load average overlay, if activated
67            ContentResolver res = context.getContentResolver();
68            if (Settings.System.getInt(res, Settings.System.SHOW_PROCESSES, 0) != 0) {
69                Intent loadavg = new Intent(context, com.android.server.LoadAverageService.class);
70                context.startService(loadavg);
71            }
72        } catch (Exception e) {
73            Log.e(TAG, "Can't start load average service", e);
74        }
75    }
76
77    private void logBootEvents(Context ctx) throws IOException {
78        final DropBoxManager db = (DropBoxManager) ctx.getSystemService(Context.DROPBOX_SERVICE);
79        final SharedPreferences prefs = ctx.getSharedPreferences("log_files", Context.MODE_PRIVATE);
80        final String props = new StringBuilder()
81            .append("Build: ").append(Build.FINGERPRINT).append("\n")
82            .append("Hardware: ").append(Build.BOARD).append("\n")
83            .append("Bootloader: ").append(Build.BOOTLOADER).append("\n")
84            .append("Radio: ").append(Build.RADIO).append("\n")
85            .append("Kernel: ")
86            .append(FileUtils.readTextFile(new File("/proc/version"), 1024, "...\n"))
87            .toString();
88
89        if (db == null || prefs == null) return;
90
91        if (SystemProperties.getLong("ro.runtime.firstboot", 0) == 0) {
92            String now = Long.toString(System.currentTimeMillis());
93            SystemProperties.set("ro.runtime.firstboot", now);
94            db.addText("SYSTEM_BOOT", props);
95
96            // Negative sizes mean to take the *tail* of the file (see FileUtils.readTextFile())
97            addFileToDropBox(db, prefs, props, "/proc/last_kmsg",
98                    -LOG_SIZE, "SYSTEM_LAST_KMSG");
99            addFileToDropBox(db, prefs, props, "/cache/recovery/log",
100                    -LOG_SIZE, "SYSTEM_RECOVERY_LOG");
101            addFileToDropBox(db, prefs, props, "/data/dontpanic/apanic_console",
102                    -LOG_SIZE, "APANIC_CONSOLE");
103            addFileToDropBox(db, prefs, props, "/data/dontpanic/apanic_threads",
104                    -LOG_SIZE, "APANIC_THREADS");
105        } else {
106            db.addText("SYSTEM_RESTART", props);
107        }
108
109        // Scan existing tombstones (in case any new ones appeared)
110        File[] tombstoneFiles = TOMBSTONE_DIR.listFiles();
111        for (int i = 0; tombstoneFiles != null && i < tombstoneFiles.length; i++) {
112            addFileToDropBox(db, prefs, props, tombstoneFiles[i].getPath(),
113                    LOG_SIZE, "SYSTEM_TOMBSTONE");
114        }
115
116        // Start watching for new tombstone files; will record them as they occur.
117        // This gets registered with the singleton file observer thread.
118        sTombstoneObserver = new FileObserver(TOMBSTONE_DIR.getPath(), FileObserver.CLOSE_WRITE) {
119            @Override
120            public void onEvent(int event, String path) {
121                try {
122                    String filename = new File(TOMBSTONE_DIR, path).getPath();
123                    addFileToDropBox(db, prefs, props, filename, LOG_SIZE, "SYSTEM_TOMBSTONE");
124                } catch (IOException e) {
125                    Log.e(TAG, "Can't log tombstone", e);
126                }
127            }
128        };
129
130        sTombstoneObserver.startWatching();
131    }
132
133    private static void addFileToDropBox(
134            DropBoxManager db, SharedPreferences prefs,
135            String headers, String filename, int maxSize, String tag) throws IOException {
136        if (!db.isTagEnabled(tag)) return;  // Logging disabled
137
138        File file = new File(filename);
139        long fileTime = file.lastModified();
140        if (fileTime <= 0) return;  // File does not exist
141
142        long lastTime = prefs.getLong(filename, 0);
143        if (lastTime == fileTime) return;  // Already logged this particular file
144        prefs.edit().putLong(filename, fileTime).commit();
145
146        StringBuilder report = new StringBuilder(headers).append("\n");
147        report.append(FileUtils.readTextFile(file, maxSize, "[[TRUNCATED]]\n"));
148        db.addText(tag, report.toString());
149        Log.i(TAG, "Logging " + filename + " to DropBox (" + tag + ")");
150    }
151}
152