summaryrefslogtreecommitdiff
path: root/tests/BackgroundDexOptServiceIntegrationTests/src/com/android/server/pm/BackgroundDexOptServiceIntegrationTests.java
blob: 90ddb6ffb34ab1f53ef29d4eb705b867d96913a1 (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) 2017 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.server.pm;

import android.app.AlarmManager;
import android.content.Context;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
import android.os.SystemProperties;
import android.os.storage.StorageManager;
import android.util.Log;

import androidx.test.InstrumentationRegistry;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * Integration tests for {@link BackgroundDexOptService}.
 *
 * Tests various scenarios around BackgroundDexOptService.
 * 1. Under normal conditions, check that dexopt upgrades test app to
 * $(getprop pm.dexopt.bg-dexopt).
 * 2. Under low storage conditions and package is unused, check
 * that dexopt downgrades test app to $(getprop pm.dexopt.inactive).
 * 3. Under low storage conditions and package is recently used, check
 * that dexopt upgrades test app to $(getprop pm.dexopt.bg-dexopt).
 *
 * Each test case runs "cmd package bg-dexopt-job com.android.frameworks.bgdexopttest".
 *
 * The setup for these tests make sure this package has been configured to have been recently used
 * plus installed far enough in the past. If a test case requires that this package has not been
 * recently used, it sets the time forward more than
 * `getprop pm.dexopt.downgrade_after_inactive_days` days.
 *
 * For tests that require low storage, the phone is filled up.
 *
 * Run with "atest BackgroundDexOptServiceIntegrationTests".
 */
@RunWith(JUnit4.class)
public final class BackgroundDexOptServiceIntegrationTests {

    private static final String TAG = BackgroundDexOptServiceIntegrationTests.class.getSimpleName();

    // Name of package to test on.
    private static final String PACKAGE_NAME = "com.android.frameworks.bgdexopttest";
    // Name of file used to fill up storage.
    private static final String BIG_FILE = "bigfile";
    private static final String BG_DEXOPT_COMPILER_FILTER = SystemProperties.get(
            "pm.dexopt.bg-dexopt");
    private static final String DOWNGRADE_COMPILER_FILTER = SystemProperties.get(
            "pm.dexopt.inactive");
    private static final long DOWNGRADE_AFTER_DAYS = SystemProperties.getLong(
            "pm.dexopt.downgrade_after_inactive_days", 0);
    // Needs to be between 1.0 and 2.0.
    private static final double LOW_STORAGE_MULTIPLIER = 1.5;

    // The file used to fill up storage.
    private File mBigFile;

    // Remember start time.
    @BeforeClass
    public static void setUpAll() {
        if (!SystemProperties.getBoolean("pm.dexopt.disable_bg_dexopt", false)) {
            throw new RuntimeException(
                    "bg-dexopt is not disabled (set pm.dexopt.disable_bg_dexopt to true)");
        }
        if (DOWNGRADE_AFTER_DAYS < 1) {
            throw new RuntimeException(
                    "pm.dexopt.downgrade_after_inactive_days must be at least 1");
        }
        if ("quicken".equals(BG_DEXOPT_COMPILER_FILTER)) {
            throw new RuntimeException("pm.dexopt.bg-dexopt should not be \"quicken\"");
        }
        if ("quicken".equals(DOWNGRADE_COMPILER_FILTER)) {
            throw new RuntimeException("pm.dexopt.inactive should not be \"quicken\"");
        }
    }


    private static Context getContext() {
        return InstrumentationRegistry.getTargetContext();
    }

    @Before
    public void setUp() throws IOException {
        File dataDir = getContext().getDataDir();
        mBigFile = new File(dataDir, BIG_FILE);
    }

    @After
    public void tearDown() {
        if (mBigFile.exists()) {
            boolean result = mBigFile.delete();
            if (!result) {
                throw new RuntimeException("Couldn't delete big file");
            }
        }
    }

    // Return the content of the InputStream as a String.
    private static String inputStreamToString(InputStream is) throws IOException {
        char[] buffer = new char[1024];
        StringBuilder builder = new StringBuilder();
        try (InputStreamReader reader = new InputStreamReader(is)) {
            for (; ; ) {
                int count = reader.read(buffer, 0, buffer.length);
                if (count < 0) {
                    break;
                }
                builder.append(buffer, 0, count);
            }
        }
        return builder.toString();
    }

    // Run the command and return the stdout.
    private static String runShellCommand(String cmd) throws IOException {
        Log.i(TAG, String.format("running command: '%s'", cmd));
        ParcelFileDescriptor pfd = InstrumentationRegistry.getInstrumentation().getUiAutomation()
                .executeShellCommand(cmd);
        byte[] buf = new byte[512];
        int bytesRead;
        FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
        StringBuilder stdout = new StringBuilder();
        while ((bytesRead = fis.read(buf)) != -1) {
            stdout.append(new String(buf, 0, bytesRead));
        }
        fis.close();
        Log.i(TAG, "stdout");
        Log.i(TAG, stdout.toString());
        return stdout.toString();
    }

    // Run the command and return the stdout split by lines.
    private static String[] runShellCommandSplitLines(String cmd) throws IOException {
        return runShellCommand(cmd).split("\n");
    }

    // Return the compiler filter of a package.
    private static String getCompilerFilter(String pkg) throws IOException {
        String cmd = String.format("dumpsys package %s", pkg);
        String[] lines = runShellCommandSplitLines(cmd);
        final String substr = "[status=";
        for (String line : lines) {
            int startIndex = line.indexOf(substr);
            if (startIndex < 0) {
                continue;
            }
            startIndex += substr.length();
            int endIndex = line.indexOf(']', startIndex);
            return line.substring(startIndex, endIndex);
        }
        throw new RuntimeException("Couldn't find compiler filter in dumpsys package");
    }

