buildbot_test_toolchains: get latest instead green vanilla build

So as to work around the problem that some builders' latest green
builds are too old.

BUG=chromium:714890
TEST=Tested _GetVanillaImageName locally.

Change-Id: I06571f3d55743fb56977d7ef56a51fcddfdda62e
Reviewed-on: https://chromium-review.googlesource.com/486086
Reviewed-by: Manoj Gupta <manojgupta@chromium.org>
Commit-Queue: Ting-Yuan Huang <laszio@chromium.org>
Tested-by: Ting-Yuan Huang <laszio@chromium.org>
Trybot-Ready: Ting-Yuan Huang <laszio@chromium.org>
diff --git a/buildbot_test_toolchains.py b/buildbot_test_toolchains.py
index 58c2668..c03c009 100755
--- a/buildbot_test_toolchains.py
+++ b/buildbot_test_toolchains.py
@@ -99,9 +99,7 @@
     mo = re.search(TRYBOT_IMAGE_RE, trybot_image)
     assert mo
     dirname = IMAGE_DIR.replace('\\', '').format(**mo.groupdict())
-    version = buildbot_utils.GetGSContent(self._chromeos_root,
-                                          dirname + '/LATEST-master')
-    return dirname + '/' + version
+    return buildbot_utils.GetLatestImage(self._chromeos_root, dirname)
 
   def _GetNonAFDOImageName(self, trybot_image):
     """Given a trybot artifact name, get corresponding non-AFDO image name.
diff --git a/cros_utils/buildbot_utils.py b/cros_utils/buildbot_utils.py
index d24ba0d..f89bb71 100644
--- a/cros_utils/buildbot_utils.py
+++ b/cros_utils/buildbot_utils.py
@@ -8,6 +8,7 @@
 import base64
 import json
 import os
+import re
 import time
 import urllib2
 
@@ -388,3 +389,22 @@
   logger.GetLogger().LogOutput('Image %s not found, waited for %d hours' %
                                (build, (TIME_OUT / 3600)))
   raise BuildbotTimeout('Timeout while waiting for image %s' % build)
+
+
+def GetLatestImage(chromeos_root, path):
+  """Get latest image"""
+
+  fmt = re.compile(r'R([0-9]+)-([0-9]+).([0-9]+).([0-9]+)')
+
+  ce = command_executer.GetCommandExecuter()
+  command = ('gsutil ls gs://chromeos-image-archive/%s' % path)
+  _, out, _ = ce.ChrootRunCommandWOutput(
+      chromeos_root, command, print_to_console=False)
+  candidates = [l.split('/')[-2] for l in out.split()]
+  candidates = map(fmt.match, candidates)
+  candidates = [[int(r) for r in m.group(1, 2, 3, 4)] for m in candidates if m]
+  candidates.sort(reverse=True)
+  for c in candidates:
+      build = '%s/R%d-%d.%d.%d' % (path, c[0], c[1], c[2], c[3])
+      if DoesImageExist(chromeos_root, build):
+          return build