cbuildbot_launch: Only clean git locks conditionally.

We currently spend nearly 5 minutes every single build cleaning git
locks, which are normally only leaked if a builder was
aborted. So... skip cleaning them, if the previous build finished
normally.

BUG=None
TEST=cbuildbot_launch_unittest

Change-Id: Ieaee7676b50566d72b89fc1f6218c8cb90624281
Reviewed-on: https://chromium-review.googlesource.com/1381056
Commit-Ready: ChromeOS CL Exonerator Bot <chromiumos-cl-exonerator@appspot.gserviceaccount.com>
Tested-by: Don Garrett <dgarrett@chromium.org>
Reviewed-by: Jason Clinton <jclinton@chromium.org>
diff --git a/scripts/cbuildbot_launch.py b/scripts/cbuildbot_launch.py
index 5e9344c..fea12ee 100644
--- a/scripts/cbuildbot_launch.py
+++ b/scripts/cbuildbot_launch.py
@@ -245,6 +245,7 @@
         be updated if the distfiles cache is cleaned.
   """
   previous_state = GetLastBuildState(root)
+  SetLastBuildState(root, build_state)
   build_state.distfiles_ts = _MaybeCleanDistfiles(
       repo, previous_state.distfiles_ts)
 
@@ -278,7 +279,13 @@
     # The previous run might have been killed in the middle leaving stale git
     # locks. Clean those up, first.
     repo.PreLoad()
-    repo.CleanStaleLocks()
+
+    # If the previous build didn't exit normally, run an expensive step to
+    # cleanup abandoned git locks.
+    if previous_state.status not in (constants.BUILDER_STATUS_FAILED,
+                                     constants.BUILDER_STATUS_PASSED):
+      repo.CleanStaleLocks()
+
     repo.BuildRootGitCleanup(prune_all=True)
   except Exception:
     logging.info('Checkout cleanup failed, wiping buildroot:', exc_info=True)