[autotest] Fix concurrent download issue in lxc.

If two threads download a file at the same time, one can end up with the
file of the other (which may or may not end up with the correct download
via retry).

BUG=b:38183322
TEST=None.

Change-Id: Ia524af44415e5042ab5c23e8232eed3cb8fd6844
Reviewed-on: https://chromium-review.googlesource.com/501170
Commit-Ready: Ilja H. Friedel <ihf@chromium.org>
Tested-by: Ilja H. Friedel <ihf@chromium.org>
Reviewed-by: Stéphane Marchesin <marcheu@chromium.org>
diff --git a/site_utils/lxc.py b/site_utils/lxc.py
index 8e1d022..134e86e 100644
--- a/site_utils/lxc.py
+++ b/site_utils/lxc.py
@@ -25,6 +25,7 @@
 import re
 import socket
 import sys
+import tempfile
 import time
 
 import common
@@ -286,10 +287,12 @@
     # TODO(xixuan): Better to only ssh to devservers in lab, and continue using
     # wget for ganeti devservers.
     if remote_url in dev_server.ImageServerBase.servers():
-        tmp_file = '/tmp/%s' % os.path.basename(target)
-        dev_server.ImageServerBase.download_file(
-                url, tmp_file, timeout=DEVSERVER_CALL_TIMEOUT)
-        utils.run('sudo mv %s %s' % (tmp_file, target))
+        # This can be run in multiple threads, pick a unique tmp_file.name.
+        with tempfile.NamedTemporaryFile(prefix=os.path.basename(target) + '_',
+                                         delete=False) as tmp_file:
+            dev_server.ImageServerBase.download_file(
+                    url, tmp_file.name, timeout=DEVSERVER_CALL_TIMEOUT)
+            utils.run('sudo mv %s %s' % (tmp_file.name, target))
     else:
         utils.run('sudo wget --timeout=300 -nv %s -O %s' % (url, target),
                   stderr_tee=utils.TEE_TO_LOGS)