summaryrefslogtreecommitdiff
path: root/src/com/android/loganalysis/LogAnalyzer.java
blob: df7d63fee03bc3f87d001c749d5873256a9088fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.loganalysis;

import com.android.loganalysis.item.BugreportItem;
import com.android.loganalysis.item.DvmLockSampleItem;
import com.android.loganalysis.item.IItem;
import com.android.loganalysis.item.KernelLogItem;
import com.android.loganalysis.item.LogcatItem;
import com.android.loganalysis.item.MemoryHealthItem;
import com.android.loganalysis.parser.BugreportParser;
import com.android.loganalysis.parser.DvmLockSampleParser;
import com.android.loganalysis.parser.KernelLogParser;
import com.android.loganalysis.parser.LogcatParser;
import com.android.loganalysis.parser.MemoryHealthParser;
import com.android.loganalysis.rule.RuleEngine;
import com.android.loganalysis.rule.RuleEngine.RuleType;
import com.android.loganalysis.util.config.ArgsOptionParser;
import com.android.loganalysis.util.config.ConfigurationException;
import com.android.loganalysis.util.config.Option;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

/**
 * A command line tool to parse a bugreport, logcat, or kernel log file and return the output.
 */
public class LogAnalyzer {

    private enum OutputFormat{
        // TODO: Add text output support.
        JSON;
    }

    private enum ResultType {
        RAW, ANALYSIS;
    }

    @Option(name="bugreport", description="The path to the bugreport")
    private String mBugreportPath = null;

    @Option(name="logcat", description="The path to the logcat")
    private String mLogcatPath = null;

    @Option(name="kernel-log", description="The path to the kernel log")
    private String mKernelLogPath = null;

    @Option(name="memory-health", description="The path to the memory health log")
    private String mMemoryHealthLogPath = null;

    @Option(name="output", description="The output format, currently only JSON")
    private OutputFormat mOutputFormat = OutputFormat.JSON;

    @Option(name="rule-type", description="The type of rules to be applied")
    private RuleType mRuleType = RuleType.ALL;

    @Option(name="print", description="Print the result type")
    private List<ResultType> mResultType = new ArrayList<ResultType>();

    @Option(name="events-log", description="The path to the events log")
    private String mEventsLogPath = null;

    /** Constant for JSON output */
    private static final String RAW_DATA = "RAW";
    /** Constant for JSON output */
    private static final String ANALYSIS_DATA = "ANALYSIS";

    /**
     * Run the command line tool
     */
    public void run(String[] args) {
        try {
            initArgs(args);
        } catch (ConfigurationException e) {
            printUsage();
            return;
        }

        if (!checkPreconditions()) {
            printUsage();
            return;
        }

        BufferedReader reader = null;
        try {
            if (mBugreportPath != null) {
                reader = getBufferedReader(mBugreportPath);
                BugreportItem bugreport = new BugreportParser().parse(reader);
                printBugreport(bugreport);
                return;
            }

            if (mLogcatPath != null) {
                reader = getBufferedReader(mLogcatPath);
                LogcatItem logcat = new LogcatParser().parse(reader);
                printLogcat(logcat);
                return;
            }

            if (mKernelLogPath != null) {
                reader = getBufferedReader(mKernelLogPath);
                KernelLogItem kernelLog = new KernelLogParser().parse(reader);
                printKernelLog(kernelLog);
                return;
            }

            if (mMemoryHealthLogPath != null) {
                reader = getBufferedReader(mMemoryHealthLogPath);
                MemoryHealthItem item = new MemoryHealthParser().parse(reader);
                printMemoryHealthLog(item);
                return;
            }

            if (mEventsLogPath != null) {
                reader = getBufferedReader(mEventsLogPath);

                // The only log we know how to parse in the Events log are
                // DVM lock samples.
                DvmLockSampleItem item = new DvmLockSampleParser().parse(reader);
                printDVMLog(item);
                return;
            }
        } catch (FileNotFoundException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            System.err.println(e.getMessage());
        } finally {
            close(reader);
        }

        // Should never reach here.
        printUsage();
    }

    private void printMemoryHealthLog(MemoryHealthItem item) {
        System.out.println(item.toJson().toString());
    }

