blob: 7b01107c07238b0018afac6df7137528b30f4aaa [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
Alex Klein56355682019-02-07 10:36:54 -070026# The image.proto ImageType enum ids.
David Burgerb171d652019-05-13 16:07:00 -060027_BASE_ID = common_pb2.BASE
28_DEV_ID = common_pb2.DEV
29_TEST_ID = common_pb2.TEST
Alex Klein21b95022019-05-09 14:14:46 -060030_BASE_VM_ID = common_pb2.BASE_VM
31_TEST_VM_ID = common_pb2.TEST_VM
Michael Mortenseneefe8952019-08-12 15:37:15 -060032_RECOVERY_ID = common_pb2.RECOVERY
33_FACTORY_ID = common_pb2.FACTORY
34_FIRMWARE_ID = common_pb2.FIRMWARE
Alex Klein56355682019-02-07 10:36:54 -070035
36# Dict to allow easily translating names to enum ids and vice versa.
37_IMAGE_MAPPING = {
38 _BASE_ID: constants.IMAGE_TYPE_BASE,
39 constants.IMAGE_TYPE_BASE: _BASE_ID,
40 _DEV_ID: constants.IMAGE_TYPE_DEV,
41 constants.IMAGE_TYPE_DEV: _DEV_ID,
42 _TEST_ID: constants.IMAGE_TYPE_TEST,
43 constants.IMAGE_TYPE_TEST: _TEST_ID,
Michael Mortenseneefe8952019-08-12 15:37:15 -060044 _RECOVERY_ID: constants.IMAGE_TYPE_RECOVERY,
45 constants.IMAGE_TYPE_RECOVERY: _RECOVERY_ID,
46 _FACTORY_ID: constants.IMAGE_TYPE_FACTORY,
47 constants.IMAGE_TYPE_FACTORY: _FACTORY_ID,
48 _FIRMWARE_ID: constants.IMAGE_TYPE_FIRMWARE,
49 constants.IMAGE_TYPE_FIRMWARE: _FIRMWARE_ID,
Alex Klein56355682019-02-07 10:36:54 -070050}
51
Alex Klein21b95022019-05-09 14:14:46 -060052_VM_IMAGE_MAPPING = {
53 _BASE_VM_ID: _IMAGE_MAPPING[_BASE_ID],
54 _TEST_VM_ID: _IMAGE_MAPPING[_TEST_ID],
55}
56
Alex Klein56355682019-02-07 10:36:54 -070057
Michael Mortensen10146cf2019-11-19 19:59:22 -070058def _CreateResponse(_input_proto, output_proto, _config):
59 """Set output_proto success field on a successful Create response."""
60 output_proto.success = True
61
62
63@faux.success(_CreateResponse)
64@faux.empty_error
Alex Klein2b236722019-06-19 15:44:26 -060065@validate.require('build_target.name')
Alex Klein231d2da2019-07-22 16:44:45 -060066@validate.validation_complete
Will Bradley9bc85452019-10-10 10:48:21 -060067@metrics.collect_metrics
Alex Klein231d2da2019-07-22 16:44:45 -060068def Create(input_proto, output_proto, _config):
Alex Klein56355682019-02-07 10:36:54 -070069 """Build an image.
70
71 Args:
72 input_proto (image_pb2.CreateImageRequest): The input message.
73 output_proto (image_pb2.CreateImageResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -060074 _config (api_config.ApiConfig): The API call config.
Alex Klein56355682019-02-07 10:36:54 -070075 """
76 board = input_proto.build_target.name
Alex Klein56355682019-02-07 10:36:54 -070077
Alex Klein56355682019-02-07 10:36:54 -070078 # Build the base image if no images provided.
79 to_build = input_proto.image_types or [_BASE_ID]
Alex Klein56355682019-02-07 10:36:54 -070080
Alex Klein21b95022019-05-09 14:14:46 -060081 image_types, vm_types = _ParseImagesToCreate(to_build)
82 build_config = _ParseCreateBuildConfig(input_proto)
Alex Klein56355682019-02-07 10:36:54 -070083
84 # Sorted isn't really necessary here, but it's much easier to test.
Alex Klein1bcd9882019-03-19 13:25:24 -060085 result = image.Build(board=board, images=sorted(list(image_types)),
86 config=build_config)
Alex Klein56355682019-02-07 10:36:54 -070087
Alex Klein1bcd9882019-03-19 13:25:24 -060088 output_proto.success = result.success
Will Bradley29a49c22019-10-21 11:50:08 -060089
Alex Klein1bcd9882019-03-19 13:25:24 -060090 if result.success:
91 # Success -- we need to list out the images we built in the output.
92 _PopulateBuiltImages(board, image_types, output_proto)
Will Bradley29a49c22019-10-21 11:50:08 -060093
94 if vm_types:
95 # There are VMs to build.
96 assert len(vm_types) == 1
97
98 vm_type = vm_types.pop()
99 is_test = vm_type == _TEST_VM_ID
100 try:
101 vm_path = image.CreateVm(board, is_test=is_test)
102 except image.ImageToVmError as e:
103 cros_build_lib.Die(e)
104
105 new_image = output_proto.images.add()
106 new_image.path = vm_path
107 new_image.type = vm_type
108 new_image.build_target.name = board
109
110 # Read metric events log and pipe them into output_proto.events.
111 deserialize_metrics_log(output_proto.events, prefix=board)
112 return controller.RETURN_CODE_SUCCESS
113
Alex Klein1bcd9882019-03-19 13:25:24 -0600114 else:
Alex Klein2557b4f2019-07-11 14:34:00 -0600115 # Failure, include all of the failed packages in the output when available.
116 if not result.failed_packages:
117 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
118
Alex Klein1bcd9882019-03-19 13:25:24 -0600119 for package in result.failed_packages:
120 current = output_proto.failed_packages.add()
121 current.category = package.category
122 current.package_name = package.package
123 if package.version:
124 current.version = package.version
125
Alex Klein8cb365a2019-05-15 16:24:53 -0600126 return controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE
Alex Klein1bcd9882019-03-19 13:25:24 -0600127
Alex Klein21b95022019-05-09 14:14:46 -0600128
129def _ParseImagesToCreate(to_build):
130 """Helper function to parse the image types to build.
131
132 This function exists just to clean up the Create function.
133
134 Args:
135 to_build (list[int]): The image type list.
136
137 Returns:
138 (set, set): The image and vm types, respectively, that need to be built.
139 """
140 image_types = set()
141 vm_types = set()
142 for current in to_build:
143 if current in _IMAGE_MAPPING:
144 image_types.add(_IMAGE_MAPPING[current])
145 elif current in _VM_IMAGE_MAPPING:
146 vm_types.add(current)
147 # Make sure we build the image required to build the VM.
148 image_types.add(_VM_IMAGE_MAPPING[current])
149 else:
150 # Not expected, but at least it will be obvious if this comes up.
151 cros_build_lib.Die(
152 "The service's known image types do not match those in image.proto. "
153 'Unknown Enum ID: %s' % current)
154
155 if len(vm_types) > 1:
156 cros_build_lib.Die('Cannot create more than one VM.')
157
158 return image_types, vm_types
159
160
161def _ParseCreateBuildConfig(input_proto):
162 """Helper to parse the image build config for Create."""
163 enable_rootfs_verification = not input_proto.disable_rootfs_verification
164 version = input_proto.version or None
165 disk_layout = input_proto.disk_layout or None
166 builder_path = input_proto.builder_path or None
167 return image.BuildConfig(
168 enable_rootfs_verification=enable_rootfs_verification, replace=True,
169 version=version, disk_layout=disk_layout, builder_path=builder_path,
170 )
171
Alex Klein1bcd9882019-03-19 13:25:24 -0600172
173def _PopulateBuiltImages(board, image_types, output_proto):
174 """Helper to list out built images for Create."""
Alex Klein56355682019-02-07 10:36:54 -0700175 # Build out the ImageType->ImagePath mapping in the output.
176 # We're using the default path, so just fetch that, but read the symlink so
177 # the path we're returning is somewhat more permanent.
178 latest_link = image_lib.GetLatestImageLink(board)
Alex Klein4f0eb432019-05-02 13:56:04 -0600179 base_path = os.path.realpath(latest_link)
Alex Klein56355682019-02-07 10:36:54 -0700180
181 for current in image_types:
182 type_id = _IMAGE_MAPPING[current]
183 path = os.path.join(base_path, constants.IMAGE_TYPE_TO_NAME[current])
184
185 new_image = output_proto.images.add()
186 new_image.path = path
187 new_image.type = type_id
Alex Klein4f0eb432019-05-02 13:56:04 -0600188 new_image.build_target.name = board
189
190
Michael Mortensen10146cf2019-11-19 19:59:22 -0700191def _SignerTestResponse(_input_proto, output_proto, _config):
192 """Set output_proto success field on a successful SignerTest response."""
193 output_proto.success = True
194 return controller.RETURN_CODE_SUCCESS
195
196
197@faux.success(_SignerTestResponse)
198@faux.empty_error
Michael Mortensenc83c9952019-08-05 12:15:12 -0600199@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600200@validate.validation_complete
201def SignerTest(input_proto, output_proto, _config):
Michael Mortensenc83c9952019-08-05 12:15:12 -0600202 """Run image tests.
203
204 Args:
205 input_proto (image_pb2.ImageTestRequest): The input message.
206 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600207 _config (api_config.ApiConfig): The API call config.
Michael Mortensenc83c9952019-08-05 12:15:12 -0600208 """
Michael Mortensenc83c9952019-08-05 12:15:12 -0600209 image_path = input_proto.image.path
210
Alex Klein231d2da2019-07-22 16:44:45 -0600211 result = image_lib.SecurityTest(image=image_path)
Michael Mortensenc83c9952019-08-05 12:15:12 -0600212 output_proto.success = result
213 if result:
214 return controller.RETURN_CODE_SUCCESS
215 else:
216 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
217
Alex Klein076841b2019-08-29 15:19:39 -0600218
Michael Mortensen10146cf2019-11-19 19:59:22 -0700219def _TestResponse(_input_proto, output_proto, _config):
220 """Set output_proto success field on a successful Test response."""
221 output_proto.success = True
222 return controller.RETURN_CODE_SUCCESS
223
224
225@faux.success(_TestResponse)
226@faux.empty_error
Alex Klein2b236722019-06-19 15:44:26 -0600227@validate.require('build_target.name', 'result.directory')
228@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600229def Test(input_proto, output_proto, config):
Alex Klein2966e302019-01-17 13:29:38 -0700230 """Run image tests.
231
232 Args:
233 input_proto (image_pb2.ImageTestRequest): The input message.
234 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600235 config (api_config.ApiConfig): The API call config.
Alex Klein2966e302019-01-17 13:29:38 -0700236 """
237 image_path = input_proto.image.path
238 board = input_proto.build_target.name
239 result_directory = input_proto.result.directory
240
Alex Klein2966e302019-01-17 13:29:38 -0700241 if not os.path.isfile(image_path) or not image_path.endswith('.bin'):
Alex Klein4f0eb432019-05-02 13:56:04 -0600242 cros_build_lib.Die(
Alex Klein2966e302019-01-17 13:29:38 -0700243 'The image.path must be an existing image file with a .bin extension.')
244
Alex Klein231d2da2019-07-22 16:44:45 -0600245 if config.validate_only:
246 return controller.RETURN_CODE_VALID_INPUT
247
Alex Klein8cb365a2019-05-15 16:24:53 -0600248 success = image.Test(board, result_directory, image_dir=image_path)
249 output_proto.success = success
250
251 if success:
252 return controller.RETURN_CODE_SUCCESS
253 else:
254 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY