downloader: attempt to fix perms on build dir creation failure

The permissions in the static directory often get messed up and
this causes failures trying to download artifacts for e.g. cros
flash. Try to fix the permissions when this happens.

BUG=None
TEST=mess up permissions manually and then try to cros flash for
  a board that has messed up perms on the directory but for which
  the artifact in question has not yet been downloaded

Change-Id: I70fe292d237c497d908f55e1d87765abaf44bd90
Reviewed-on: https://chromium-review.googlesource.com/1481241
Commit-Ready: Eric Caruso <ejcaruso@chromium.org>
Tested-by: Eric Caruso <ejcaruso@chromium.org>
Reviewed-by: Amin Hassani <ahassani@chromium.org>
Reviewed-by: Kirtika Ruchandani <kirtika@chromium.org>
diff --git a/downloader.py b/downloader.py
index 95e8d63..8afdda9 100755
--- a/downloader.py
+++ b/downloader.py
@@ -9,10 +9,12 @@
 from __future__ import print_function
 
 import collections
+import errno
 import glob
 import os
 import re
 import shutil
+import subprocess
 import threading
 from datetime import datetime
 
@@ -169,13 +171,24 @@
     the background following the principle of spatial locality.
 
     Args:
-     factory: The artifact factory.
-     async: If True, return without waiting for download to complete.
+      factory: The artifact factory.
+      async: If True, return without waiting for download to complete.
 
     Raises:
       build_artifact.ArtifactDownloadError: If failed to download the artifact.
     """
-    common_util.MkDirP(self._build_dir)
+    try:
+      common_util.MkDirP(self._build_dir)
+    except OSError as e:
+      if e.errno != errno.EACCES:
+        raise
+      self._Log('Could not create build dir due to permissions issue. '
+                'Attempting to fix permissions.')
+      subprocess.Popen(['sudo', 'chown', '-R',
+                        '%s:%s' % (os.getuid(), os.getgid()),
+                        self._static_dir]).wait()
+      # Then try to create the build dir again.
+      common_util.MkDirP(self._build_dir)
 
     # We are doing some work on this build -- let's touch it to indicate that
     # we shouldn't be cleaning it up anytime soon.