    // Return the number of bytes available in the data partition.
    private static long getDataDirUsableSpace() {
        return Environment.getDataDirectory().getUsableSpace();
    }

    // Fill up the storage until there are bytesRemaining number of bytes available in the data
    // partition. Writes to the current package's data directory.
    private void fillUpStorage(long bytesRemaining) throws IOException {
        Log.i(TAG, String.format("Filling up storage with %d bytes remaining", bytesRemaining));
        logSpaceRemaining();
        long numBytesToAdd = getDataDirUsableSpace() - bytesRemaining;
        String cmd = String.format("fallocate -l %d %s", numBytesToAdd, mBigFile.getAbsolutePath());
        runShellCommand(cmd);
        logSpaceRemaining();
    }

    // Fill up storage so that device is in low storage condition.
    private void fillUpToLowStorage() throws IOException {
        fillUpStorage((long) (getStorageLowBytes() * LOW_STORAGE_MULTIPLIER));
    }

    private static void runBackgroundDexOpt() throws IOException {
        runBackgroundDexOpt("Success");
    }

    // TODO(aeubanks): figure out how to get scheduled bg-dexopt to run
    private static void runBackgroundDexOpt(String expectedStatus) throws IOException {
        String result = runShellCommand("cmd package bg-dexopt-job " + PACKAGE_NAME);
        if (!result.trim().equals(expectedStatus)) {
            throw new IllegalStateException("Expected status: " + expectedStatus
                + "; Received: " + result.trim());
        }
    }

    // Set the time ahead of the last use time of the test app in days.
    private static void setTimeFutureDays(long futureDays) {
        setTimeFutureMillis(TimeUnit.DAYS.toMillis(futureDays));
    }

    // Set the time ahead of the last use time of the test app in milliseconds.
    private static void setTimeFutureMillis(long futureMillis) {
        long currentTime = System.currentTimeMillis();
        setTime(currentTime + futureMillis);
    }

    private static void setTime(long time) {
        AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
        am.setTime(time);
    }

    // Return the number of free bytes when the data partition is considered low on storage.
    private static long getStorageLowBytes() {
        StorageManager storageManager = (StorageManager) getContext().getSystemService(
                Context.STORAGE_SERVICE);
        return storageManager.getStorageLowBytes(Environment.getDataDirectory());
    }

    // Log the amount of space remaining in the data directory.
    private static void logSpaceRemaining() throws IOException {
        runShellCommand("df -h /data");
    }

    // Compile the given package with the given compiler filter.
    private static void compilePackageWithFilter(String pkg, String filter) throws IOException {
        runShellCommand(String.format("cmd package compile -f -m %s %s", filter, pkg));
    }

    // Override the thermal status of the device
    public static void overrideThermalStatus(int status) throws IOException {
        runShellCommand("cmd thermalservice override-status " + status);
    }

    // Reset the thermal status of the device
    public static void resetThermalStatus() throws IOException {
        runShellCommand("cmd thermalservice reset");
    }

    // Test that background dexopt under normal conditions succeeds.
    @Test
    public void testBackgroundDexOpt() throws IOException {
        // Set filter to quicken.
        compilePackageWithFilter(PACKAGE_NAME, "verify");
        Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME));

        runBackgroundDexOpt();

        // Verify that bg-dexopt is successful.
        Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
    }

    // Test that background dexopt under low storage conditions upgrades used packages.
    @Test
    public void testBackgroundDexOptDowngradeSkipRecentlyUsedPackage() throws IOException {
        // Should be less than DOWNGRADE_AFTER_DAYS.
        long deltaDays = DOWNGRADE_AFTER_DAYS - 1;
        try {
            // Set time to future.
            setTimeFutureDays(deltaDays);

            // Set filter to verify.
            compilePackageWithFilter(PACKAGE_NAME, "verify");
            Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME));

            // Fill up storage to trigger low storage threshold.
            fillUpToLowStorage();

            runBackgroundDexOpt();

            // Verify that downgrade did not happen.
            Assert.assertEquals(BG_DEXOPT_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
        } finally {
            // Reset time.
            setTimeFutureDays(-deltaDays);
        }
    }

    // Test that background dexopt under low storage conditions downgrades unused packages.
    @Test
    public void testBackgroundDexOptDowngradeSuccessful() throws IOException {
        // Should be more than DOWNGRADE_AFTER_DAYS.
        long deltaDays = DOWNGRADE_AFTER_DAYS + 1;
        try {
            // Set time to future.
            setTimeFutureDays(deltaDays);

            // Set filter to speed-profile.
            compilePackageWithFilter(PACKAGE_NAME, "speed-profile");
            Assert.assertEquals("speed-profile", getCompilerFilter(PACKAGE_NAME));

            // Fill up storage to trigger low storage threshold.
            fillUpToLowStorage();

            runBackgroundDexOpt();

            // Verify that downgrade is successful.
            Assert.assertEquals(DOWNGRADE_COMPILER_FILTER, getCompilerFilter(PACKAGE_NAME));
        } finally {
            // Reset time.
            setTimeFutureDays(-deltaDays);
        }
    }

    // Test that background dexopt job doesn't trigger if the device is under thermal throttling.
    @Test
    public void testBackgroundDexOptThermalThrottling() throws IOException {
        try {
            compilePackageWithFilter(PACKAGE_NAME, "verify");
            overrideThermalStatus(PowerManager.THERMAL_STATUS_MODERATE);
            // The bgdexopt task should fail when onStartJob is run
            runBackgroundDexOpt("Failure");
            Assert.assertEquals("verify", getCompilerFilter(PACKAGE_NAME));
        } finally {
            resetThermalStatus();
        }
    }
}