1 /*
2  * Copyright (C) 2023 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 package android.tools.traces.monitors.events
18 
19 import android.tools.Timestamp
20 import android.tools.io.TraceType
21 import android.tools.traces.events.EventLog
22 import android.tools.traces.executeShellCommand
23 import android.tools.traces.monitors.LOG_TAG
24 import android.tools.traces.monitors.TraceMonitor
25 import android.tools.traces.now
26 import android.util.Log
27 import java.io.File
28 import java.io.FileOutputStream
29 
30 /** Collects event logs during transitions. */
31 open class EventLogMonitor : TraceMonitor() {
32     override val traceType = TraceType.EVENT_LOG
33     final override var isEnabled = false
34         private set
35 
36     private var traceStartTime: Timestamp? = null
37 
doStartnull38     override fun doStart() {
39         require(!isEnabled) { "Trace already running" }
40         isEnabled = true
41         traceStartTime = now()
42     }
43 
doStopnull44     override fun doStop(): File {
45         require(isEnabled) { "Trace not running" }
46         isEnabled = false
47         val sinceTime = traceStartTime?.unixNanosToLogFormat() ?: error("Missing start timestamp")
48 
49         traceStartTime = null
50         val outputFile = File.createTempFile(TraceType.EVENT_LOG.fileName, "")
51 
52         FileOutputStream(outputFile).use {
53             it.write("${EventLog.MAGIC_NUMBER}\n".toByteArray())
54             val command =
55                 "logcat -b events -v threadtime -v printable -v uid -v nsec " +
56                     "-v epoch -t $sinceTime >> $outputFile"
57             Log.d(LOG_TAG, "Running '$command'")
58             val eventLogString = executeShellCommand(command)
59             it.write(eventLogString)
60         }
61 
62         return outputFile
63     }
64 }
65