acloud: Handle build_id in AVDSpec if user doesn't specify build_id.

Bug: 112524854
Test: ./run_tests.sh, m acloud && acloud create
acloud create --branch master --build_target cf_x86_phone-userdebug

Change-Id: I5b783f2b92220096156580f6b9be157cf099fc91
diff --git a/internal/lib/android_build_client.py b/internal/lib/android_build_client.py
index 4f7ee57..735c0e4 100644
--- a/internal/lib/android_build_client.py
+++ b/internal/lib/android_build_client.py
@@ -18,10 +18,10 @@
 
 import io
 import logging
-import os
 
 import apiclient
 
+from acloud import errors as root_errors
 from acloud.internal.lib import base_cloud_client
 from acloud.public import errors
 
@@ -42,12 +42,17 @@
     DEFAULT_ATTEMPT_ID = "0"
     DEFAULT_CHUNK_SIZE = 20 * 1024 * 1024
     NO_ACCESS_ERROR_PATTERN = "does not have storage.objects.create access"
+    # LKGB variables.
+    BUILD_STATUS_COMPLETE = "complete"
+    BUILD_TYPE_SUBMITTED = "submitted"
+    ONE_RESULT = 1
+    BUILD_SUCCESSFUL = True
 
     # Message constant
     COPY_TO_MSG = ("build artifact (target: %s, build_id: %s, "
                    "artifact: %s, attempt_id: %s) to "
                    "google storage (bucket: %s, path: %s)")
-
+    # pylint: disable=invalid-name
     def DownloadArtifact(self,
                          build_target,
                          build_id,
@@ -140,3 +145,35 @@
         api = self.service.build().get(buildId=build_id, target=build_target)
         build = self.Execute(api)
         return build.get("branch", "")
+
+    def GetLKGB(self, build_target, build_branch):
+        """Get latest successful build id.
+
+        From branch and target, we can use api to query latest successful build id.
+        e.g. {u'nextPageToken':..., u'builds': [{u'completionTimestamp':u'1534157869286',
+        ... u'buildId': u'4949805', u'machineName'...}]}
+
+        Args:
+            build_target: String, target name, e.g. "aosp_cf_x86_phone-userdebug"
+            build_branch: String, git branch name, e.g. "aosp-master"
+
+        Returns:
+            A string, string of build id number.
+
+        Raises:
+            errors.CreateError: Can't get build id.
+        """
+        api = self.service.build().list(
+            branch=build_branch,
+            target=build_target,
+            buildAttemptStatus=self.BUILD_STATUS_COMPLETE,
+            buildType=self.BUILD_TYPE_SUBMITTED,
+            maxResults=self.ONE_RESULT,
+            successful=self.BUILD_SUCCESSFUL)
+        build = self.Execute(api)
+        if build:
+            return str(build.get("builds")[0].get("buildId"))
+        raise root_errors.GetBuildIDError(
+            "No available good builds for branch: %s target: %s"
+            % (build_branch, build_target)
+        )