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