[autotest] Handle race condition on label creation.

If two suite runs in parallel we may run into a race condition when
trying to create the cros-version label. This CL handles the race
condition.

BUG=chromium:542928
TEST=Test locally with an autotest instance. Force the code to exeucte.

Change-Id: If59cd00e66525203e1d954fbdea99476c060e05c
Reviewed-on: https://chromium-review.googlesource.com/307590
Commit-Ready: Fang Deng <fdeng@chromium.org>
Tested-by: Fang Deng <fdeng@chromium.org>
Reviewed-by: Paul Hobbs <phobbs@google.com>
diff --git a/frontend/afe/rpc_utils.py b/frontend/afe/rpc_utils.py
index 23ca47b..8623daf 100644
--- a/frontend/afe/rpc_utils.py
+++ b/frontend/afe/rpc_utils.py
@@ -11,6 +11,7 @@
 import inspect
 import os
 import sys
+import django.db.utils
 import django.http
 
 from autotest_lib.frontend import thread_local
@@ -25,6 +26,7 @@
 
 NULL_DATETIME = datetime.datetime.max
 NULL_DATE = datetime.date.max
+DUPLICATE_KEY_MSG = 'Duplicate entry'
 
 def prepare_for_serialization(objects):
     """
@@ -647,9 +649,17 @@
     try:
         models.Label.objects.get(name=name)
     except models.Label.DoesNotExist:
-        new_label = models.Label.objects.create(name=name)
-        new_label.save()
-        return True
+        try:
+            new_label = models.Label.objects.create(name=name)
+            new_label.save()
+            return True
+        except django.db.utils.IntegrityError as e:
+            # It is possible that another suite/test already
+            # created the label between the check and save.
+            if DUPLICATE_KEY_MSG in str(e):
+                return False
+            else:
+                raise
     return False