blob: 09e02dbb88a843b6289312a64e2d762a1684b0bc [file] [log] [blame]
Alex Klein2966e302019-01-17 13:29:38 -07001# Copyright 2018 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"""Image API Service.
6
7The image related API endpoints should generally be found here.
8"""
9
Alex Klein2966e302019-01-17 13:29:38 -070010import os
11
Alex Klein8cb365a2019-05-15 16:24:53 -060012from chromite.api import controller
Alex Klein076841b2019-08-29 15:19:39 -060013from chromite.api import faux
Alex Klein2b236722019-06-19 15:44:26 -060014from chromite.api import validate
Alex Kleine9a7dbf2020-10-06 18:12:12 -060015from chromite.api.controller import controller_util
David Burgerb171d652019-05-13 16:07:00 -060016from chromite.api.gen.chromiumos import common_pb2
Will Bradley9bc85452019-10-10 10:48:21 -060017from chromite.api.metrics import deserialize_metrics_log
Alex Klein4f0eb432019-05-02 13:56:04 -060018from chromite.lib import cros_build_lib
Alex Klein56355682019-02-07 10:36:54 -070019from chromite.lib import constants
20from chromite.lib import image_lib
Jack Neus761e1842020-12-01 18:20:11 +000021from chromite.lib import cros_logging as logging
22from chromite.scripts import pushimage
Alex Kleinb7cdbe62019-02-22 11:41:32 -070023from chromite.service import image
Will Bradley9bc85452019-10-10 10:48:21 -060024from chromite.utils import metrics
Alex Klein2966e302019-01-17 13:29:38 -070025
Alex Klein56355682019-02-07 10:36:54 -070026# The image.proto ImageType enum ids.
George Engelbrechtc55d6312021-05-05 12:11:13 -060027_BASE_ID = common_pb2.IMAGE_TYPE_BASE
28_DEV_ID = common_pb2.IMAGE_TYPE_DEV
29_TEST_ID = common_pb2.IMAGE_TYPE_TEST
30_BASE_VM_ID = common_pb2.IMAGE_TYPE_BASE_VM
31_TEST_VM_ID = common_pb2.IMAGE_TYPE_TEST_VM
32_RECOVERY_ID = common_pb2.IMAGE_TYPE_RECOVERY
33_FACTORY_ID = common_pb2.IMAGE_TYPE_FACTORY
34_FIRMWARE_ID = common_pb2.IMAGE_TYPE_FIRMWARE
35_BASE_GUEST_VM_ID = common_pb2.IMAGE_TYPE_BASE_GUEST_VM
36_TEST_GUEST_VM_ID = common_pb2.IMAGE_TYPE_TEST_GUEST_VM
Alex Klein56355682019-02-07 10:36:54 -070037
38# Dict to allow easily translating names to enum ids and vice versa.
39_IMAGE_MAPPING = {
40 _BASE_ID: constants.IMAGE_TYPE_BASE,
41 constants.IMAGE_TYPE_BASE: _BASE_ID,
42 _DEV_ID: constants.IMAGE_TYPE_DEV,
43 constants.IMAGE_TYPE_DEV: _DEV_ID,
44 _TEST_ID: constants.IMAGE_TYPE_TEST,
45 constants.IMAGE_TYPE_TEST: _TEST_ID,
Michael Mortenseneefe8952019-08-12 15:37:15 -060046 _RECOVERY_ID: constants.IMAGE_TYPE_RECOVERY,
47 constants.IMAGE_TYPE_RECOVERY: _RECOVERY_ID,
48 _FACTORY_ID: constants.IMAGE_TYPE_FACTORY,
49 constants.IMAGE_TYPE_FACTORY: _FACTORY_ID,
50 _FIRMWARE_ID: constants.IMAGE_TYPE_FIRMWARE,
51 constants.IMAGE_TYPE_FIRMWARE: _FIRMWARE_ID,
Alex Klein56355682019-02-07 10:36:54 -070052}
53
George Engelbrecht9f4f8322021-03-08 12:04:17 -070054# Dict to describe the prerequisite built images for each VM image type.
Alex Klein21b95022019-05-09 14:14:46 -060055_VM_IMAGE_MAPPING = {
56 _BASE_VM_ID: _IMAGE_MAPPING[_BASE_ID],
57 _TEST_VM_ID: _IMAGE_MAPPING[_TEST_ID],
Trent Begin008cade2019-10-31 13:40:59 -060058 _BASE_GUEST_VM_ID: _IMAGE_MAPPING[_BASE_ID],
59 _TEST_GUEST_VM_ID: _IMAGE_MAPPING[_TEST_ID],
Alex Klein21b95022019-05-09 14:14:46 -060060}
61
George Engelbrecht9f4f8322021-03-08 12:04:17 -070062# Dict to describe the prerequisite built images for each mod image type.
63_MOD_IMAGE_MAPPING = {
64 _RECOVERY_ID: _IMAGE_MAPPING[_BASE_ID],
65}
66
Jack Neus761e1842020-12-01 18:20:11 +000067# Supported image types for PushImage.
68SUPPORTED_IMAGE_TYPES = {
69 common_pb2.IMAGE_TYPE_RECOVERY: constants.IMAGE_TYPE_RECOVERY,
70 common_pb2.IMAGE_TYPE_FACTORY: constants.IMAGE_TYPE_FACTORY,
71 common_pb2.IMAGE_TYPE_FIRMWARE: constants.IMAGE_TYPE_FIRMWARE,
72 common_pb2.IMAGE_TYPE_ACCESSORY_USBPD: constants.IMAGE_TYPE_ACCESSORY_USBPD,
73 common_pb2.IMAGE_TYPE_ACCESSORY_RWSIG: constants.IMAGE_TYPE_ACCESSORY_RWSIG,
74 common_pb2.IMAGE_TYPE_BASE: constants.IMAGE_TYPE_BASE,
George Engelbrecht9f4f8322021-03-08 12:04:17 -070075 common_pb2.IMAGE_TYPE_GSC_FIRMWARE: constants.IMAGE_TYPE_GSC_FIRMWARE,
Jack Neus761e1842020-12-01 18:20:11 +000076}
77
Alex Klein56355682019-02-07 10:36:54 -070078
George Engelbrecht9f4f8322021-03-08 12:04:17 -070079def _add_image_to_proto(output_proto, path, image_type, board):
80 """Quick helper function to add a new image to the output proto."""
81 new_image = output_proto.images.add()
82 new_image.path = path
83 new_image.type = image_type
84 new_image.build_target.name = board
85
86
Michael Mortensen10146cf2019-11-19 19:59:22 -070087def _CreateResponse(_input_proto, output_proto, _config):
88 """Set output_proto success field on a successful Create response."""
89 output_proto.success = True
90
91
92@faux.success(_CreateResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -070093@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -060094@validate.require('build_target.name')
Alex Klein231d2da2019-07-22 16:44:45 -060095@validate.validation_complete
Will Bradley9bc85452019-10-10 10:48:21 -060096@metrics.collect_metrics
Alex Klein231d2da2019-07-22 16:44:45 -060097def Create(input_proto, output_proto, _config):
George Engelbrecht9f4f8322021-03-08 12:04:17 -070098 """Build images.
Alex Klein56355682019-02-07 10:36:54 -070099
100 Args:
101 input_proto (image_pb2.CreateImageRequest): The input message.
102 output_proto (image_pb2.CreateImageResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600103 _config (api_config.ApiConfig): The API call config.
Alex Klein56355682019-02-07 10:36:54 -0700104 """
105 board = input_proto.build_target.name
Alex Klein56355682019-02-07 10:36:54 -0700106
Alex Klein56355682019-02-07 10:36:54 -0700107 # Build the base image if no images provided.
108 to_build = input_proto.image_types or [_BASE_ID]
Alex Klein56355682019-02-07 10:36:54 -0700109
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700110 image_types, vm_types, mod_image_types = _ParseImagesToCreate(to_build)
Alex Klein21b95022019-05-09 14:14:46 -0600111 build_config = _ParseCreateBuildConfig(input_proto)
Alex Klein56355682019-02-07 10:36:54 -0700112
113 # Sorted isn't really necessary here, but it's much easier to test.
Jack Neus761e1842020-12-01 18:20:11 +0000114 result = image.Build(
115 board=board, images=sorted(list(image_types)), config=build_config)
Alex Klein56355682019-02-07 10:36:54 -0700116
Alex Klein1bcd9882019-03-19 13:25:24 -0600117 output_proto.success = result.success
Will Bradley29a49c22019-10-21 11:50:08 -0600118
Alex Klein1bcd9882019-03-19 13:25:24 -0600119 if result.success:
120 # Success -- we need to list out the images we built in the output.
121 _PopulateBuiltImages(board, image_types, output_proto)
Will Bradley29a49c22019-10-21 11:50:08 -0600122
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700123 for vm_type in vm_types:
124 is_test = vm_type in [_TEST_VM_ID, _TEST_GUEST_VM_ID]
125 try:
126 if vm_type in [_BASE_GUEST_VM_ID, _TEST_GUEST_VM_ID]:
127 vm_path = image.CreateGuestVm(board, is_test=is_test)
128 else:
129 vm_path = image.CreateVm(
130 board, disk_layout=build_config.disk_layout, is_test=is_test)
131 except image.ImageToVmError as e:
132 cros_build_lib.Die(e)
Will Bradley29a49c22019-10-21 11:50:08 -0600133
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700134 _add_image_to_proto(output_proto, vm_path, vm_type, board)
135
136 for mod_type in mod_image_types:
137 if mod_type == _RECOVERY_ID:
138 base_image_path = _GetBaseImagePath(output_proto)
139 result = image.BuildRecoveryImage(board=board,
140 image_path=base_image_path)
141 if result.success:
142 _PopulateBuiltImages(board, [_IMAGE_MAPPING[mod_type]], output_proto)
143 else:
144 cros_build_lib.Die('Failed to create recovery image.')
145 else:
146 cros_build_lib.Die('_RECOVERY_ID is the only mod_image_type.')
Will Bradley29a49c22019-10-21 11:50:08 -0600147
148 # Read metric events log and pipe them into output_proto.events.
149 deserialize_metrics_log(output_proto.events, prefix=board)
150 return controller.RETURN_CODE_SUCCESS
151
Alex Klein1bcd9882019-03-19 13:25:24 -0600152 else:
Alex Klein2557b4f2019-07-11 14:34:00 -0600153 # Failure, include all of the failed packages in the output when available.
154 if not result.failed_packages:
155 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
156
Alex Klein1bcd9882019-03-19 13:25:24 -0600157 for package in result.failed_packages:
158 current = output_proto.failed_packages.add()
Alex Kleine9a7dbf2020-10-06 18:12:12 -0600159 controller_util.serialize_package_info(package, current)
Alex Klein1bcd9882019-03-19 13:25:24 -0600160
Alex Klein8cb365a2019-05-15 16:24:53 -0600161 return controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE
Alex Klein1bcd9882019-03-19 13:25:24 -0600162
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700163def _GetBaseImagePath(output_proto):
164 """From image_pb2.CreateImageResult, return base image path or None."""
165 ret = None
166 for i in output_proto.images:
167 if i.type == _BASE_ID:
168 ret = i.path
169 return ret
170
Alex Klein21b95022019-05-09 14:14:46 -0600171
172def _ParseImagesToCreate(to_build):
173 """Helper function to parse the image types to build.
174
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700175 This function expresses the dependencies of each image type and adds
176 the requisite image types if they're not explicitly defined.
Alex Klein21b95022019-05-09 14:14:46 -0600177
178 Args:
179 to_build (list[int]): The image type list.
180
181 Returns:
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700182 (set, set, set): The image, vm, and mod_image types that need to be built.
Alex Klein21b95022019-05-09 14:14:46 -0600183 """
184 image_types = set()
185 vm_types = set()
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700186 mod_image_types = set()
Alex Klein21b95022019-05-09 14:14:46 -0600187 for current in to_build:
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700188 # Find out if it's a special case (vm, img mod), or just any old image.
189 if current in _VM_IMAGE_MAPPING:
Alex Klein21b95022019-05-09 14:14:46 -0600190 vm_types.add(current)
191 # Make sure we build the image required to build the VM.
192 image_types.add(_VM_IMAGE_MAPPING[current])
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700193 elif current in _MOD_IMAGE_MAPPING:
194 mod_image_types.add(current)
195 image_types.add(_MOD_IMAGE_MAPPING[current])
196 elif current in _IMAGE_MAPPING:
197 image_types.add(_IMAGE_MAPPING[current])
Alex Klein21b95022019-05-09 14:14:46 -0600198 else:
199 # Not expected, but at least it will be obvious if this comes up.
200 cros_build_lib.Die(
201 "The service's known image types do not match those in image.proto. "
202 'Unknown Enum ID: %s' % current)
203
Trent Begin008cade2019-10-31 13:40:59 -0600204 # We can only build one type of these images at a time since image_to_vm.sh
205 # uses the default path if a name is not provided.
206 if vm_types.issuperset({_BASE_VM_ID, _TEST_VM_ID}):
Alex Klein21b95022019-05-09 14:14:46 -0600207 cros_build_lib.Die('Cannot create more than one VM.')
208
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700209 return image_types, vm_types, mod_image_types
Alex Klein21b95022019-05-09 14:14:46 -0600210
211
212def _ParseCreateBuildConfig(input_proto):
213 """Helper to parse the image build config for Create."""
214 enable_rootfs_verification = not input_proto.disable_rootfs_verification
215 version = input_proto.version or None
216 disk_layout = input_proto.disk_layout or None
217 builder_path = input_proto.builder_path or None
218 return image.BuildConfig(
Jack Neus761e1842020-12-01 18:20:11 +0000219 enable_rootfs_verification=enable_rootfs_verification,
220 replace=True,
221 version=version,
222 disk_layout=disk_layout,
223 builder_path=builder_path,
Alex Klein21b95022019-05-09 14:14:46 -0600224 )
225
Alex Klein1bcd9882019-03-19 13:25:24 -0600226
227def _PopulateBuiltImages(board, image_types, output_proto):
228 """Helper to list out built images for Create."""
Alex Klein56355682019-02-07 10:36:54 -0700229 # Build out the ImageType->ImagePath mapping in the output.
230 # We're using the default path, so just fetch that, but read the symlink so
231 # the path we're returning is somewhat more permanent.
232 latest_link = image_lib.GetLatestImageLink(board)
Alex Klein4f0eb432019-05-02 13:56:04 -0600233 base_path = os.path.realpath(latest_link)
Alex Klein56355682019-02-07 10:36:54 -0700234
235 for current in image_types:
236 type_id = _IMAGE_MAPPING[current]
237 path = os.path.join(base_path, constants.IMAGE_TYPE_TO_NAME[current])
George Engelbrecht9f4f8322021-03-08 12:04:17 -0700238 _add_image_to_proto(output_proto, path, type_id, board)
Alex Klein4f0eb432019-05-02 13:56:04 -0600239
240
Michael Mortensen10146cf2019-11-19 19:59:22 -0700241def _SignerTestResponse(_input_proto, output_proto, _config):
242 """Set output_proto success field on a successful SignerTest response."""
243 output_proto.success = True
244 return controller.RETURN_CODE_SUCCESS
245
246
247@faux.success(_SignerTestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700248@faux.empty_completed_unsuccessfully_error
Michael Mortensenc83c9952019-08-05 12:15:12 -0600249@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600250@validate.validation_complete
251def SignerTest(input_proto, output_proto, _config):
Michael Mortensenc83c9952019-08-05 12:15:12 -0600252 """Run image tests.
253
254 Args:
255 input_proto (image_pb2.ImageTestRequest): The input message.
256 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600257 _config (api_config.ApiConfig): The API call config.
Michael Mortensenc83c9952019-08-05 12:15:12 -0600258 """
Michael Mortensenc83c9952019-08-05 12:15:12 -0600259 image_path = input_proto.image.path
260
Alex Klein231d2da2019-07-22 16:44:45 -0600261 result = image_lib.SecurityTest(image=image_path)
Michael Mortensenc83c9952019-08-05 12:15:12 -0600262 output_proto.success = result
263 if result:
264 return controller.RETURN_CODE_SUCCESS
265 else:
266 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
267
Alex Klein076841b2019-08-29 15:19:39 -0600268
Michael Mortensen10146cf2019-11-19 19:59:22 -0700269def _TestResponse(_input_proto, output_proto, _config):
270 """Set output_proto success field on a successful Test response."""
271 output_proto.success = True
272 return controller.RETURN_CODE_SUCCESS
273
274
275@faux.success(_TestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700276@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -0600277@validate.require('build_target.name', 'result.directory')
278@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600279def Test(input_proto, output_proto, config):
Alex Klein2966e302019-01-17 13:29:38 -0700280 """Run image tests.
281
282 Args:
283 input_proto (image_pb2.ImageTestRequest): The input message.
284 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600285 config (api_config.ApiConfig): The API call config.
Alex Klein2966e302019-01-17 13:29:38 -0700286 """
287 image_path = input_proto.image.path
288 board = input_proto.build_target.name
289 result_directory = input_proto.result.directory
290
Alex Klein2966e302019-01-17 13:29:38 -0700291 if not os.path.isfile(image_path) or not image_path.endswith('.bin'):
Alex Klein4f0eb432019-05-02 13:56:04 -0600292 cros_build_lib.Die(
Alex Klein2966e302019-01-17 13:29:38 -0700293 'The image.path must be an existing image file with a .bin extension.')
294
Alex Klein231d2da2019-07-22 16:44:45 -0600295 if config.validate_only:
296 return controller.RETURN_CODE_VALID_INPUT
297
Alex Klein8cb365a2019-05-15 16:24:53 -0600298 success = image.Test(board, result_directory, image_dir=image_path)
299 output_proto.success = success
300
301 if success:
302 return controller.RETURN_CODE_SUCCESS
303 else:
304 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
Jack Neus761e1842020-12-01 18:20:11 +0000305
306
307@faux.empty_success
308@faux.empty_completed_unsuccessfully_error
309@validate.require('gs_image_dir', 'sysroot.build_target.name')
310def PushImage(input_proto, _output_proto, config):
311 """Push artifacts from the archive bucket to the release bucket.
312
313 Wraps chromite/scripts/pushimage.py.
314
315 Args:
316 input_proto (PushImageRequest): Input proto.
317 _output_proto (PushImageResponse): Output proto.
318 config (api.config.ApiConfig): The API call config.
319
320 Returns:
321 A controller return code (e.g. controller.RETURN_CODE_SUCCESS).
322 """
323 sign_types = []
324 if input_proto.sign_types:
325 for sign_type in input_proto.sign_types:
326 if sign_type not in SUPPORTED_IMAGE_TYPES:
327 logging.error('unsupported sign type %g', sign_type)
328 return controller.RETURN_CODE_INVALID_INPUT
329 sign_types.append(SUPPORTED_IMAGE_TYPES[sign_type])
330
331 # If configured for validation only we're done here.
332 if config.validate_only:
333 return controller.RETURN_CODE_VALID_INPUT
334
Jack Neus485a9d22020-12-21 03:15:15 +0000335 kwargs = {}
336 if input_proto.profile.name:
337 kwargs['profile'] = input_proto.profile.name
338 if input_proto.dest_bucket:
339 kwargs['dest_bucket'] = input_proto.dest_bucket
Jack Neus761e1842020-12-01 18:20:11 +0000340 try:
341 pushimage.PushImage(
342 input_proto.gs_image_dir,
343 input_proto.sysroot.build_target.name,
344 dry_run=input_proto.dryrun,
Jack Neus485a9d22020-12-21 03:15:15 +0000345 sign_types=sign_types,
346 **kwargs)
Jack Neus761e1842020-12-01 18:20:11 +0000347 return controller.RETURN_CODE_SUCCESS
348 except Exception:
Jack Neuse3150a42021-01-29 17:16:36 +0000349 logging.error('PushImage failed: ', exc_info=True)
Jack Neus761e1842020-12-01 18:20:11 +0000350 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY