Test CompOS more directly.

Rather than using "vm --daemonize ..." to test, which is a slightly
unrealistic environment and doesn't exercise much of our client-side
code, use composd where we can.

A side-effect of this is that we no longer need to disable selinux for
the tests, nor do we need the special "don't log to stderr"
configuration.

Bug: 200924405
Test: atest ComposHostTestCases
Change-Id: I2c56ef0decb521a9208843fc54166e6778388879
diff --git a/compos/apk/assets/vm_test_config.json b/compos/apk/assets/vm_test_config.json
deleted file mode 100644
index 54a0aac..0000000
--- a/compos/apk/assets/vm_test_config.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
-    "version": 1,
-    "os": {
-        "name": "microdroid"
-    },
-    "task": {
-        "type": "executable",
-        "command": "/apex/com.android.compos/bin/compsvc"
-    },
-    "apexes": [
-        {
-            "name": "com.android.art"
-        },
-        {
-            "name": "com.android.compos"
-        }
-    ]
-}
\ No newline at end of file
diff --git a/compos/tests/AndroidTest.xml b/compos/tests/AndroidTest.xml
index 61b6d47..940531b 100644
--- a/compos/tests/AndroidTest.xml
+++ b/compos/tests/AndroidTest.xml
@@ -18,10 +18,6 @@
         <option name="force-root" value="true" />
     </target_preparer>
 
-    <!-- virtualizationservice doesn't have access to shell_data_file. Instead of giving it
-      a test-only permission, run it without selinux -->
-    <target_preparer class="com.android.tradefed.targetprep.DisableSELinuxTargetPreparer"/>
-
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="ComposHostTestCases.jar" />
     </test>
diff --git a/compos/tests/java/android/compos/test/ComposKeyTestCase.java b/compos/tests/java/android/compos/test/ComposKeyTestCase.java
index 00b002f..2f3b243 100644
--- a/compos/tests/java/android/compos/test/ComposKeyTestCase.java
+++ b/compos/tests/java/android/compos/test/ComposKeyTestCase.java
@@ -22,7 +22,6 @@
 import android.virt.test.CommandRunner;
 import android.virt.test.VirtualizationTestCaseBase;
 
-import com.android.compatibility.common.util.PollingCheck;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.util.CommandResult;
 import com.android.tradefed.util.CommandStatus;
@@ -35,44 +34,37 @@
 @RootPermissionTest
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class ComposKeyTestCase extends VirtualizationTestCaseBase {
-
-    /** Wait time for service to be ready on boot */
-    private static final int READY_LATENCY_MS = 10 * 1000; // 10 seconds
-
-    // Path to compos_key_cmd tool
     private static final String COMPOS_KEY_CMD_BIN = "/apex/com.android.compos/bin/compos_key_cmd";
-
-    private String mCid;
+    private static final String INSTANCE_IMAGE = TEST_ROOT + "compos_instance.img";
 
     @Before
     public void setUp() throws Exception {
         testIfDeviceIsCapable(getDevice());
-
-        prepareVirtualizationTestSetup(getDevice());
     }
 
     @After
     public void tearDown() throws Exception {
-        if (mCid != null) {
-            shutdownMicrodroid(getDevice(), mCid);
-            mCid = null;
-        }
+        CommandRunner android = new CommandRunner(getDevice());
 
-        cleanUpVirtualizationTestSetup(getDevice());
+        // kill stale VMs and directories
+        android.tryRun("killall", "crosvm");
+        android.tryRun("rm", "-rf", "/data/misc/virtualizationservice/*");
+        android.tryRun("stop", "virtualizationservice");
     }
 
+
     @Test
     public void testKeyService() throws Exception {
-        startVm();
-        waitForServiceRunning();
-
         CommandRunner android = new CommandRunner(getDevice());
         CommandResult result;
 
+        // Create an empty image file
+        android.run(COMPOS_KEY_CMD_BIN, "make-instance", INSTANCE_IMAGE);
+
         // Generate keys - should succeed
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--cid " + mCid,
+                "--start " + INSTANCE_IMAGE,
                 "generate",
                 TEST_ROOT + "test_key.blob",
                 TEST_ROOT + "test_key.pubkey");
@@ -80,7 +72,7 @@
         // Verify them - should also succeed, since we just generated them
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--cid " + mCid,
+                "--start " + INSTANCE_IMAGE,
                 "verify",
                 TEST_ROOT + "test_key.blob",
                 TEST_ROOT + "test_key.pubkey");
