cheets_CTS: Clean up the server-side copy of media files after the first run.

After the files are pushed to the device, thes server side copy is no more
necessary. To free up the storage pressure on the autotest shard as soon as
possible, delete the files in the tmp directory.

BUG=chromium:970881
TEST=cheets_CTS_P.9.0_r8.arm.CtsMediaTestCases

Change-Id: Ibf3fb108c5bd126560611226fa2443e4fcfc6558
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/autotest/+/1645692
Tested-by: Kazuhiro Inaba <kinaba@chromium.org>
Reviewed-by: Ilja H. Friedel <ihf@chromium.org>
(cherry picked from commit 0791266b7236353dc27fdee28aeb4307cefda5f6)
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/autotest/+/1646794
Reviewed-by: Kazuhiro Inaba <kinaba@chromium.org>
diff --git a/server/cros/tradefed_test.py b/server/cros/tradefed_test.py
index ee28ac2..600517c 100644
--- a/server/cros/tradefed_test.py
+++ b/server/cros/tradefed_test.py
@@ -729,6 +729,16 @@
             self._num_media_bundles = len(
                     os.listdir(constants.TRADEFED_MEDIA_PATH))
 
+    def _cleanup_media(self):
+        """Clean up the local copy of cached media files."""
+        self._fail_on_unexpected_media_download()
+        if os.path.islink(constants.TRADEFED_MEDIA_PATH):
+            path = os.readlink(constants.TRADEFED_MEDIA_PATH)
+            os.unlink(constants.TRADEFED_MEDIA_PATH)
+            if os.path.isdir(path):
+                logging.info('Cleaning up media files in %s', path)
+                shutil.rmtree(path)
+
     def _fail_on_unexpected_media_download(self):
         if os.path.isdir(constants.TRADEFED_MEDIA_PATH):
             contents = os.listdir(constants.TRADEFED_MEDIA_PATH)
@@ -1111,6 +1121,13 @@
 
                 waived = len(waived_tests)
                 last_session_id, passed, failed, all_done = result
+
+                if passed + failed > 0:
+                    # At least one test had run, which means the media push step
+                    # of tradefed didn't fail. To free up the storage earlier,
+                    # delete the copy on the server side. See crbug.com/970881
+                    self._cleanup_media()
+
                 # If the result is |acc|urate according to the log, or the
                 # inaccuracy is recognized by tradefed (not all_done), then
                 # it is fine.