common_util: call chown on existing directory in MkDirP

In the MkDirP function, if the directory already exists, call
chown with current user and group to fix the ownerships of the
directory and its subfiles.

BUG=chromium:438814
TEST=Manually tested

Change-Id: Ifc41431e11c1d8ffe871df3138b2e41f70dbb469
Reviewed-on: https://chromium-review.googlesource.com/232522
Reviewed-by: Yu-Ju Hong <yjhong@chromium.org>
Tested-by: Yiming Chen <yimingc@chromium.org>
Commit-Queue: Yiming Chen <yimingc@chromium.org>
diff --git a/common_util.py b/common_util.py
index eae7411..0cf7937 100644
--- a/common_util.py
+++ b/common_util.py
@@ -47,11 +47,23 @@
 
 
 def MkDirP(directory):
-  """Thread-safely create a directory like mkdir -p."""
+  """Thread-safely create a directory like mkdir -p.
+
+  If the directory already exists, call chown on the directory and its subfiles
+  recursively with current user and group to make sure current process has full
+  access to the directory.
+  """
   try:
     os.makedirs(directory)
   except OSError, e:
-    if not (e.errno == errno.EEXIST and os.path.isdir(directory)):
+    if e.errno == errno.EEXIST and os.path.isdir(directory):
+      # Fix permissions and ownership of the directory and its subfiles by
+      # calling chown recursively with current user and group.
+      chown_command = [
+          'sudo', 'chown', '-R', '%s:%s' % (os.getuid(), os.getgid()), directory
+      ]
+      subprocess.Popen(chown_command).wait()
+    else:
       raise