@@ -89,7 +81,7 @@
         result =
                 android.runForResult(
                         COMPOS_KEY_CMD_BIN,
-                        "--cid " + mCid,
+                        "--start " + INSTANCE_IMAGE,
                         "verify",
                         TEST_ROOT + "test_key.pubkey",
                         TEST_ROOT + "test_key.blob");
@@ -98,7 +90,7 @@
         // Generate another set of keys - should succeed
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--cid " + mCid,
+                "--start " + INSTANCE_IMAGE,
                 "generate",
                 TEST_ROOT + "test_key2.blob",
                 TEST_ROOT + "test_key2.pubkey");
@@ -106,7 +98,7 @@
         // They should also verify ok
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--cid " + mCid,
+                "--start " + INSTANCE_IMAGE,
                 "verify",
                 TEST_ROOT + "test_key2.blob",
                 TEST_ROOT + "test_key2.pubkey");
@@ -115,7 +107,7 @@
         result =
                 android.runForResult(
                         COMPOS_KEY_CMD_BIN,
-                        "--cid " + mCid,
+                        "--start " + INSTANCE_IMAGE,
                         "verify",
                         TEST_ROOT + "test_key.pubkey",
                         TEST_ROOT + "test_key2.blob");
@@ -126,52 +118,18 @@
         // very slow, a new test method unfortunately makes the whole test module to exceed the
         // timeout configured in the test infrastructure.
 
-        // Generate key - should succeed
-        android.run(
-                COMPOS_KEY_CMD_BIN,
-                "--cid " + mCid,
-                "generate",
-                TEST_ROOT + "test_key3.blob",
-                TEST_ROOT + "test_key3.pubkey");
-
         // Generate some data to sign in a writable directory
         android.run("echo something > /data/local/tmp/something.txt");
 
         // Sign something - should succeed
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--cid " + mCid,
+                "--start " + INSTANCE_IMAGE,
                 "sign",
-                TEST_ROOT + "test_key3.blob",
+                TEST_ROOT + "test_key2.blob",
                 "/data/local/tmp/something.txt");
 
         // Check existence of the output signature - should succeed
         android.run("test -f /data/local/tmp/something.txt.signature");
     }
-
-    private void startVm() throws Exception {
-        final String apkName = "CompOSPayloadApp.apk";
-        final String packageName = "com.android.compos.payload";
-        mCid =
-                startMicrodroid(
-                        getDevice(),
-                        getBuild(),
-                        apkName,
-                        packageName,
-                        "assets/vm_test_config.json",
-                        /* debug */ false);
-        adbConnectToMicrodroid(getDevice(), mCid);
-    }
-
-    private void waitForServiceRunning() {
-        try {
-            PollingCheck.waitFor(READY_LATENCY_MS, this::isServiceRunning);
-        } catch (Exception e) {
-            throw new RuntimeException("Service unavailable", e);
-        }
-    }
-
-    private boolean isServiceRunning() {
-        return tryRunOnMicrodroid("pidof compsvc") != null;
-    }
 }
diff --git a/compos/tests/java/android/compos/test/ComposTestCase.java b/compos/tests/java/android/compos/test/ComposTestCase.java
index 42a323f..fb6b981 100644
--- a/compos/tests/java/android/compos/test/ComposTestCase.java
+++ b/compos/tests/java/android/compos/test/ComposTestCase.java
@@ -22,7 +22,6 @@
 import android.virt.test.CommandRunner;
 import android.virt.test.VirtualizationTestCaseBase;
 
-import com.android.compatibility.common.util.PollingCheck;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
@@ -37,11 +36,10 @@
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class ComposTestCase extends VirtualizationTestCaseBase {
 
-    /** Path to odrefresh on Microdroid */
+    // Binaries used in test. (These paths are valid both in host and Microdroid.)
     private static final String ODREFRESH_BIN = "/apex/com.android.art/bin/odrefresh";
-
-    /** Path to compos_key_cmd on Microdroid */
     private static final String COMPOS_KEY_CMD_BIN = "/apex/com.android.compos/bin/compos_key_cmd";
+    private static final String COMPOSD_CMD_BIN = "/apex/com.android.compos/bin/composd_cmd";
 
     /** Output directory of odrefresh */
     private static final String ODREFRESH_OUTPUT_DIR =
@@ -50,38 +48,34 @@
     /** Timeout of odrefresh to finish */
     private static final int ODREFRESH_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
 
-    /** Wait time for compsvc to be ready on boot */
-    private static final int COMPSVC_READY_LATENCY_MS = 10 * 1000; // 10 seconds
-
     // ExitCode expanded from art/odrefresh/include/odrefresh/odrefresh.h.
     private static final int OKAY = 0;
     private static final int COMPILATION_SUCCESS = 80;
 
-    private String mCid;
+    // Files that define the "current" instance of CompOS
+    private static final String COMPOS_CURRENT_ROOT =
+            "/data/misc/apexdata/com.android.compos/current/";
+    private static final String INSTANCE_IMAGE = COMPOS_CURRENT_ROOT + "instance.img";
+    private static final String PUBLIC_KEY = COMPOS_CURRENT_ROOT + "key.pubkey";
+    private static final String PRIVATE_KEY_BLOB = COMPOS_CURRENT_ROOT + "key.blob";
 
     @Before
     public void setUp() throws Exception {
         testIfDeviceIsCapable(getDevice());
-
-        prepareVirtualizationTestSetup(getDevice());
-
-        startComposVm();
     }
 
     @After
     public void tearDown() throws Exception {
-        if (mCid != null) {
-            shutdownMicrodroid(getDevice(), mCid);
-            mCid = null;
-        }
+        CommandRunner android = new CommandRunner(getDevice());
 
-        cleanUpVirtualizationTestSetup(getDevice());
+        // kill stale VMs and directories
+        android.tryRun("killall", "crosvm");
+        android.tryRun("rm", "-rf", "/data/misc/virtualizationservice/*");
+        android.tryRun("stop", "virtualizationservice");
     }
 
     @Test
     public void testOdrefresh() throws Exception {
-        waitForServiceRunning();
-
         CommandRunner android = new CommandRunner(getDevice());
 
         // Prepare the groundtruth. The compilation on Android should finish successfully.
@@ -103,26 +97,26 @@
                 android.runForResultWithTimeout(ODREFRESH_TIMEOUT_MS, ODREFRESH_BIN, "--check");
         assertThat(result.getExitCode()).isEqualTo(OKAY);
 
-        // Initialize the service with the generated key. Should succeed.
+        // Make sure the CompOS current directory actually exists
+        android.run("mkdir", "-p", COMPOS_CURRENT_ROOT);
+
+        // Create an empty image file
+        android.run(COMPOS_KEY_CMD_BIN, "make-instance", INSTANCE_IMAGE);
+
+        // Generate keys - should succeed
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--cid " + mCid,
+                "--start " + INSTANCE_IMAGE,
                 "generate",
-                TEST_ROOT + "test_key.blob",
-                TEST_ROOT + "test_key.pubkey");
-        android.run(COMPOS_KEY_CMD_BIN, "--cid " + mCid, "init-key", TEST_ROOT + "test_key.blob");
+                PRIVATE_KEY_BLOB,
+                PUBLIC_KEY);
 
         // Expect the compilation in Compilation OS to finish successfully.
         {
             long start = System.currentTimeMillis();
-            result =
-                    android.runForResultWithTimeout(
-                            ODREFRESH_TIMEOUT_MS,
-                            ODREFRESH_BIN,
-                            "--use-compilation-os=" + mCid,
-                            "--force-compile");
+            result = android.runForResultWithTimeout(ODREFRESH_TIMEOUT_MS, COMPOSD_CMD_BIN);
             long elapsed = System.currentTimeMillis() - start;
-            assertThat(result.getExitCode()).isEqualTo(COMPILATION_SUCCESS);
+            assertThat(result.getExitCode()).isEqualTo(0);
             CLog.i("Comp OS compilation took " + elapsed + "ms");
         }
 
@@ -140,32 +134,6 @@
         assertThat(actualChecksumSnapshot).isEqualTo(expectedChecksumSnapshot);
     }
 
-    private void startComposVm() throws DeviceNotAvailableException {
-        final String apkName = "CompOSPayloadApp.apk";
-        final String packageName = "com.android.compos.payload";
-        mCid =
-                startMicrodroid(
-                        getDevice(),
-                        getBuild(),
-                        apkName,
-                        packageName,
-                        "assets/vm_test_config.json",
-                        /* debug */ false);
-        adbConnectToMicrodroid(getDevice(), mCid);
-    }
-
-    private void waitForServiceRunning() {
-        try {
-            PollingCheck.waitFor(COMPSVC_READY_LATENCY_MS, this::isServiceRunning);
-        } catch (Exception e) {
-            throw new RuntimeException("Service unavailable", e);
-        }
-    }
-
-    private boolean isServiceRunning() {
-        return tryRunOnMicrodroid("pidof compsvc") != null;
-    }
-
     private String checksumDirectoryContent(CommandRunner runner, String path)
             throws DeviceNotAvailableException {
         return runner.run("find " + path + " -type f -exec sha256sum {} \\; | sort");