    /**
     * Print the bugreport to stdout.
     */
    private void printBugreport(BugreportItem bugreport) {
        if (OutputFormat.JSON.equals(mOutputFormat)) {
            if (mResultType.size() == 0) {
                printJson(bugreport);
            } else if (mResultType.size() == 1) {
                switch (mResultType.get(0)) {
                    case RAW:
                        printJson(bugreport);
                        break;
                    case ANALYSIS:
                        printBugreportAnalysis(getBugreportAnalysis(bugreport));
                        break;
                    default:
                        // should not get here
                        return;
                }
            } else {
                JSONObject result = new JSONObject();
                try {
                    for (ResultType resultType : mResultType) {
                        switch (resultType) {
                            case RAW:
                                result.put(RAW_DATA, bugreport.toJson());
                                break;
                            case ANALYSIS:
                                result.put(ANALYSIS_DATA, getBugreportAnalysis(bugreport));
                                break;
                            default:
                                // should not get here
                                break;
                        }
                    }
                } catch (JSONException e) {
                    // Ignore
                }
                printJson(result);
            }
        }
    }

    private JSONArray getBugreportAnalysis(BugreportItem bugreport) {
        RuleEngine ruleEngine = new RuleEngine(bugreport);
        ruleEngine.registerRules(mRuleType);
        ruleEngine.executeRules();
        if (ruleEngine.getAnalysis() != null) {
            return ruleEngine.getAnalysis();
        } else {
            return new JSONArray();
        }
    }

    private void printBugreportAnalysis(JSONArray analysis) {
        if (analysis != null && analysis.length() > 0) {
            System.out.println(analysis.toString());
        } else {
            System.out.println(new JSONObject().toString());
        }
    }

    /**
     * Print the logcat to stdout.
     */
    private void printLogcat(LogcatItem logcat) {
        if (OutputFormat.JSON.equals(mOutputFormat)) {
            printJson(logcat);
        }
        // TODO: Print logcat in human readable form.
    }

    /**
     * Print the kernel log to stdout.
     */
    private void printKernelLog(KernelLogItem kernelLog) {
        if (OutputFormat.JSON.equals(mOutputFormat)) {
            printJson(kernelLog);
        }
        // TODO: Print kernel log in human readable form.
    }

    /**
     * Print a DVM log entry to stdout.
     */
    private void printDVMLog(DvmLockSampleItem dvmLog) {
        if (OutputFormat.JSON.equals(mOutputFormat)) {
            printJson(dvmLog);
        }
        // TODO: Print DVM log in human readable form.
    }

    /**
     * Print an {@link IItem} to stdout.
     */
    private void printJson(IItem item) {
        if (item != null && item.toJson() != null) {
            printJson(item.toJson());
        } else {
            printJson(new JSONObject());
        }
    }

    /**
     * Print an {@link JSONObject} to stdout
     */
    private void printJson(JSONObject json) {
        if (json != null) {
            System.out.println(json.toString());
        } else {
            System.out.println(new JSONObject().toString());
        }
    }

    /**
     * Get a {@link BufferedReader} from a given filepath.
     * @param filepath the path to the file.
     * @return The {@link BufferedReader} containing the contents of the file.
     * @throws FileNotFoundException if the file could not be found.
     */
    private BufferedReader getBufferedReader(String filepath) throws FileNotFoundException {
        return new BufferedReader(new FileReader(new File(filepath)));
    }

    /**
     * Helper to close a {@link Closeable}.
     */
    private void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }

    /**
     * Parse the command line options and set {@link Option} annotated fields.
     */
    private void initArgs(String[] args) throws ConfigurationException {
        ArgsOptionParser opt = new ArgsOptionParser(this);
        opt.parse(args);
    }

    /**
     * Checks the arguments to see if they are valid.
     *
     * @return true if they are valid, false if they are not.
     */
    private boolean checkPreconditions() {
        // Check to see that exactly one log is set.
        int logCount = 0;
        if (mBugreportPath != null) logCount++;
        if (mLogcatPath != null) logCount++;
        if (mKernelLogPath != null) logCount++;
        if (mMemoryHealthLogPath != null) logCount++;
        return (logCount == 1);
    }

    /**
     * Print the usage for the command.
     */
    private void printUsage() {
        System.err.println(
                "Usage: loganalysis [--bugreport FILE | --events-log FILE | --logcat FILE | "
                        + "--kernel-log FILE]");
    }

    /**
     * Run the LogAnalyzer from the command line.
     */
    public static void main(String[] args) {
        LogAnalyzer analyzer = new LogAnalyzer();
        analyzer.run(args);
    }
}