blob: 3ee0f290c47fb23d31ba529e846bd3333a5cc45b [file] [log] [blame]
Dan Shi72b16132015-10-08 12:10:33 -07001# Copyright 2015 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Helper methods to make Google API call to query Android build server."""
6
7from __future__ import print_function
8
9import apiclient
10import httplib2
11import io
Dan Shi7b9b6a92015-11-12 01:00:29 -080012import subprocess
Dan Shi72b16132015-10-08 12:10:33 -070013
14from apiclient import discovery
15from oauth2client.client import SignedJwtAssertionCredentials
16
Dan Shi7b9b6a92015-11-12 01:00:29 -080017import retry
18
19
Dan Shi72b16132015-10-08 12:10:33 -070020CREDENTIAL_SCOPE = 'https://www.googleapis.com/auth/androidbuild.internal'
21DEFAULT_BUILDER = 'androidbuildinternal'
22DEFAULT_CHUNKSIZE = 20*1024*1024
Dan Shi7b9b6a92015-11-12 01:00:29 -080023# Maximum attempts to interact with Launch Control API.
24MAX_ATTEMPTS = 10
25# Timeout in minutes for downloading attempt.
26DOWNLOAD_TIMEOUT_MINS = 30
27# Timeout in minutes for API query.
28QUERY_TIMEOUT_MINS = 1
29
Dan Shi72b16132015-10-08 12:10:33 -070030
31class AndroidBuildFetchError(Exception):
32 """Exception to raise when failed to make calls to Android build server."""
33
34class BuildAccessor(object):
35 """Wrapper class to make Google API call to query Android build server."""
36
37 # Credential information is required to access Android builds. The values will
38 # be set when the devserver starts.
39 credential_info = None
40
41 @classmethod
Dan Shi7b9b6a92015-11-12 01:00:29 -080042 @retry.retry(Exception, timeout_min=QUERY_TIMEOUT_MINS)
Dan Shi72b16132015-10-08 12:10:33 -070043 def _GetServiceObject(cls):
44 """Returns a service object with given credential information."""
45 if not cls.credential_info:
46 raise AndroidBuildFetchError('Android Build credential is missing.')
47
48 credentials = SignedJwtAssertionCredentials(
49 cls.credential_info['client_email'],
50 cls.credential_info['private_key'], CREDENTIAL_SCOPE)
51 http_auth = credentials.authorize(httplib2.Http())
Dan Shi7b9b6a92015-11-12 01:00:29 -080052 return discovery.build(DEFAULT_BUILDER, 'v1', http=http_auth)
53
Dan Shicfd9aac2016-05-18 09:52:28 -070054 @staticmethod
55 def _GetBuildType(build_id):
56 """Get the build type based on the given build id.
57
58 Args:
59 build_id: Build id of the Android build, e.g., 2155602.
60
61 Returns:
62 The build type, e.g., submitted, pending.
63 """
64 if build_id and build_id.lower().startswith('p'):
65 return 'pending'
66 return 'submitted'
Dan Shi72b16132015-10-08 12:10:33 -070067
68 @classmethod
69 def _VerifyBranch(cls, service_obj, branch, build_id, target):
70 """Verify the build with given id and target is for the specified branch.
71
72 Args:
73 service_obj: A service object to be used to make API call to build server.
74 branch: branch of the desired build.
75 build_id: Build id of the Android build, e.g., 2155602.
76 target: Target of the Android build, e.g., shamu-userdebug.
77
78 Raises:
79 AndroidBuildFetchError: If the given build id and target are not for the
80 specified branch.
81 """
Dan Shicfd9aac2016-05-18 09:52:28 -070082 build_type = cls._GetBuildType(build_id)
Dan Shi72b16132015-10-08 12:10:33 -070083 builds = service_obj.build().list(
Dan Shicfd9aac2016-05-18 09:52:28 -070084 buildType=build_type, branch=branch, buildId=build_id, target=target,
Dan Shi7b9b6a92015-11-12 01:00:29 -080085 maxResults=0).execute(num_retries=MAX_ATTEMPTS)
Dan Shi72b16132015-10-08 12:10:33 -070086 if not builds:
87 raise AndroidBuildFetchError(
88 'Failed to locate build with branch %s, build id %s and target %s.' %
89 (branch, build_id, target))
90
91 @classmethod
92 def GetArtifacts(cls, branch, build_id, target):
93 """Get the list of artifacts for given build id and target.
94
95 The return value is a list of dictionaries, each containing information
96 about an artifact.
97 For example:
98 {u'contentType': u'application/octet-stream',
99 u'crc32': 4131231264,
100 u'lastModifiedTime': u'143518405786',
101 u'md5': u'c04c823a64293aa5bf508e2eb4683ec8',
102 u'name': u'fastboot',
103 u'revision': u'HsXLpGsgEaqj654THKvR/A==',
104 u'size': u'6999296'},
105
106 Args:
107 branch: branch of the desired build.
108 build_id: Build id of the Android build, e.g., 2155602.
109 target: Target of the Android build, e.g., shamu-userdebug.
110
111 Returns:
112 A list of artifacts for given build id and target.
113 """
114 service_obj = cls._GetServiceObject()
115 cls._VerifyBranch(service_obj, branch, build_id, target)
Dan Shicfd9aac2016-05-18 09:52:28 -0700116 build_type = cls._GetBuildType(build_id)
Dan Shi72b16132015-10-08 12:10:33 -0700117
118 # Get all artifacts for the given build_id and target.
Dan Shib066b062017-05-26 14:31:13 -0700119 # maxResults is set to 1000 so API returns enough results to include all
120 # artifacts.
Dan Shi72b16132015-10-08 12:10:33 -0700121 artifacts = service_obj.buildartifact().list(
Dan Shicfd9aac2016-05-18 09:52:28 -0700122 buildType=build_type, buildId=build_id, target=target,
Dan Shib066b062017-05-26 14:31:13 -0700123 attemptId='latest', maxResults=1000).execute(num_retries=MAX_ATTEMPTS)
Dan Shi72b16132015-10-08 12:10:33 -0700124 return artifacts['artifacts']
125
126 @classmethod
Dan Shi7b9b6a92015-11-12 01:00:29 -0800127 @retry.retry(Exception, timeout_min=DOWNLOAD_TIMEOUT_MINS)
Dan Shi72b16132015-10-08 12:10:33 -0700128 def Download(cls, branch, build_id, target, resource_id, dest_file):
Dan Shi7b9b6a92015-11-12 01:00:29 -0800129 """Download the list of artifacts for given build id and target.
Dan Shi72b16132015-10-08 12:10:33 -0700130
131 Args:
132 branch: branch of the desired build.
133 build_id: Build id of the Android build, e.g., 2155602.
134 target: Target of the Android build, e.g., shamu-userdebug.
135 resource_id: Name of the artifact to donwload.
136 dest_file: Path to the file to download to.
137 """
138 service_obj = cls._GetServiceObject()
139 cls._VerifyBranch(service_obj, branch, build_id, target)
140
Dan Shi7b9b6a92015-11-12 01:00:29 -0800141 # Delete partially downloaded file if exists.
142 subprocess.call(['rm', '-rf', dest_file])
143
Dan Shicfd9aac2016-05-18 09:52:28 -0700144 build_type = cls._GetBuildType(build_id)
Dan Shi72b16132015-10-08 12:10:33 -0700145 # TODO(dshi): Add retry logic here to avoid API flakes.
146 download_req = service_obj.buildartifact().get_media(
Dan Shicfd9aac2016-05-18 09:52:28 -0700147 buildType=build_type, buildId=build_id, target=target,
Dan Shi72b16132015-10-08 12:10:33 -0700148 attemptId='latest', resourceId=resource_id)
149 with io.FileIO(dest_file, mode='wb') as fh:
150 downloader = apiclient.http.MediaIoBaseDownload(
151 fh, download_req, chunksize=DEFAULT_CHUNKSIZE)
152 done = None
153 while not done:
Dan Shi7b9b6a92015-11-12 01:00:29 -0800154 _, done = downloader.next_chunk(num_retries=MAX_ATTEMPTS)
155
Dan Shi61305df2015-10-26 16:52:35 -0700156
157 @classmethod
Dan Shi7b9b6a92015-11-12 01:00:29 -0800158 @retry.retry(Exception, timeout_min=QUERY_TIMEOUT_MINS,
159 blacklist=[AndroidBuildFetchError])
Dan Shi61305df2015-10-26 16:52:35 -0700160 def GetLatestBuildID(cls, target, branch):
161 """Get the latest build ID for the given target and branch.
162
163 Args:
164 branch: branch of the desired build.
165 target: Target of the Android build, e.g., shamu-userdebug.
166
167 Returns:
168 Build id of the latest successful Android build for the given target and
169 branch, e.g., 2155602.
170 """
171 service_obj = cls._GetServiceObject()
172 builds = service_obj.build().list(
173 buildType='submitted', branch=branch, target=target, successful=True,
Dan Shi7b9b6a92015-11-12 01:00:29 -0800174 maxResults=1).execute(num_retries=MAX_ATTEMPTS)
Dan Shi61305df2015-10-26 16:52:35 -0700175 if not builds or not builds['builds']:
176 raise AndroidBuildFetchError(
177 'Failed to locate build with branch %s and target %s.' %
178 (branch, target))
179 return builds['builds'][0]['buildId']