Debian Codegraph @

tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2017 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.pm;
18
19 import android.app.AlarmManager;
20 import android.content.Context;
21 import android.os.Environment;
22 import android.os.ParcelFileDescriptor;
23 import android.os.PowerManager;
24 import android.os.SystemProperties;
25 import android.os.storage.StorageManager;
26 import android.util.Log;
27
28 import androidx.test.InstrumentationRegistry;
29
30 import org.junit.After;
31 import org.junit.Assert;
32 import org.junit.Before;
33 import org.junit.BeforeClass;
34 import org.junit.Ignore;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.junit.runners.JUnit4;
38
39 import java.io.File;
40 import java.io.FileInputStream;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.InputStreamReader;
44 import java.util.concurrent.TimeUnit;
45
46 /**
47 * Integration tests for {@link BackgroundDexOptService}.
48 *
49 * Tests various scenarios around BackgroundDexOptService.
50 * 1. Under normal conditions, check that dexopt upgrades test app to
51 * $(getprop pm.dexopt.bg-dexopt).
52 * 2. Under low storage conditions and package is unused, check
53 * that dexopt downgrades test app to $(getprop pm.dexopt.inactive).
54 * 3. Under low storage conditions and package is recently used, check
55 * that dexopt upgrades test app to $(getprop pm.dexopt.bg-dexopt).
56 *
57 * Each test case runs "cmd package bg-dexopt-job com.android.frameworks.bgdexopttest".
58 *
59 * The setup for these tests make sure this package has been configured to have been recently used
60 * plus installed far enough in the past. If a test case requires that this package has not been
61 * recently used, it sets the time forward more than
62 * `getprop pm.dexopt.downgrade_after_inactive_days` days.
63 *
64 * For tests that require low storage, the phone is filled up.
65 *
66 * Run with "atest BackgroundDexOptServiceIntegrationTests".
67 */
68 @RunWith(JUnit4.class)
69 public final class BackgroundDexOptServiceIntegrationTests {
70
71 private static final String TAG = BackgroundDexOptServiceIntegrationTests.class.getSimpleName();
72
73 // Name of package to test on.
74 private static final String PACKAGE_NAME = "com.android.frameworks.bgdexopttest";
75 // Name of file used to fill up storage.
76 private static final String BIG_FILE = "bigfile";
77 private static final String BG_DEXOPT_COMPILER_FILTER = SystemProperties.get(
78 "pm.dexopt.bg-dexopt");
79 private static final String DOWNGRADE_COMPILER_FILTER = SystemProperties.get(
80 "pm.dexopt.inactive");
81 private static final long DOWNGRADE_AFTER_DAYS = SystemProperties.getLong(
82 "pm.dexopt.downgrade_after_inactive_days", 0);
83 // Needs to be between 1.0 and 2.0.
84 private static final double LOW_STORAGE_MULTIPLIER = 1.5;
85
86 // The file used to fill up storage.
87 private File mBigFile;
88
89 // Remember start time.
90 @BeforeClass
91 public static void setUpAll() {
92 if (!SystemProperties.getBoolean("pm.dexopt.disable_bg_dexopt", false)) {
93 throw new RuntimeException(
94 "bg-dexopt is not disabled (set pm.dexopt.disable_bg_dexopt to true)");
95 }
96 if (DOWNGRADE_AFTER_DAYS < 1) {
97 throw new RuntimeException(
98 "pm.dexopt.downgrade_after_inactive_days must be at least 1");
99 }
100 if ("quicken".equals(BG_DEXOPT_COMPILER_FILTER)) {
101 throw new RuntimeException("pm.dexopt.bg-dexopt should not be \"quicken\"");
102 }
103 if ("quicken".equals(DOWNGRADE_COMPILER_FILTER)) {
104 throw new RuntimeException("pm.dexopt.inactive should not be \"quicken\"");
105 }
106 }
107
108
109 private static Context getContext() {
110 return InstrumentationRegistry.getTargetContext();
111 }
112
113 @Before
114 public void setUp() throws IOException {
115 File dataDir = getContext().getDataDir();
116 mBigFile = new File(dataDir, BIG_FILE);
117 }
118
119 @After
120 public void tearDown() {
121 if (mBigFile.exists()) {
122 boolean result = mBigFile.delete();
123 if (!result) {
124 throw new RuntimeException("Couldn't delete big file");
125 }
126 }
127 }
128
129 // Return the content of the InputStream as a String.
130 private static String inputStreamToString(InputStream is) throws IOException {
131 char[] buffer = new char[1024];
132 StringBuilder builder = new StringBuilder();
133 try (InputStreamReader reader = new InputStreamReader(is)) {
134 for (; ; ) {
135 int count = reader.read(buffer, 0, buffer.length);
136 if (count < 0) {
137 break;
138 }
139 builder.append(buffer, 0, count);
140 }
141 }
142 return builder.toString();
143 }
144
145 // Run the command and return the stdout.
146 private static String runShellCommand(String cmd) throws IOException {
147 Log.i(TAG, String.format("running command: '%s'", cmd));
148 ParcelFileDescriptor pfd = InstrumentationRegistry.getInstrumentation().getUiAutomation()
149 .executeShellCommand(cmd);
150 byte[] buf = new byte[512];
151 int bytesRead;
152 FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
153 StringBuilder stdout = new StringBuilder();
154 while ((bytesRead = fis.read(buf)) != -1) {
155 stdout.append(new String(buf, 0, bytesRead));
156 }
157 fis.close();
158 Log.i(TAG, "stdout");
159 Log.i(TAG, stdout.toString());
160 return stdout.toString();
161 }
162
163 // Run the command and return the stdout split by lines.
164 private static String[] runShellCommandSplitLines(String cmd) throws IOException {
165 return runShellCommand(cmd).split("\n");
166 }
167
168 // Return the compiler filter of a package.
169 private static String getCompilerFilter(String pkg) throws IOException {
170 String cmd = String.format("dumpsys package %s", pkg);
171 String[] lines = runShellCommandSplitLines(cmd);
172 final String substr = "[status=";
173 for (String line : lines) {
174 int startIndex = line.indexOf(substr);
175 if (startIndex < 0) {
176 continue;
177 }
178 startIndex += substr.length();
179 int endIndex = line.indexOf(']', startIndex);
180 return line.substring(startIndex, endIndex);
181 }
182 throw new RuntimeException("Couldn't find compiler filter in dumpsys package");
183 }
184
185 // Return the number of bytes available in the data partition.
186 private static long getDataDirUsableSpace() {
187 return Environment.getDataDirectory().getUsableSpace();
188 }
189
190 // Fill up the storage until there are bytesRemaining number of bytes available in the data
191 // partition. Writes to the current package's data directory.
192 private void fillUpStorage(long bytesRemaining) throws IOException {
193 Log.i(TAG, String.format("Filling up storage with %d bytes remaining", bytesRemaining));
194 logSpaceRemaining();
195 long numBytesToAdd = getDataDirUsableSpace() - bytesRemaining;
196 String cmd = String.format("fallocate -l %d %s", numBytesToAdd, mBigFile.getAbsolutePath());
197 runShellCommand(cmd);
198 logSpaceRemaining();
199 }
200
201 // Fill up storage so that device is in low storage condition.
202 private void fillUpToLowStorage() throws IOException {
203 fillUpStorage((long) (getStorageLowBytes() * LOW_STORAGE_MULTIPLIER));
204 }
205
206 private static void runBackgroundDexOpt() throws IOException {
207 runBackgroundDexOpt("Success");
208 }
209
210 // TODO(aeubanks): figure out how to get scheduled bg-dexopt to run
211 private static void runBackgroundDexOpt(String expectedStatus) throws IOException {
212 String result = runShellCommand("cmd package bg-dexopt-job " + PACKAGE_NAME);
213 if (!result.trim().equals(expectedStatus)) {
214 throw new IllegalStateException("Expected status: " + expectedStatus
215 + "; Received: " + result.trim());
216 }
217 }
218
219 // Set the time ahead of the last use time of the test app in days.
220 private static void setTimeFutureDays(long futureDays) {
221 setTimeFutureMillis(TimeUnit.DAYS.toMillis(futureDays));
222 }
223
224 // Set the time ahead of the last use time of the test app in milliseconds.
225 private static void setTimeFutureMillis(long futureMillis) {
226 long currentTime = System.currentTimeMillis();
227 setTime(currentTime + futureMillis);
228 }
229
230 private static void setTime(long time) {
231 AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
232 am.setTime(time);
233 }
234
235 // Return the number of free bytes when the data partition is considered low on storage.
236 private static long getStorageLowBytes() {
237 StorageManager storageManager = (StorageManager) getContext().getSystemService(
238 Context.STORAGE_SERVICE);
239 return storageManager.getStorageLowBytes(Environment.getDataDirectory());
240 }
241
242 // Log the amount of space remaining in the data directory.
243 private static void logSpaceRemaining() throws IOException {
244 runShellCommand("df -h /data");
245 }
246
247 // Compile the given package with the given compiler filter.
248 private static void compilePackageWithFilter(String pkg, String filter) throws IOException {
249 runShellCommand(String.format("cmd package compile -f -m %s %s", filter, pkg));
250 }
251
252 // Override the thermal status of the device
253 public static void overrideThermalStatus(int status) throws IOException {
254 runShellCommand("cmd thermalservice override-status " + status);
255 }
256
257 // Reset the thermal status of the device
258 public static void resetThermalStatus() throws IOException {
259 runShellCommand("cmd thermalservice reset");
260 }
261
262 // Test that background dexopt under normal conditions succeeds.
263 @Test
264 public void testBackgroundDexOpt() throws IOException {
265 // Set filter to quicken.
266 compilePackageWithFilter(PACKAGE_NAME, "verify");
267 Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME));
268
269 runBackgroundDexOpt();
270
271 // Verify that bg-dexopt is successful.
272 Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
273 }
274
275 // Test that background dexopt under low storage conditions upgrades used packages.
276 @Test
277 public void testBackgroundDexOptDowngradeSkipRecentlyUsedPackage() throws IOException {
278 // Should be less than DOWNGRADE_AFTER_DAYS.
279 long deltaDays = DOWNGRADE_AFTER_DAYS - 1;
280 try {
281 // Set time to future.
282 setTimeFutureDays(deltaDays);
283
284 // Set filter to verify.
285 compilePackageWithFilter(PACKAGE_NAME, "verify");
286 Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME));
287
288 // Fill up storage to trigger low storage threshold.
289 fillUpToLowStorage();
290
291 runBackgroundDexOpt();
292
293 // Verify that downgrade did not happen.
294 Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
295 } finally {
296 // Reset time.
297 setTimeFutureDays(-deltaDays);
298 }
299 }
300
301 // Test that background dexopt under low storage conditions downgrades unused packages.
302 @Test
303 @Ignore("b/251438180: This test has been failing for a long time; temporarily disable it while"
304 + " we investigate this issue.")
305 public void testBackgroundDexOptDowngradeSuccessful() throws IOException {
306 // Should be more than DOWNGRADE_AFTER_DAYS.
307 long deltaDays = DOWNGRADE_AFTER_DAYS + 1;
308 try {
309 // Set time to future.
310 setTimeFutureDays(deltaDays);
311
312 // Set filter to speed-profile.
313 compilePackageWithFilter(PACKAGE_NAME, "speed-profile");
314 Assert.assertEquals("speed-profile", getCompilerFilter(PACKAGE_NAME));
315
316 // Fill up storage to trigger low storage threshold.
317 fillUpToLowStorage();
318
319 runBackgroundDexOpt();
320
321 // Verify that downgrade is successful.
322 Assert.assertEquals(DOWNGRADE_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
323 } finally {
324 // Reset time.
325 setTimeFutureDays(-deltaDays);
326 }
327 }
328
329 // Test that background dexopt job doesn't trigger if the device is under thermal throttling.
330 @Test
331 public void testBackgroundDexOptThermalThrottling() throws IOException {
332 try {
333 compilePackageWithFilter(PACKAGE_NAME, "verify");
334 overrideThermalStatus(PowerManager.THERMAL_STATUS_MODERATE);
335 // The bgdexopt task should fail when onStartJob is run
336 runBackgroundDexOpt("Failure");
337 Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME));
338 } finally {
339 resetThermalStatus();
340 }
341 }
342 }