blob: 04d832ced8d5ae6e53233e6813e79c762e8a01a9 [file] [log] [blame]
Yifan Hong3a7c2ef2019-11-01 18:23:19 +00001#!/usr/bin/env python
2#
3# Copyright (C) 2019 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Check dynamic partition sizes.
19
20usage: check_partition_sizes [info.txt]
21
22Check dump-super-partitions-info procedure for expected keys in info.txt. In
23addition, *_image (e.g. system_image, vendor_image, etc.) must be defined for
24each partition in dynamic_partition_list.
25
26Exit code is 0 if successful and non-zero if any failures.
27"""
28
29from __future__ import print_function
30
31import logging
32import sys
33
34import common
35import sparse_img
36
37if sys.hexversion < 0x02070000:
38 print("Python 2.7 or newer is required.", file=sys.stderr)
39 sys.exit(1)
40
41logger = logging.getLogger(__name__)
42
43class Expression(object):
44 def __init__(self, desc, expr, value=None):
45 # Human-readable description
46 self.desc = str(desc)
47 # Numeric expression
48 self.expr = str(expr)
49 # Value of expression
50 self.value = int(expr) if value is None else value
51
52 def CheckLe(self, other, level=logging.ERROR):
53 format_args = (self.desc, other.desc, self.expr, self.value,
54 other.expr, other.value)
55 if self.value <= other.value:
56 logger.info("%s is less than or equal to %s:\n%s == %d <= %s == %d",
57 *format_args)
58 else:
59 msg = "{} is greater than {}:\n{} == {} > {} == {}".format(*format_args)
60 if level == logging.ERROR:
61 raise RuntimeError(msg)
62 else:
63 logger.log(level, msg)
64
65 def CheckEq(self, other):
66 format_args = (self.desc, other.desc, self.expr, self.value,
67 other.expr, other.value)
68 if self.value == other.value:
69 logger.info("%s equals %s:\n%s == %d == %s == %d", *format_args)
70 else:
71 raise RuntimeError("{} does not equal {}:\n{} == {} != {} == {}".format(
72 *format_args))
73
74
75# A/B feature flags
76class DeviceType(object):
77 NONE = 0
78 AB = 1
79
80 @staticmethod
81 def Get(info_dict):
82 if info_dict.get("ab_update") != "true":
83 return DeviceType.NONE
84 return DeviceType.AB
85
86
87# Dynamic partition feature flags
88class Dap(object):
89 NONE = 0
90 RDAP = 1
91 DAP = 2
92
93 @staticmethod
94 def Get(info_dict):
95 if info_dict.get("use_dynamic_partitions") != "true":
96 return Dap.NONE
97 if info_dict.get("dynamic_partition_retrofit") == "true":
98 return Dap.RDAP
99 return Dap.DAP
100
101
102class DynamicPartitionSizeChecker(object):
103 def __init__(self, info_dict):
104 if "super_partition_size" in info_dict:
105 if "super_partition_warn_limit" not in info_dict:
106 info_dict["super_partition_warn_limit"] = \
107 int(info_dict["super_partition_size"]) * 95 // 100
108 if "super_partition_error_limit" not in info_dict:
109 info_dict["super_partition_error_limit"] = \
110 int(info_dict["super_partition_size"])
111 self.info_dict = info_dict
112
113
114 def _ReadSizeOfPartition(self, name):
115 # Tests uses *_image_size instead (to avoid creating empty sparse images
116 # on disk)
117 if name + "_image_size" in self.info_dict:
118 return int(self.info_dict[name + "_image_size"])
119 return sparse_img.GetImagePartitionSize(self.info_dict[name + "_image"])
120
121
122 # Round result to BOARD_SUPER_PARTITION_ALIGNMENT
123 def _RoundPartitionSize(self, size):
124 alignment = self.info_dict.get("super_partition_alignment")
125 if alignment is None:
126 return size
127 return (size + alignment - 1) // alignment * alignment
128
129
130 def _CheckSuperPartitionSize(self):
131 info_dict = self.info_dict
132 super_block_devices = \
133 info_dict.get("super_block_devices", "").strip().split()
134 size_list = [int(info_dict.get("super_{}_device_size".format(b), "0"))
135 for b in super_block_devices]
136 sum_size = Expression("sum of super partition block device sizes",
137 "+".join(str(size) for size in size_list),
138 sum(size_list))
139 super_partition_size = Expression("BOARD_SUPER_PARTITION_SIZE",
140 info_dict["super_partition_size"])
141 sum_size.CheckEq(super_partition_size)
142
143 def _CheckSumOfPartitionSizes(self, max_size, partition_names,
144 warn_size=None, error_size=None):
145 partition_size_list = [self._RoundPartitionSize(
146 self._ReadSizeOfPartition(p)) for p in partition_names]
147 sum_size = Expression("sum of sizes of {}".format(partition_names),
148 "+".join(str(size) for size in partition_size_list),
149 sum(partition_size_list))
150 sum_size.CheckLe(max_size)
151 if error_size:
152 sum_size.CheckLe(error_size)
153 if warn_size:
154 sum_size.CheckLe(warn_size, level=logging.WARNING)
155
156 def _NumDeviceTypesInSuper(self):
157 slot = DeviceType.Get(self.info_dict)
158 dap = Dap.Get(self.info_dict)
159
160 if dap == Dap.NONE:
161 raise RuntimeError("check_partition_sizes should only be executed on "
162 "builds with dynamic partitions enabled")
163
164 # Retrofit dynamic partitions: 1 slot per "super", 2 "super"s on the device
165 if dap == Dap.RDAP:
166 if slot != DeviceType.AB:
167 raise RuntimeError("Device with retrofit dynamic partitions must use "
168 "regular (non-Virtual) A/B")
169 return 1
170
171 # Launch DAP: 1 super on the device
172 assert dap == Dap.DAP
173
174 # DAP + A/B: 2 slots in super
175 if slot == DeviceType.AB:
176 return 2
177
178 # DAP + non-A/B: 1 slot in super
179 assert slot == DeviceType.NONE
180 return 1
181
182 def _CheckAllPartitionSizes(self):
183 info_dict = self.info_dict
184 num_slots = self._NumDeviceTypesInSuper()
185 size_limit_suffix = (" / %d" % num_slots) if num_slots > 1 else ""
186
187 # Check sum(all partitions) <= super partition (/ 2 for A/B devices launched
188 # with dynamic partitions)
189 if "super_partition_size" in info_dict and \
190 "dynamic_partition_list" in info_dict:
191 max_size = Expression(
192 "BOARD_SUPER_PARTITION_SIZE{}".format(size_limit_suffix),
193 int(info_dict["super_partition_size"]) // num_slots)
194 warn_limit = Expression(
195 "BOARD_SUPER_PARTITION_WARN_LIMIT{}".format(size_limit_suffix),
196 int(info_dict["super_partition_warn_limit"]) // num_slots)
197 error_limit = Expression(
198 "BOARD_SUPER_PARTITION_ERROR_LIMIT{}".format(size_limit_suffix),
199 int(info_dict["super_partition_error_limit"]) // num_slots)
200 self._CheckSumOfPartitionSizes(
201 max_size, info_dict["dynamic_partition_list"].strip().split(),
202 warn_limit, error_limit)
203
204 groups = info_dict.get("super_partition_groups", "").strip().split()
205
206 # For each group, check sum(partitions in group) <= group size
207 for group in groups:
208 if "super_{}_group_size".format(group) in info_dict and \
209 "super_{}_partition_list".format(group) in info_dict:
210 group_size = Expression(
211 "BOARD_{}_SIZE".format(group),
212 int(info_dict["super_{}_group_size".format(group)]))
213 self._CheckSumOfPartitionSizes(
214 group_size,
215 info_dict["super_{}_partition_list".format(group)].strip().split())
216
217 # Check sum(all group sizes) <= super partition (/ 2 for A/B devices
218 # launched with dynamic partitions)
219 if "super_partition_size" in info_dict:
220 group_size_list = [int(info_dict.get(
221 "super_{}_group_size".format(group), 0)) for group in groups]
222 sum_size = Expression("sum of sizes of {}".format(groups),
223 "+".join(str(size) for size in group_size_list),
224 sum(group_size_list))
225 max_size = Expression(
226 "BOARD_SUPER_PARTITION_SIZE{}".format(size_limit_suffix),
227 int(info_dict["super_partition_size"]) // num_slots)
228 sum_size.CheckLe(max_size)
229
230 def Run(self):
231 self._CheckAllPartitionSizes()
232 if self.info_dict.get("dynamic_partition_retrofit") == "true":
233 self._CheckSuperPartitionSize()
234
235
236def CheckPartitionSizes(inp):
237 if isinstance(inp, str):
238 info_dict = common.LoadDictionaryFromFile(inp)
239 return DynamicPartitionSizeChecker(info_dict).Run()
240 if isinstance(inp, dict):
241 return DynamicPartitionSizeChecker(inp).Run()
242 raise ValueError("{} is not a dictionary or a valid path".format(inp))
243
244
245def main(argv):
246 args = common.ParseOptions(argv, __doc__)
247 if len(args) != 1:
248 common.Usage(__doc__)
249 sys.exit(1)
250 common.InitLogging()
251 CheckPartitionSizes(args[0])
252
253
254if __name__ == "__main__":
255 try:
256 common.CloseInheritedPipes()
257 main(sys.argv[1:])
258 except common.ExternalError:
259 logger.exception("\n ERROR:\n")
260 sys.exit(1)
261 finally:
262 common.Cleanup()