blob: 66fc9a6c2e3eacda43ec5245157bb855714a95b1 [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
Mike Frysingeref94e4c2020-02-10 23:59:54 -050014import sys
Alex Klein2966e302019-01-17 13:29:38 -070015
Alex Klein8cb365a2019-05-15 16:24:53 -060016from chromite.api import controller
Alex Klein076841b2019-08-29 15:19:39 -060017from chromite.api import faux
Alex Klein2b236722019-06-19 15:44:26 -060018from chromite.api import validate
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
Alex Kleinb7cdbe62019-02-22 11:41:32 -070024from chromite.service import image
Will Bradley9bc85452019-10-10 10:48:21 -060025from chromite.utils import metrics
Alex Klein2966e302019-01-17 13:29:38 -070026
Mike Frysingeref94e4c2020-02-10 23:59:54 -050027
28assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
29
30
Alex Klein56355682019-02-07 10:36:54 -070031# The image.proto ImageType enum ids.
David Burgerb171d652019-05-13 16:07:00 -060032_BASE_ID = common_pb2.BASE
33_DEV_ID = common_pb2.DEV
34_TEST_ID = common_pb2.TEST
Alex Klein21b95022019-05-09 14:14:46 -060035_BASE_VM_ID = common_pb2.BASE_VM
36_TEST_VM_ID = common_pb2.TEST_VM
Michael Mortenseneefe8952019-08-12 15:37:15 -060037_RECOVERY_ID = common_pb2.RECOVERY
38_FACTORY_ID = common_pb2.FACTORY
39_FIRMWARE_ID = common_pb2.FIRMWARE
Trent Begin008cade2019-10-31 13:40:59 -060040_BASE_GUEST_VM_ID = common_pb2.BASE_GUEST_VM
41_TEST_GUEST_VM_ID = common_pb2.TEST_GUEST_VM
Alex Klein56355682019-02-07 10:36:54 -070042
43# Dict to allow easily translating names to enum ids and vice versa.
44_IMAGE_MAPPING = {
45 _BASE_ID: constants.IMAGE_TYPE_BASE,
46 constants.IMAGE_TYPE_BASE: _BASE_ID,
47 _DEV_ID: constants.IMAGE_TYPE_DEV,
48 constants.IMAGE_TYPE_DEV: _DEV_ID,
49 _TEST_ID: constants.IMAGE_TYPE_TEST,
50 constants.IMAGE_TYPE_TEST: _TEST_ID,
Michael Mortenseneefe8952019-08-12 15:37:15 -060051 _RECOVERY_ID: constants.IMAGE_TYPE_RECOVERY,
52 constants.IMAGE_TYPE_RECOVERY: _RECOVERY_ID,
53 _FACTORY_ID: constants.IMAGE_TYPE_FACTORY,
54 constants.IMAGE_TYPE_FACTORY: _FACTORY_ID,
55 _FIRMWARE_ID: constants.IMAGE_TYPE_FIRMWARE,
56 constants.IMAGE_TYPE_FIRMWARE: _FIRMWARE_ID,
Alex Klein56355682019-02-07 10:36:54 -070057}
58
Alex Klein21b95022019-05-09 14:14:46 -060059_VM_IMAGE_MAPPING = {
60 _BASE_VM_ID: _IMAGE_MAPPING[_BASE_ID],
61 _TEST_VM_ID: _IMAGE_MAPPING[_TEST_ID],
Trent Begin008cade2019-10-31 13:40:59 -060062 _BASE_GUEST_VM_ID: _IMAGE_MAPPING[_BASE_ID],
63 _TEST_GUEST_VM_ID: _IMAGE_MAPPING[_TEST_ID],
Alex Klein21b95022019-05-09 14:14:46 -060064}
65
Alex Klein56355682019-02-07 10:36:54 -070066
Michael Mortensen10146cf2019-11-19 19:59:22 -070067def _CreateResponse(_input_proto, output_proto, _config):
68 """Set output_proto success field on a successful Create response."""
69 output_proto.success = True
70
71
72@faux.success(_CreateResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -070073@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -060074@validate.require('build_target.name')
Alex Klein231d2da2019-07-22 16:44:45 -060075@validate.validation_complete
Will Bradley9bc85452019-10-10 10:48:21 -060076@metrics.collect_metrics
Alex Klein231d2da2019-07-22 16:44:45 -060077def Create(input_proto, output_proto, _config):
Alex Klein56355682019-02-07 10:36:54 -070078 """Build an image.
79
80 Args:
81 input_proto (image_pb2.CreateImageRequest): The input message.
82 output_proto (image_pb2.CreateImageResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -060083 _config (api_config.ApiConfig): The API call config.
Alex Klein56355682019-02-07 10:36:54 -070084 """
85 board = input_proto.build_target.name
Alex Klein56355682019-02-07 10:36:54 -070086
Alex Klein56355682019-02-07 10:36:54 -070087 # Build the base image if no images provided.
88 to_build = input_proto.image_types or [_BASE_ID]
Alex Klein56355682019-02-07 10:36:54 -070089
Alex Klein21b95022019-05-09 14:14:46 -060090 image_types, vm_types = _ParseImagesToCreate(to_build)
91 build_config = _ParseCreateBuildConfig(input_proto)
Alex Klein56355682019-02-07 10:36:54 -070092
93 # Sorted isn't really necessary here, but it's much easier to test.
Alex Klein1bcd9882019-03-19 13:25:24 -060094 result = image.Build(board=board, images=sorted(list(image_types)),
95 config=build_config)
Alex Klein56355682019-02-07 10:36:54 -070096
Alex Klein1bcd9882019-03-19 13:25:24 -060097 output_proto.success = result.success
Will Bradley29a49c22019-10-21 11:50:08 -060098
Alex Klein1bcd9882019-03-19 13:25:24 -060099 if result.success:
100 # Success -- we need to list out the images we built in the output.
101 _PopulateBuiltImages(board, image_types, output_proto)
Will Bradley29a49c22019-10-21 11:50:08 -0600102
103 if vm_types:
Trent Begin008cade2019-10-31 13:40:59 -0600104 for vm_type in vm_types:
105 is_test = vm_type in [_TEST_VM_ID, _TEST_GUEST_VM_ID]
106 try:
107 if vm_type in [_BASE_GUEST_VM_ID, _TEST_GUEST_VM_ID]:
108 vm_path = image.CreateGuestVm(board, is_test=is_test)
109 else:
110 vm_path = image.CreateVm(board, is_test=is_test)
111 except image.ImageToVmError as e:
112 cros_build_lib.Die(e)
Will Bradley29a49c22019-10-21 11:50:08 -0600113
Trent Begin008cade2019-10-31 13:40:59 -0600114 new_image = output_proto.images.add()
115 new_image.path = vm_path
116 new_image.type = vm_type
117 new_image.build_target.name = board
Will Bradley29a49c22019-10-21 11:50:08 -0600118
119 # Read metric events log and pipe them into output_proto.events.
120 deserialize_metrics_log(output_proto.events, prefix=board)
121 return controller.RETURN_CODE_SUCCESS
122
Alex Klein1bcd9882019-03-19 13:25:24 -0600123 else:
Alex Klein2557b4f2019-07-11 14:34:00 -0600124 # Failure, include all of the failed packages in the output when available.
125 if not result.failed_packages:
126 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
127
Alex Klein1bcd9882019-03-19 13:25:24 -0600128 for package in result.failed_packages:
129 current = output_proto.failed_packages.add()
130 current.category = package.category
131 current.package_name = package.package
132 if package.version:
133 current.version = package.version
134
Alex Klein8cb365a2019-05-15 16:24:53 -0600135 return controller.RETURN_CODE_UNSUCCESSFUL_RESPONSE_AVAILABLE
Alex Klein1bcd9882019-03-19 13:25:24 -0600136
Alex Klein21b95022019-05-09 14:14:46 -0600137
138def _ParseImagesToCreate(to_build):
139 """Helper function to parse the image types to build.
140
141 This function exists just to clean up the Create function.
142
143 Args:
144 to_build (list[int]): The image type list.
145
146 Returns:
147 (set, set): The image and vm types, respectively, that need to be built.
148 """
149 image_types = set()
150 vm_types = set()
151 for current in to_build:
152 if current in _IMAGE_MAPPING:
153 image_types.add(_IMAGE_MAPPING[current])
154 elif current in _VM_IMAGE_MAPPING:
155 vm_types.add(current)
156 # Make sure we build the image required to build the VM.
157 image_types.add(_VM_IMAGE_MAPPING[current])
158 else:
159 # Not expected, but at least it will be obvious if this comes up.
160 cros_build_lib.Die(
161 "The service's known image types do not match those in image.proto. "
162 'Unknown Enum ID: %s' % current)
163
Trent Begin008cade2019-10-31 13:40:59 -0600164 # We can only build one type of these images at a time since image_to_vm.sh
165 # uses the default path if a name is not provided.
166 if vm_types.issuperset({_BASE_VM_ID, _TEST_VM_ID}):
Alex Klein21b95022019-05-09 14:14:46 -0600167 cros_build_lib.Die('Cannot create more than one VM.')
168
169 return image_types, vm_types
170
171
172def _ParseCreateBuildConfig(input_proto):
173 """Helper to parse the image build config for Create."""
174 enable_rootfs_verification = not input_proto.disable_rootfs_verification
175 version = input_proto.version or None
176 disk_layout = input_proto.disk_layout or None
177 builder_path = input_proto.builder_path or None
178 return image.BuildConfig(
179 enable_rootfs_verification=enable_rootfs_verification, replace=True,
180 version=version, disk_layout=disk_layout, builder_path=builder_path,
181 )
182
Alex Klein1bcd9882019-03-19 13:25:24 -0600183
184def _PopulateBuiltImages(board, image_types, output_proto):
185 """Helper to list out built images for Create."""
Alex Klein56355682019-02-07 10:36:54 -0700186 # Build out the ImageType->ImagePath mapping in the output.
187 # We're using the default path, so just fetch that, but read the symlink so
188 # the path we're returning is somewhat more permanent.
189 latest_link = image_lib.GetLatestImageLink(board)
Alex Klein4f0eb432019-05-02 13:56:04 -0600190 base_path = os.path.realpath(latest_link)
Alex Klein56355682019-02-07 10:36:54 -0700191
192 for current in image_types:
193 type_id = _IMAGE_MAPPING[current]
194 path = os.path.join(base_path, constants.IMAGE_TYPE_TO_NAME[current])
195
196 new_image = output_proto.images.add()
197 new_image.path = path
198 new_image.type = type_id
Alex Klein4f0eb432019-05-02 13:56:04 -0600199 new_image.build_target.name = board
200
201
Michael Mortensen10146cf2019-11-19 19:59:22 -0700202def _SignerTestResponse(_input_proto, output_proto, _config):
203 """Set output_proto success field on a successful SignerTest response."""
204 output_proto.success = True
205 return controller.RETURN_CODE_SUCCESS
206
207
208@faux.success(_SignerTestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700209@faux.empty_completed_unsuccessfully_error
Michael Mortensenc83c9952019-08-05 12:15:12 -0600210@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600211@validate.validation_complete
212def SignerTest(input_proto, output_proto, _config):
Michael Mortensenc83c9952019-08-05 12:15:12 -0600213 """Run image tests.
214
215 Args:
216 input_proto (image_pb2.ImageTestRequest): The input message.
217 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600218 _config (api_config.ApiConfig): The API call config.
Michael Mortensenc83c9952019-08-05 12:15:12 -0600219 """
Michael Mortensenc83c9952019-08-05 12:15:12 -0600220 image_path = input_proto.image.path
221
Alex Klein231d2da2019-07-22 16:44:45 -0600222 result = image_lib.SecurityTest(image=image_path)
Michael Mortensenc83c9952019-08-05 12:15:12 -0600223 output_proto.success = result
224 if result:
225 return controller.RETURN_CODE_SUCCESS
226 else:
227 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY
228
Alex Klein076841b2019-08-29 15:19:39 -0600229
Michael Mortensen10146cf2019-11-19 19:59:22 -0700230def _TestResponse(_input_proto, output_proto, _config):
231 """Set output_proto success field on a successful Test response."""
232 output_proto.success = True
233 return controller.RETURN_CODE_SUCCESS
234
235
236@faux.success(_TestResponse)
Michael Mortensen85d38402019-12-12 09:50:29 -0700237@faux.empty_completed_unsuccessfully_error
Alex Klein2b236722019-06-19 15:44:26 -0600238@validate.require('build_target.name', 'result.directory')
239@validate.exists('image.path')
Alex Klein231d2da2019-07-22 16:44:45 -0600240def Test(input_proto, output_proto, config):
Alex Klein2966e302019-01-17 13:29:38 -0700241 """Run image tests.
242
243 Args:
244 input_proto (image_pb2.ImageTestRequest): The input message.
245 output_proto (image_pb2.ImageTestResult): The output message.
Alex Klein231d2da2019-07-22 16:44:45 -0600246 config (api_config.ApiConfig): The API call config.
Alex Klein2966e302019-01-17 13:29:38 -0700247 """
248 image_path = input_proto.image.path
249 board = input_proto.build_target.name
250 result_directory = input_proto.result.directory
251
Alex Klein2966e302019-01-17 13:29:38 -0700252 if not os.path.isfile(image_path) or not image_path.endswith('.bin'):
Alex Klein4f0eb432019-05-02 13:56:04 -0600253 cros_build_lib.Die(
Alex Klein2966e302019-01-17 13:29:38 -0700254 'The image.path must be an existing image file with a .bin extension.')
255
Alex Klein231d2da2019-07-22 16:44:45 -0600256 if config.validate_only:
257 return controller.RETURN_CODE_VALID_INPUT
258
Alex Klein8cb365a2019-05-15 16:24:53 -0600259 success = image.Test(board, result_directory, image_dir=image_path)
260 output_proto.success = success
261
262 if success:
263 return controller.RETURN_CODE_SUCCESS
264 else:
265 return controller.RETURN_CODE_COMPLETED_UNSUCCESSFULLY