[autotest] delete stage dir for attempt to download a non-existing build

The leaking staged.timestamp and stage dir is causing script used in lab to
consider a non-existing build to be the latest build. Clean up such file/
directory helps to avoid such confusion.

BUG=chromium:229091
TEST=tested with download url in local devserver:
http://dshi.mtv:8080/download?archive_url=gs://chromeos-image-archive/x86-
generic/R17-1208.0.0-a1-b338
DEPLOY=none

Change-Id: Ifce8a75a1d891471875eabed0f434bd5aaf710e3
Reviewed-on: https://gerrit.chromium.org/gerrit/60165
Tested-by: Dan Shi <dshi@chromium.org>
Reviewed-by: Chris Sosa <sosa@chromium.org>
Commit-Queue: Dan Shi <dshi@chromium.org>
diff --git a/downloader.py b/downloader.py
index 2567e92..e19c84f 100755
--- a/downloader.py
+++ b/downloader.py
@@ -7,6 +7,7 @@
 
 import build_artifact
 import common_util
+import gsutil_util
 import log_util
 
 
@@ -75,6 +76,22 @@
     with file(file_name, 'a'):
       os.utime(file_name, None)
 
+  @staticmethod
+  def _TryRemoveStageDir(directory_path):
+    """If download failed with GSUtilError, try to remove the stage dir.
+
+    If the download attempt failed with GSUtilError and staged.timestamp is the
+    only file in that directory. The build could be non-existing, and the
+    directory should be removed.
+
+    @param directory_path: directory used to stage the image.
+
+    """
+    file_name = os.path.join(directory_path, Downloader._TIMESTAMP_FILENAME)
+    if os.path.exists(file_name) and len(os.listdir(directory_path)) == 1:
+      os.remove(file_name)
+      os.rmdir(directory_path)
+
   def Download(self, artifacts):
     """Downloads and caches the |artifacts|.
 
@@ -103,7 +120,11 @@
     required_artifacts = factory.RequiredArtifacts()
     str_repr = [str(a) for a in required_artifacts]
     self._Log('Downloading artifacts %s.', ' '.join(str_repr))
-    self._DownloadArtifactsSerially(required_artifacts, no_wait=True)
+    try:
+      self._DownloadArtifactsSerially(required_artifacts, no_wait=True)
+    except gsutil_util.GSUtilError:
+      Downloader._TryRemoveStageDir(self._build_dir)
+      raise
 
   def _DownloadArtifactsSerially(self, artifacts, no_wait):
     """Simple function to download all the given artifacts serially.