blob: 7c3f8b3badbef0ddfe3340b05fa45bc18b1f7fb3 [file] [log] [blame]
Alex Klein2966e302019-01-17 13:29:38 -07001# -*- coding: utf-8 -*-
2# Copyright 2018 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Image API Service.
7
8The image related API endpoints should generally be found here.
9"""
10
11from __future__ import print_function
12
13import os
14
Alex Klein8cb365a2019-05-15 16:24:53 -060015from chromite.api import controller
Alex Klein076841b2019-08-29 15:19:39 -060016from chromite.api import faux
Alex Klein2b236722019-06-19 15:44:26 -060017from chromite.api import validate
Alex Kleine9a7dbf2020-10-06 18:12:12 -060018from chromite.api.controller import controller_util
David Burgerb171d652019-05-13 16:07:00 -060019from chromite.api.gen.chromiumos import common_pb2
Will Bradley9bc85452019-10-10 10:48:21 -060020from chromite.api.metrics import deserialize_metrics_log
Alex Klein4f0eb432019-05-02 13:56:04 -060021from chromite.lib import cros_build_lib
Alex Klein56355682019-02-07 10:36:54 -070022from chromite.lib import constants
23from chromite.lib import image_lib
Jack Neus761e1842020-12-01 18:20:11 +000024from chromite.lib import cros_logging as logging
25from chromite.scripts import pushimage
Alex Kleinb7cdbe62019-02-22 11:41:32 -070026from chromite.service import image
Will Bradley9bc85452019-10-10 10:48:21 -060027from chromite.utils import metrics
Alex Klein2966e302019-01-17 13:29:38 -070028
Alex Klein56355682019-02-07 10:36:54 -070029# The image.proto ImageType enum ids.
David Burgerb171d652019-05-13 16:07:00 -060030_BASE_ID = common_pb2.BASE
31_DEV_ID = common_pb2.DEV
32_TEST_ID = common_pb2.TEST
Alex Klein21b95022019-05-09 14:14:46 -060033_BASE_VM_ID = common_pb2.BASE_VM
34_TEST_VM_ID = common_pb2.TEST_VM
Michael Mortenseneefe8952019-08-12 15:37:15 -060035_RECOVERY_ID = common_pb2.RECOVERY
36_FACTORY_ID = common_pb2.FACTORY
37_FIRMWARE_ID = common_pb2.FIRMWARE
Trent Begin008cade2019-10-31 13:40:59 -060038_BASE_GUEST_VM_ID = common_pb2.BASE_GUEST_VM
39_TEST_GUEST_VM_ID = common_pb2.TEST_GUEST_VM
Alex Klein56355682019-02-07 10:36:54 -070040
41# Dict to allow easily translating names to enum ids and vice versa.
42_IMAGE_MAPPING = {
43 _BASE_ID: constants.IMAGE_TYPE_BASE,
44 constants.IMAGE_TYPE_BASE: _BASE_ID,
45 _DEV_ID: constants.IMAGE_TYPE_DEV,
46 constants.IMAGE_TYPE_DEV: _DEV_ID,
47 _TEST_ID: constants.IMAGE_TYPE_TEST,
48 constants.IMAGE_TYPE_TEST: _TEST_ID,
Michael Mortenseneefe8952019-08-12 15:37:15 -060049 _RECOVERY_ID: constants.IMAGE_TYPE_RECOVERY,
50 constants.IMAGE_TYPE_RECOVERY: _RECOVERY_ID,
51 _FACTORY_ID: constants.IMAGE_TYPE_FACTORY,
52 constants.IMAGE_TYPE_FACTORY: _FACTORY_ID,
53 _FIRMWARE_ID: constants.IMAGE_TYPE_FIRMWARE,
54 constants.IMAGE_TYPE_FIRMWARE: _FIRMWARE_ID,
Alex Klein56355682019-02-07 10:36:54 -070055}
56
Alex Klein21b95022019-05-09 14:14:46 -060057_VM_IMAGE_MAPPING = {
58 _BASE_VM_ID: _IMAGE_MAPPING[_BASE_ID],
59 _TEST_VM_ID: _IMAGE_MAPPING[_TEST_ID],
Trent Begin008cade2019-10-31 13:40:59 -060060 _BASE_GUEST_VM_ID: _IMAGE_MAPPING[_BASE_ID],
61 _TEST_GUEST_VM_ID: _IMAGE_MAPPING[_TEST_ID],
Alex Klein21b95022019-05-09 14:14:46 -060062}
63
Jack Neus761e1842020-12-01 18:20:11 +000064# Supported image types for PushImage.
65SUPPORTED_IMAGE_TYPES = {
66 common_pb2.IMAGE_TYPE_RECOVERY: constants.IMAGE_TYPE_RECOVERY,
67 common_pb2.IMAGE_TYPE_FACTORY: constants.IMAGE_TYPE_FACTORY,
68 common_pb2.IMAGE_TYPE_FIRMWARE: constants.IMAGE_TYPE_FIRMWARE,
69 common_pb2.IMAGE_TYPE_ACCESSORY_USBPD: constants.IMAGE_TYPE_ACCESSORY_USBPD,
70 common_pb2.IMAGE_TYPE_ACCESSORY_RWSIG: constants.IMAGE_TYPE_ACCESSORY_RWSIG,
71 common_pb2.IMAGE_TYPE_BASE: constants.IMAGE_TYPE_BASE,
72 common_pb2.IMAGE_TYPE_GSC_FIRMWARE: constants.IMAGE_TYPE_GSC_FIRMWARE
73}
74
Alex Klein56355682019-02-07 10:36:54 -070075
Michael Mortensen10146cf2019-11-19 19:59:22 -070076def _CreateResponse(_input_proto, output_proto, _config):
77 """Set output_proto success field on a successful Create response."""
78 output_proto.success = True
79
80
81@faux.success(_CreateResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -070082@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -060083@validate.require('build_target.name')
Alex Klein231d2da2019-07-22 16:44:45 -060084@validate.validation_complete
Will Bradley9bc85452019-10-10 10:48:21 -060085@metrics.collect_metrics
Alex Klein231d2da2019-07-22 16:44:45 -060086def Create(input_proto, output_proto, _config):
Alex Klein56355682019-02-07 10:36:54 -070087 """Build an image.
88
89 Args:
90 input_proto (image_pb2.CreateImageRequest): The input message.
91 output_proto (image_pb2.CreateImageResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -060092 _config (api_config.ApiConfig): The API call config.
Alex Klein56355682019-02-07 10:36:54 -070093 """
94 board = input_proto.build_target.name
Alex Klein56355682019-02-07 10:36:54 -070095
Alex Klein56355682019-02-07 10:36:54 -070096 # Build the base image if no images provided.
97 to_build = input_proto.image_types or [_BASE_ID]
Alex Klein56355682019-02-07 10:36:54 -070098
Alex Klein21b95022019-05-09 14:14:46 -060099 image_types, vm_types = _ParseImagesToCreate(to_build)
100 build_config = _ParseCreateBuildConfig(input_proto)
Alex Klein56355682019-02-07 10:36:54 -0700101
102 # Sorted isn't really necessary here, but it's much easier to test.
Jack Neus761e1842020-12-01 18:20:11 +0000103 result = image.Build(
104 board=board, images=sorted(list(image_types)), config=build_config)
Alex Klein56355682019-02-07 10:36:54 -0700105
Alex Klein1bcd9882019-03-19 13:25:24 -0600106 output_proto.success = result.success
Will Bradley29a49c22019-10-21 11:50:08 -0600107
Alex Klein1bcd9882019-03-19 13:25:24 -0600108 if result.success:
109 # Success -- we need to list out the images we built in the output.
110 _PopulateBuiltImages(board, image_types, output_proto)
Will Bradley29a49c22019-10-21 11:50:08 -0600111
112 if vm_types:
Trent Begin008cade2019-10-31 13:40:59 -0600113 for vm_type in vm_types:
114 is_test = vm_type in [_TEST_VM_ID, _TEST_GUEST_VM_ID]
115 try:
116 if vm_type in [_BASE_GUEST_VM_ID, _TEST_GUEST_VM_ID]:
117 vm_path = image.CreateGuestVm(board, is_test=is_test)
118 else:
Sean Abraham87545342020-06-03 14:24:19 -0600119 vm_path = image.CreateVm(
120 board, disk_layout=build_config.disk_layout, is_test=is_test)
Trent Begin008cade2019-10-31 13:40:59 -0600121 except image.ImageToVmError as e:
122 cros_build_lib.Die(e)
Will Bradley29a49c22019-10-21 11:50:08 -0600123
Trent Begin008cade2019-10-31 13:40:59 -0600124 new_image = output_proto.images.add()
125 new_image.path = vm_path
126 new_image.type = vm_type
127 new_image.build_target.name = board
Will Bradley29a49c22019-10-21 11:50:08 -0600128
129 # Read metric events log and pipe them into output_proto.events.
130 deserialize_metrics_log(output_proto.events, prefix=board)
131 return controller.RETURN_CODE_SUCCESS
132
Alex Klein1bcd9882019-03-19 13:25:24 -0600133 else:
Alex Klein2557b4f2019-07-11 14:34:00 -0600134 # Failure, include all of the failed packages in the output when available.
135 if not result.failed_packages:
136 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
137
Alex Klein1bcd9882019-03-19 13:25:24 -0600138 for package in result.failed_packages:
139 current = output_proto.failed_packages.add()
Alex Kleine9a7dbf2020-10-06 18:12:12 -0600140 controller_util.serialize_package_info(package, current)
Alex Klein1bcd9882019-03-19 13:25:24 -0600141
Alex Klein8cb365a2019-05-15 16:24:53 -0600142 return controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE
Alex Klein1bcd9882019-03-19 13:25:24 -0600143
Alex Klein21b95022019-05-09 14:14:46 -0600144
145def _ParseImagesToCreate(to_build):
146 """Helper function to parse the image types to build.
147
148 This function exists just to clean up the Create function.
149
150 Args:
151 to_build (list[int]): The image type list.
152
153 Returns:
154 (set, set): The image and vm types, respectively, that need to be built.
155 """
156 image_types = set()
157 vm_types = set()
158 for current in to_build:
159 if current in _IMAGE_MAPPING:
160 image_types.add(_IMAGE_MAPPING[current])
161 elif current in _VM_IMAGE_MAPPING:
162 vm_types.add(current)
163 # Make sure we build the image required to build the VM.
164 image_types.add(_VM_IMAGE_MAPPING[current])
165 else:
166 # Not expected, but at least it will be obvious if this comes up.
167 cros_build_lib.Die(
168 "The service's known image types do not match those in image.proto. "
169 'Unknown Enum ID: %s' % current)
170
Trent Begin008cade2019-10-31 13:40:59 -0600171 # We can only build one type of these images at a time since image_to_vm.sh
172 # uses the default path if a name is not provided.
173 if vm_types.issuperset({_BASE_VM_ID, _TEST_VM_ID}):
Alex Klein21b95022019-05-09 14:14:46 -0600174 cros_build_lib.Die('Cannot create more than one VM.')
175
176 return image_types, vm_types
177
178
179def _ParseCreateBuildConfig(input_proto):
180 """Helper to parse the image build config for Create."""
181 enable_rootfs_verification = not input_proto.disable_rootfs_verification
182 version = input_proto.version or None
183 disk_layout = input_proto.disk_layout or None
184 builder_path = input_proto.builder_path or None
185 return image.BuildConfig(
Jack Neus761e1842020-12-01 18:20:11 +0000186 enable_rootfs_verification=enable_rootfs_verification,
187 replace=True,
188 version=version,
189 disk_layout=disk_layout,
190 builder_path=builder_path,
Alex Klein21b95022019-05-09 14:14:46 -0600191 )
192
Alex Klein1bcd9882019-03-19 13:25:24 -0600193
194def _PopulateBuiltImages(board, image_types, output_proto):
195 """Helper to list out built images for Create."""
Alex Klein56355682019-02-07 10:36:54 -0700196 # Build out the ImageType->ImagePath mapping in the output.
197 # We're using the default path, so just fetch that, but read the symlink so
198 # the path we're returning is somewhat more permanent.
199 latest_link = image_lib.GetLatestImageLink(board)
Alex Klein4f0eb432019-05-02 13:56:04 -0600200 base_path = os.path.realpath(latest_link)
Alex Klein56355682019-02-07 10:36:54 -0700201
202 for current in image_types:
203 type_id = _IMAGE_MAPPING[current]
204 path = os.path.join(base_path, constants.IMAGE_TYPE_TO_NAME[current])
205
206 new_image = output_proto.images.add()
207 new_image.path = path
208 new_image.type = type_id
Alex Klein4f0eb432019-05-02 13:56:04 -0600209 new_image.build_target.name = board
210
211
Michael Mortensen10146cf2019-11-19 19:59:22 -0700212def _SignerTestResponse(_input_proto, output_proto, _config):
213 """Set output_proto success field on a successful SignerTest response."""
214 output_proto.success = True
215 return controller.RETURN_CODE_SUCCESS
216
217
218@faux.success(_SignerTestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700219@faux.empty_completed_unsuccessfully_error
Michael Mortensenc83c9952019-08-05 12:15:12 -0600220@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600221@validate.validation_complete
222def SignerTest(input_proto, output_proto, _config):
Michael Mortensenc83c9952019-08-05 12:15:12 -0600223 """Run image tests.
224
225 Args:
226 input_proto (image_pb2.ImageTestRequest): The input message.
227 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600228 _config (api_config.ApiConfig): The API call config.
Michael Mortensenc83c9952019-08-05 12:15:12 -0600229 """
Michael Mortensenc83c9952019-08-05 12:15:12 -0600230 image_path = input_proto.image.path
231
Alex Klein231d2da2019-07-22 16:44:45 -0600232 result = image_lib.SecurityTest(image=image_path)
Michael Mortensenc83c9952019-08-05 12:15:12 -0600233 output_proto.success = result
234 if result:
235 return controller.RETURN_CODE_SUCCESS
236 else:
237 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
238
Alex Klein076841b2019-08-29 15:19:39 -0600239
Michael Mortensen10146cf2019-11-19 19:59:22 -0700240def _TestResponse(_input_proto, output_proto, _config):
241 """Set output_proto success field on a successful Test response."""
242 output_proto.success = True
243 return controller.RETURN_CODE_SUCCESS
244
245
246@faux.success(_TestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700247@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -0600248@validate.require('build_target.name', 'result.directory')
249@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600250def Test(input_proto, output_proto, config):
Alex Klein2966e302019-01-17 13:29:38 -0700251 """Run image tests.
252
253 Args:
254 input_proto (image_pb2.ImageTestRequest): The input message.
255 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600256 config (api_config.ApiConfig): The API call config.
Alex Klein2966e302019-01-17 13:29:38 -0700257 """
258 image_path = input_proto.image.path
259 board = input_proto.build_target.name
260 result_directory = input_proto.result.directory
261
Alex Klein2966e302019-01-17 13:29:38 -0700262 if not os.path.isfile(image_path) or not image_path.endswith('.bin'):
Alex Klein4f0eb432019-05-02 13:56:04 -0600263 cros_build_lib.Die(
Alex Klein2966e302019-01-17 13:29:38 -0700264 'The image.path must be an existing image file with a .bin extension.')
265
Alex Klein231d2da2019-07-22 16:44:45 -0600266 if config.validate_only:
267 return controller.RETURN_CODE_VALID_INPUT
268
Alex Klein8cb365a2019-05-15 16:24:53 -0600269 success = image.Test(board, result_directory, image_dir=image_path)
270 output_proto.success = success
271
272 if success:
273 return controller.RETURN_CODE_SUCCESS
274 else:
275 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
Jack Neus761e1842020-12-01 18:20:11 +0000276
277
278@faux.empty_success
279@faux.empty_completed_unsuccessfully_error
280@validate.require('gs_image_dir', 'sysroot.build_target.name')
281def PushImage(input_proto, _output_proto, config):
282 """Push artifacts from the archive bucket to the release bucket.
283
284 Wraps chromite/scripts/pushimage.py.
285
286 Args:
287 input_proto (PushImageRequest): Input proto.
288 _output_proto (PushImageResponse): Output proto.
289 config (api.config.ApiConfig): The API call config.
290
291 Returns:
292 A controller return code (e.g. controller.RETURN_CODE_SUCCESS).
293 """
294 sign_types = []
295 if input_proto.sign_types:
296 for sign_type in input_proto.sign_types:
297 if sign_type not in SUPPORTED_IMAGE_TYPES:
298 logging.error('unsupported sign type %g', sign_type)
299 return controller.RETURN_CODE_INVALID_INPUT
300 sign_types.append(SUPPORTED_IMAGE_TYPES[sign_type])
301
302 # If configured for validation only we're done here.
303 if config.validate_only:
304 return controller.RETURN_CODE_VALID_INPUT
305
Jack Neus485a9d22020-12-21 03:15:15 +0000306 kwargs = {}
307 if input_proto.profile.name:
308 kwargs['profile'] = input_proto.profile.name
309 if input_proto.dest_bucket:
310 kwargs['dest_bucket'] = input_proto.dest_bucket
Jack Neus761e1842020-12-01 18:20:11 +0000311 try:
312 pushimage.PushImage(
313 input_proto.gs_image_dir,
314 input_proto.sysroot.build_target.name,
315 dry_run=input_proto.dryrun,
Jack Neus485a9d22020-12-21 03:15:15 +0000316 sign_types=sign_types,
317 **kwargs)
Jack Neus761e1842020-12-01 18:20:11 +0000318 return controller.RETURN_CODE_SUCCESS
319 except Exception:
Jack Neuse3150a42021-01-29 17:16:36 +0000320 logging.error('PushImage failed: ', exc_info=True)
Jack Neus761e1842020-12-01 18:20:11 +0000321 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY