blob: 34dea9d2f8d54ae409d200a3d5d91242b878cf57 [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
David Burgerb171d652019-05-13 16:07:00 -060018from chromite.api.gen.chromiumos import common_pb2
Will Bradley9bc85452019-10-10 10:48:21 -060019from chromite.api.metrics import deserialize_metrics_log
Alex Klein4f0eb432019-05-02 13:56:04 -060020from chromite.lib import cros_build_lib
Alex Klein56355682019-02-07 10:36:54 -070021from chromite.lib import constants
22from chromite.lib import image_lib
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
Mike Frysingeref94e4c2020-02-10 23:59:54 -050026
Alex Klein56355682019-02-07 10:36:54 -070027# The image.proto ImageType enum ids.
David Burgerb171d652019-05-13 16:07:00 -060028_BASE_ID = common_pb2.BASE
29_DEV_ID = common_pb2.DEV
30_TEST_ID = common_pb2.TEST
Alex Klein21b95022019-05-09 14:14:46 -060031_BASE_VM_ID = common_pb2.BASE_VM
32_TEST_VM_ID = common_pb2.TEST_VM
Michael Mortenseneefe8952019-08-12 15:37:15 -060033_RECOVERY_ID = common_pb2.RECOVERY
34_FACTORY_ID = common_pb2.FACTORY
35_FIRMWARE_ID = common_pb2.FIRMWARE
Trent Begin008cade2019-10-31 13:40:59 -060036_BASE_GUEST_VM_ID = common_pb2.BASE_GUEST_VM
37_TEST_GUEST_VM_ID = common_pb2.TEST_GUEST_VM
Alex Klein56355682019-02-07 10:36:54 -070038
39# Dict to allow easily translating names to enum ids and vice versa.
40_IMAGE_MAPPING = {
41 _BASE_ID: constants.IMAGE_TYPE_BASE,
42 constants.IMAGE_TYPE_BASE: _BASE_ID,
43 _DEV_ID: constants.IMAGE_TYPE_DEV,
44 constants.IMAGE_TYPE_DEV: _DEV_ID,
45 _TEST_ID: constants.IMAGE_TYPE_TEST,
46 constants.IMAGE_TYPE_TEST: _TEST_ID,
Michael Mortenseneefe8952019-08-12 15:37:15 -060047 _RECOVERY_ID: constants.IMAGE_TYPE_RECOVERY,
48 constants.IMAGE_TYPE_RECOVERY: _RECOVERY_ID,
49 _FACTORY_ID: constants.IMAGE_TYPE_FACTORY,
50 constants.IMAGE_TYPE_FACTORY: _FACTORY_ID,
51 _FIRMWARE_ID: constants.IMAGE_TYPE_FIRMWARE,
52 constants.IMAGE_TYPE_FIRMWARE: _FIRMWARE_ID,
Alex Klein56355682019-02-07 10:36:54 -070053}
54
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
Alex Klein56355682019-02-07 10:36:54 -070062
Michael Mortensen10146cf2019-11-19 19:59:22 -070063def _CreateResponse(_input_proto, output_proto, _config):
64 """Set output_proto success field on a successful Create response."""
65 output_proto.success = True
66
67
68@faux.success(_CreateResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -070069@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -060070@validate.require('build_target.name')
Alex Klein231d2da2019-07-22 16:44:45 -060071@validate.validation_complete
Will Bradley9bc85452019-10-10 10:48:21 -060072@metrics.collect_metrics
Alex Klein231d2da2019-07-22 16:44:45 -060073def Create(input_proto, output_proto, _config):
Alex Klein56355682019-02-07 10:36:54 -070074 """Build an image.
75
76 Args:
77 input_proto (image_pb2.CreateImageRequest): The input message.
78 output_proto (image_pb2.CreateImageResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -060079 _config (api_config.ApiConfig): The API call config.
Alex Klein56355682019-02-07 10:36:54 -070080 """
81 board = input_proto.build_target.name
Alex Klein56355682019-02-07 10:36:54 -070082
Alex Klein56355682019-02-07 10:36:54 -070083 # Build the base image if no images provided.
84 to_build = input_proto.image_types or [_BASE_ID]
Alex Klein56355682019-02-07 10:36:54 -070085
Alex Klein21b95022019-05-09 14:14:46 -060086 image_types, vm_types = _ParseImagesToCreate(to_build)
87 build_config = _ParseCreateBuildConfig(input_proto)
Alex Klein56355682019-02-07 10:36:54 -070088
89 # Sorted isn't really necessary here, but it's much easier to test.
Alex Klein1bcd9882019-03-19 13:25:24 -060090 result = image.Build(board=board, images=sorted(list(image_types)),
91 config=build_config)
Alex Klein56355682019-02-07 10:36:54 -070092
Alex Klein1bcd9882019-03-19 13:25:24 -060093 output_proto.success = result.success
Will Bradley29a49c22019-10-21 11:50:08 -060094
Alex Klein1bcd9882019-03-19 13:25:24 -060095 if result.success:
96 # Success -- we need to list out the images we built in the output.
97 _PopulateBuiltImages(board, image_types, output_proto)
Will Bradley29a49c22019-10-21 11:50:08 -060098
99 if vm_types:
Trent Begin008cade2019-10-31 13:40:59 -0600100 for vm_type in vm_types:
101 is_test = vm_type in [_TEST_VM_ID, _TEST_GUEST_VM_ID]
102 try:
103 if vm_type in [_BASE_GUEST_VM_ID, _TEST_GUEST_VM_ID]:
104 vm_path = image.CreateGuestVm(board, is_test=is_test)
105 else:
Sean Abraham87545342020-06-03 14:24:19 -0600106 vm_path = image.CreateVm(
107 board, disk_layout=build_config.disk_layout, is_test=is_test)
Trent Begin008cade2019-10-31 13:40:59 -0600108 except image.ImageToVmError as e:
109 cros_build_lib.Die(e)
Will Bradley29a49c22019-10-21 11:50:08 -0600110
Trent Begin008cade2019-10-31 13:40:59 -0600111 new_image = output_proto.images.add()
112 new_image.path = vm_path
113 new_image.type = vm_type
114 new_image.build_target.name = board
Will Bradley29a49c22019-10-21 11:50:08 -0600115
116 # Read metric events log and pipe them into output_proto.events.
117 deserialize_metrics_log(output_proto.events, prefix=board)
118 return controller.RETURN_CODE_SUCCESS
119
Alex Klein1bcd9882019-03-19 13:25:24 -0600120 else:
Alex Klein2557b4f2019-07-11 14:34:00 -0600121 # Failure, include all of the failed packages in the output when available.
122 if not result.failed_packages:
123 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
124
Alex Klein1bcd9882019-03-19 13:25:24 -0600125 for package in result.failed_packages:
126 current = output_proto.failed_packages.add()
127 current.category = package.category
128 current.package_name = package.package
129 if package.version:
130 current.version = package.version
131
Alex Klein8cb365a2019-05-15 16:24:53 -0600132 return controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE
Alex Klein1bcd9882019-03-19 13:25:24 -0600133
Alex Klein21b95022019-05-09 14:14:46 -0600134
135def _ParseImagesToCreate(to_build):
136 """Helper function to parse the image types to build.
137
138 This function exists just to clean up the Create function.
139
140 Args:
141 to_build (list[int]): The image type list.
142
143 Returns:
144 (set, set): The image and vm types, respectively, that need to be built.
145 """
146 image_types = set()
147 vm_types = set()
148 for current in to_build:
149 if current in _IMAGE_MAPPING:
150 image_types.add(_IMAGE_MAPPING[current])
151 elif current in _VM_IMAGE_MAPPING:
152 vm_types.add(current)
153 # Make sure we build the image required to build the VM.
154 image_types.add(_VM_IMAGE_MAPPING[current])
155 else:
156 # Not expected, but at least it will be obvious if this comes up.
157 cros_build_lib.Die(
158 "The service's known image types do not match those in image.proto. "
159 'Unknown Enum ID: %s' % current)
160
Trent Begin008cade2019-10-31 13:40:59 -0600161 # We can only build one type of these images at a time since image_to_vm.sh
162 # uses the default path if a name is not provided.
163 if vm_types.issuperset({_BASE_VM_ID, _TEST_VM_ID}):
Alex Klein21b95022019-05-09 14:14:46 -0600164 cros_build_lib.Die('Cannot create more than one VM.')
165
166 return image_types, vm_types
167
168
169def _ParseCreateBuildConfig(input_proto):
170 """Helper to parse the image build config for Create."""
171 enable_rootfs_verification = not input_proto.disable_rootfs_verification
172 version = input_proto.version or None
173 disk_layout = input_proto.disk_layout or None
174 builder_path = input_proto.builder_path or None
175 return image.BuildConfig(
176 enable_rootfs_verification=enable_rootfs_verification, replace=True,
177 version=version, disk_layout=disk_layout, builder_path=builder_path,
178 )
179
Alex Klein1bcd9882019-03-19 13:25:24 -0600180
181def _PopulateBuiltImages(board, image_types, output_proto):
182 """Helper to list out built images for Create."""
Alex Klein56355682019-02-07 10:36:54 -0700183 # Build out the ImageType->ImagePath mapping in the output.
184 # We're using the default path, so just fetch that, but read the symlink so
185 # the path we're returning is somewhat more permanent.
186 latest_link = image_lib.GetLatestImageLink(board)
Alex Klein4f0eb432019-05-02 13:56:04 -0600187 base_path = os.path.realpath(latest_link)
Alex Klein56355682019-02-07 10:36:54 -0700188
189 for current in image_types:
190 type_id = _IMAGE_MAPPING[current]
191 path = os.path.join(base_path, constants.IMAGE_TYPE_TO_NAME[current])
192
193 new_image = output_proto.images.add()
194 new_image.path = path
195 new_image.type = type_id
Alex Klein4f0eb432019-05-02 13:56:04 -0600196 new_image.build_target.name = board
197
198
Michael Mortensen10146cf2019-11-19 19:59:22 -0700199def _SignerTestResponse(_input_proto, output_proto, _config):
200 """Set output_proto success field on a successful SignerTest response."""
201 output_proto.success = True
202 return controller.RETURN_CODE_SUCCESS
203
204
205@faux.success(_SignerTestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700206@faux.empty_completed_unsuccessfully_error
Michael Mortensenc83c9952019-08-05 12:15:12 -0600207@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600208@validate.validation_complete
209def SignerTest(input_proto, output_proto, _config):
Michael Mortensenc83c9952019-08-05 12:15:12 -0600210 """Run image tests.
211
212 Args:
213 input_proto (image_pb2.ImageTestRequest): The input message.
214 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600215 _config (api_config.ApiConfig): The API call config.
Michael Mortensenc83c9952019-08-05 12:15:12 -0600216 """
Michael Mortensenc83c9952019-08-05 12:15:12 -0600217 image_path = input_proto.image.path
218
Alex Klein231d2da2019-07-22 16:44:45 -0600219 result = image_lib.SecurityTest(image=image_path)
Michael Mortensenc83c9952019-08-05 12:15:12 -0600220 output_proto.success = result
221 if result:
222 return controller.RETURN_CODE_SUCCESS
223 else:
224 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
225
Alex Klein076841b2019-08-29 15:19:39 -0600226
Michael Mortensen10146cf2019-11-19 19:59:22 -0700227def _TestResponse(_input_proto, output_proto, _config):
228 """Set output_proto success field on a successful Test response."""
229 output_proto.success = True
230 return controller.RETURN_CODE_SUCCESS
231
232
233@faux.success(_TestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700234@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -0600235@validate.require('build_target.name', 'result.directory')
236@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600237def Test(input_proto, output_proto, config):
Alex Klein2966e302019-01-17 13:29:38 -0700238 """Run image tests.
239
240 Args:
241 input_proto (image_pb2.ImageTestRequest): The input message.
242 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600243 config (api_config.ApiConfig): The API call config.
Alex Klein2966e302019-01-17 13:29:38 -0700244 """
245 image_path = input_proto.image.path
246 board = input_proto.build_target.name
247 result_directory = input_proto.result.directory
248
Alex Klein2966e302019-01-17 13:29:38 -0700249 if not os.path.isfile(image_path) or not image_path.endswith('.bin'):
Alex Klein4f0eb432019-05-02 13:56:04 -0600250 cros_build_lib.Die(
Alex Klein2966e302019-01-17 13:29:38 -0700251 'The image.path must be an existing image file with a .bin extension.')
252
Alex Klein231d2da2019-07-22 16:44:45 -0600253 if config.validate_only:
254 return controller.RETURN_CODE_VALID_INPUT
255
Alex Klein8cb365a2019-05-15 16:24:53 -0600256 success = image.Test(board, result_directory, image_dir=image_path)
257 output_proto.success = success
258
259 if success:
260 return controller.RETURN_CODE_SUCCESS
261 else:
262 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY