Revert "Test CompOS more directly."

This reverts commit a00d792a8f7f4bca3d4deae34abbbc0dcca02f2b.

Reason for revert: b/201047807

Change-Id: Ib874416a63879ff8cb2945b9841a89750bd9f9fa
diff --git a/compos/apk/assets/vm_test_config.json b/compos/apk/assets/vm_test_config.json
new file mode 100644
index 0000000..54a0aac
--- /dev/null
+++ b/compos/apk/assets/vm_test_config.json
@@ -0,0 +1,18 @@
+{
+    "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 940531b..61b6d47 100644
--- a/compos/tests/AndroidTest.xml
+++ b/compos/tests/AndroidTest.xml
@@ -18,6 +18,10 @@
         <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 2f3b243..00b002f 100644
--- a/compos/tests/java/android/compos/test/ComposKeyTestCase.java
+++ b/compos/tests/java/android/compos/test/ComposKeyTestCase.java
@@ -22,6 +22,7 @@
 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;
@@ -34,37 +35,44 @@
 @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 static final String INSTANCE_IMAGE = TEST_ROOT + "compos_instance.img";
+
+    private String mCid;
 
     @Before
     public void setUp() throws Exception {
         testIfDeviceIsCapable(getDevice());
+
+        prepareVirtualizationTestSetup(getDevice());
     }
 
     @After
     public void tearDown() throws Exception {
-        CommandRunner android = new CommandRunner(getDevice());
+        if (mCid != null) {
+            shutdownMicrodroid(getDevice(), mCid);
+            mCid = null;
+        }
 
-        // kill stale VMs and directories
-        android.tryRun("killall", "crosvm");
-        android.tryRun("rm", "-rf", "/data/misc/virtualizationservice/*");
-        android.tryRun("stop", "virtualizationservice");
+        cleanUpVirtualizationTestSetup(getDevice());
     }
 
-
     @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,
-                "--start " + INSTANCE_IMAGE,
+                "--cid " + mCid,
                 "generate",
                 TEST_ROOT + "test_key.blob",
                 TEST_ROOT + "test_key.pubkey");
@@ -72,7 +80,7 @@
         // Verify them - should also succeed, since we just generated them
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--start " + INSTANCE_IMAGE,
+                "--cid " + mCid,
                 "verify",
                 TEST_ROOT + "test_key.blob",
                 TEST_ROOT + "test_key.pubkey");
@@ -81,7 +89,7 @@
         result =
                 android.runForResult(
                         COMPOS_KEY_CMD_BIN,
-                        "--start " + INSTANCE_IMAGE,
+                        "--cid " + mCid,
                         "verify",
                         TEST_ROOT + "test_key.pubkey",
                         TEST_ROOT + "test_key.blob");
@@ -90,7 +98,7 @@
         // Generate another set of keys - should succeed
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--start " + INSTANCE_IMAGE,
+                "--cid " + mCid,
                 "generate",
                 TEST_ROOT + "test_key2.blob",
                 TEST_ROOT + "test_key2.pubkey");
@@ -98,7 +106,7 @@
         // They should also verify ok
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--start " + INSTANCE_IMAGE,
+                "--cid " + mCid,
                 "verify",
                 TEST_ROOT + "test_key2.blob",
                 TEST_ROOT + "test_key2.pubkey");
@@ -107,7 +115,7 @@
         result =
                 android.runForResult(
                         COMPOS_KEY_CMD_BIN,
-                        "--start " + INSTANCE_IMAGE,
+                        "--cid " + mCid,
                         "verify",
                         TEST_ROOT + "test_key.pubkey",
                         TEST_ROOT + "test_key2.blob");
@@ -118,18 +126,52 @@
         // 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,
-                "--start " + INSTANCE_IMAGE,
+                "--cid " + mCid,
                 "sign",
-                TEST_ROOT + "test_key2.blob",
+                TEST_ROOT + "test_key3.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 fb6b981..42a323f 100644
--- a/compos/tests/java/android/compos/test/ComposTestCase.java
+++ b/compos/tests/java/android/compos/test/ComposTestCase.java
@@ -22,6 +22,7 @@
 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;
@@ -36,10 +37,11 @@
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class ComposTestCase extends VirtualizationTestCaseBase {
 
-    // Binaries used in test. (These paths are valid both in host and Microdroid.)
+    /** Path to odrefresh on 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 =
@@ -48,34 +50,38 @@
     /** 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;
 
-    // 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";
+    private String mCid;
 
     @Before
     public void setUp() throws Exception {
         testIfDeviceIsCapable(getDevice());
+
+        prepareVirtualizationTestSetup(getDevice());
+
+        startComposVm();
     }
 
     @After
     public void tearDown() throws Exception {
-        CommandRunner android = new CommandRunner(getDevice());
+        if (mCid != null) {
+            shutdownMicrodroid(getDevice(), mCid);
+            mCid = null;
+        }
 
-        // kill stale VMs and directories
-        android.tryRun("killall", "crosvm");
-        android.tryRun("rm", "-rf", "/data/misc/virtualizationservice/*");
-        android.tryRun("stop", "virtualizationservice");
+        cleanUpVirtualizationTestSetup(getDevice());
     }
 
     @Test
     public void testOdrefresh() throws Exception {
+        waitForServiceRunning();
+
         CommandRunner android = new CommandRunner(getDevice());
 
         // Prepare the groundtruth. The compilation on Android should finish successfully.
@@ -97,26 +103,26 @@
                 android.runForResultWithTimeout(ODREFRESH_TIMEOUT_MS, ODREFRESH_BIN, "--check");
         assertThat(result.getExitCode()).isEqualTo(OKAY);
 
-        // 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
+        // Initialize the service with the generated key. Should succeed.
         android.run(
                 COMPOS_KEY_CMD_BIN,
-                "--start " + INSTANCE_IMAGE,
+                "--cid " + mCid,
                 "generate",
-                PRIVATE_KEY_BLOB,
-                PUBLIC_KEY);
+                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");
 
         // Expect the compilation in Compilation OS to finish successfully.
         {
             long start = System.currentTimeMillis();
-            result = android.runForResultWithTimeout(ODREFRESH_TIMEOUT_MS, COMPOSD_CMD_BIN);
+            result =
+                    android.runForResultWithTimeout(
+                            ODREFRESH_TIMEOUT_MS,
+                            ODREFRESH_BIN,
+                            "--use-compilation-os=" + mCid,
+                            "--force-compile");
             long elapsed = System.currentTimeMillis() - start;
-            assertThat(result.getExitCode()).isEqualTo(0);
+            assertThat(result.getExitCode()).isEqualTo(COMPILATION_SUCCESS);
             CLog.i("Comp OS compilation took " + elapsed + "ms");
         }
 
@@ -134,6 +140,32 @@
         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");