blob: a556f5380d45b46f347768b33cad17fbce6c36f1 [file] [log] [blame]
Yifan Honge3ba82c2019-08-21 13:29:30 -07001#!/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 VINTF compatibility from a target files package.
19
20Usage: check_target_files_vintf target_files
21
22target_files can be a ZIP file or an extracted target files directory.
23"""
24
25import logging
26import subprocess
27import sys
28import os
29import zipfile
30
31import common
32
33logger = logging.getLogger(__name__)
34
35OPTIONS = common.OPTIONS
36
37# Keys are paths that VINTF searches. Must keep in sync with libvintf's search
38# paths (VintfObject.cpp).
39# These paths are stored in different directories in target files package, so
40# we have to search for the correct path and tell checkvintf to remap them.
Yifan Hong2870d1e2019-12-19 13:58:00 -080041# Look for TARGET_COPY_OUT_* variables in board_config.mk for possible paths for
42# each partition.
Yifan Honge3ba82c2019-08-21 13:29:30 -070043DIR_SEARCH_PATHS = {
44 '/system': ('SYSTEM',),
45 '/vendor': ('VENDOR', 'SYSTEM/vendor'),
46 '/product': ('PRODUCT', 'SYSTEM/product'),
Yifan Hong2870d1e2019-12-19 13:58:00 -080047 '/odm': ('ODM', 'VENDOR/odm', 'SYSTEM/vendor/odm'),
Yifan Honge3ba82c2019-08-21 13:29:30 -070048}
49
50UNZIP_PATTERN = ['META/*', '*/build.prop']
51
52
53def GetDirmap(input_tmp):
54 dirmap = {}
55 for device_path, target_files_rel_paths in DIR_SEARCH_PATHS.items():
56 for target_files_rel_path in target_files_rel_paths:
57 target_files_path = os.path.join(input_tmp, target_files_rel_path)
58 if os.path.isdir(target_files_path):
59 dirmap[device_path] = target_files_path
60 break
61 if device_path not in dirmap:
62 raise ValueError("Can't determine path for device path " + device_path +
63 ". Searched the following:" +
64 ("\n".join(target_files_rel_paths)))
65 return dirmap
66
67
68def GetArgsForSkus(info_dict):
69 skus = info_dict.get('vintf_odm_manifest_skus', '').strip().split()
70 if not skus:
71 logger.info("ODM_MANIFEST_SKUS is not defined. Check once without SKUs.")
72 skus = ['']
73 return [['--property', 'ro.boot.product.hardware.sku=' + sku]
74 for sku in skus]
75
76
77def GetArgsForShippingApiLevel(info_dict):
78 shipping_api_level = info_dict['vendor.build.prop'].get(
79 'ro.product.first_api_level')
80 if not shipping_api_level:
81 logger.warning('Cannot determine ro.product.first_api_level')
82 return []
83 return ['--property', 'ro.product.first_api_level=' + shipping_api_level]
84
85
86def GetArgsForKernel(input_tmp):
87 version_path = os.path.join(input_tmp, 'META/kernel_version.txt')
88 config_path = os.path.join(input_tmp, 'META/kernel_configs.txt')
89
90 if not os.path.isfile(version_path) or not os.path.isfile(config_path):
91 logger.info('Skipping kernel config checks because ' +
92 'PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS is not set')
93 return []
94
95 with open(version_path) as f:
96 version = f.read().strip()
97
98 return ['--kernel', '{}:{}'.format(version, config_path)]
99
100
101def CheckVintfFromExtractedTargetFiles(input_tmp, info_dict=None):
102 """
103 Checks VINTF metadata of an extracted target files directory.
104
105 Args:
106 inp: path to the directory that contains the extracted target files archive.
107 info_dict: The build-time info dict. If None, it will be loaded from inp.
108
109 Returns:
110 True if VINTF check is skipped or compatible, False if incompatible. Raise
111 a RuntimeError if any error occurs.
112 """
113
114 if info_dict is None:
115 info_dict = common.LoadInfoDict(input_tmp)
116
117 if info_dict.get('vintf_enforce') != 'true':
118 logger.warning('PRODUCT_ENFORCE_VINTF_MANIFEST is not set, skipping checks')
119 return True
120
121 dirmap = GetDirmap(input_tmp)
122 args_for_skus = GetArgsForSkus(info_dict)
123 shipping_api_level_args = GetArgsForShippingApiLevel(info_dict)
124 kernel_args = GetArgsForKernel(input_tmp)
125
126 common_command = [
127 'checkvintf',
128 '--check-compat',
129 ]
130 for device_path, real_path in dirmap.items():
131 common_command += ['--dirmap', '{}:{}'.format(device_path, real_path)]
132 common_command += kernel_args
133 common_command += shipping_api_level_args
134
135 success = True
136 for sku_args in args_for_skus:
137 command = common_command + sku_args
138 proc = common.Run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
139 out, err = proc.communicate()
140 if proc.returncode == 0:
141 logger.info("Command `%s` returns 'compatible'", ' '.join(command))
142 elif out.strip() == "INCOMPATIBLE":
143 logger.info("Command `%s` returns 'incompatible'", ' '.join(command))
144 success = False
145 else:
146 raise common.ExternalError(
147 "Failed to run command '{}' (exit code {}):\nstdout:{}\nstderr:{}"
148 .format(' '.join(command), proc.returncode, out, err))
149 logger.info("stdout: %s", out)
150 logger.info("stderr: %s", err)
151
152 return success
153
154
155def GetVintfFileList():
156 """
157 Returns a list of VINTF metadata files that should be read from a target files
158 package before executing checkvintf.
159 """
160 def PathToPatterns(path):
161 if path[-1] == '/':
162 path += '*'
163 for device_path, target_files_rel_paths in DIR_SEARCH_PATHS.items():
164 if path.startswith(device_path):
165 suffix = path[len(device_path):]
166 return [rel_path + suffix for rel_path in target_files_rel_paths]
167 raise RuntimeError('Unrecognized path from checkvintf --dump-file-list: ' +
168 path)
169
170 out = common.RunAndCheckOutput(['checkvintf', '--dump-file-list'])
171 paths = out.strip().split('\n')
172 paths = sum((PathToPatterns(path) for path in paths if path), [])
173 return paths
174
175
176def CheckVintfFromTargetFiles(inp, info_dict=None):
177 """
178 Checks VINTF metadata of a target files zip.
179
180 Args:
181 inp: path to the target files archive.
182 info_dict: The build-time info dict. If None, it will be loaded from inp.
183
184 Returns:
185 True if VINTF check is skipped or compatible, False if incompatible. Raise
186 a RuntimeError if any error occurs.
187 """
188 input_tmp = common.UnzipTemp(inp, GetVintfFileList() + UNZIP_PATTERN)
189 return CheckVintfFromExtractedTargetFiles(input_tmp, info_dict)
190
191
192def CheckVintf(inp, info_dict=None):
193 """
194 Checks VINTF metadata of a target files zip or extracted target files
195 directory.
196
197 Args:
198 inp: path to the (possibly extracted) target files archive.
199 info_dict: The build-time info dict. If None, it will be loaded from inp.
200
201 Returns:
202 True if VINTF check is skipped or compatible, False if incompatible. Raise
203 a RuntimeError if any error occurs.
204 """
205 if os.path.isdir(inp):
206 logger.info('Checking VINTF compatibility extracted target files...')
207 return CheckVintfFromExtractedTargetFiles(inp, info_dict)
208
209 if zipfile.is_zipfile(inp):
210 logger.info('Checking VINTF compatibility target files...')
211 return CheckVintfFromTargetFiles(inp, info_dict)
212
213 raise ValueError('{} is not a valid directory or zip file'.format(inp))
214
215
216def main(argv):
217 args = common.ParseOptions(argv, __doc__)
218 if len(args) != 1:
219 common.Usage(__doc__)
220 sys.exit(1)
221 common.InitLogging()
222 if not CheckVintf(args[0]):
223 sys.exit(1)
224
225
226if __name__ == '__main__':
227 try:
228 common.CloseInheritedPipes()
229 main(sys.argv[1:])
230 except common.ExternalError:
231 logger.exception('\n ERROR:\n')
232 sys.exit(1)
233 finally:
234 common.Cleanup()