1 /*
2  * Copyright (C) 2018 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 com.android.server.wm.flicker.monitor;
18 
19 import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
20 
21 import android.os.RemoteException;
22 
23 import androidx.annotation.VisibleForTesting;
24 
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.util.Locale;
28 
29 /**
30  * Base class for monitors containing common logic to read the trace as a byte array and save the
31  * trace to another location.
32  */
33 public abstract class TraceMonitor extends TransitionMonitor {
34     private static final Path TRACE_DIR = Paths.get("/data/misc/wmtrace/");
35 
36     protected Path mTraceFile;
37 
isEnabled()38     public abstract boolean isEnabled() throws RemoteException;
39 
TraceMonitor(Path outputDir, Path traceFile)40     TraceMonitor(Path outputDir, Path traceFile) {
41         mTraceFile = traceFile;
42         mOutputPath = outputDir;
43     }
44 
TraceMonitor(Path outputDir, String traceFileName)45     TraceMonitor(Path outputDir, String traceFileName) {
46         this(outputDir, TRACE_DIR.resolve(traceFileName));
47     }
48 
saveTrace(String testTag)49     protected Path saveTrace(String testTag) {
50         Path traceFileCopy = getOutputTraceFilePath(testTag);
51         moveFile(mTraceFile, traceFileCopy);
52 
53         return traceFileCopy;
54     }
55 
moveFile(Path src, Path dst)56     protected void moveFile(Path src, Path dst) {
57         // Move the  file to the output directory
58         // Note: Due to b/141386109, certain devices do not allow moving the files between
59         //       directories with different encryption policies, so manually copy and then
60         //       remove the original file
61         String copyCommand =
62                 String.format(Locale.getDefault(), "cp %s %s", src.toString(), dst.toString());
63         runShellCommand(copyCommand);
64         String removeCommand = String.format(Locale.getDefault(), "rm %s", src.toString());
65         runShellCommand(removeCommand);
66     }
67 
68     @VisibleForTesting
getOutputTraceFilePath(String testTag)69     public Path getOutputTraceFilePath(String testTag) {
70         return mOutputPath.resolve(testTag + "_" + mTraceFile.getFileName());
71     }
72 }
73