blob: 4616753797b05165111301e949072cc179af9078 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Development tool - sdk-update command plugin
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05002#
3# Copyright (C) 2015-2016 Intel Corporation
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License version 2 as
7# published by the Free Software Foundation.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License along
15# with this program; if not, write to the Free Software Foundation, Inc.,
16# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Patrick Williamsc124f4f2015-09-15 14:41:29 -050017
18import os
19import subprocess
20import logging
21import glob
22import shutil
23import errno
24import sys
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050025import tempfile
26import re
27from devtool import exec_build_env_command, setup_tinfoil, parse_recipe, DevtoolError
Patrick Williamsc124f4f2015-09-15 14:41:29 -050028
29logger = logging.getLogger('devtool')
30
Patrick Williamsc124f4f2015-09-15 14:41:29 -050031def parse_locked_sigs(sigfile_path):
32 """Return <pn:task>:<hash> dictionary"""
33 sig_dict = {}
34 with open(sigfile_path) as f:
35 lines = f.readlines()
36 for line in lines:
37 if ':' in line:
38 taskkey, _, hashval = line.rpartition(':')
39 sig_dict[taskkey.strip()] = hashval.split()[0]
40 return sig_dict
41
42def generate_update_dict(sigfile_new, sigfile_old):
43 """Return a dict containing <pn:task>:<hash> which indicates what need to be updated"""
44 update_dict = {}
45 sigdict_new = parse_locked_sigs(sigfile_new)
46 sigdict_old = parse_locked_sigs(sigfile_old)
47 for k in sigdict_new:
48 if k not in sigdict_old:
49 update_dict[k] = sigdict_new[k]
50 continue
51 if sigdict_new[k] != sigdict_old[k]:
52 update_dict[k] = sigdict_new[k]
53 continue
54 return update_dict
55
Patrick Williamsf1e5d692016-03-30 15:21:19 -050056def get_sstate_objects(update_dict, sstate_dir):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050057 """Return a list containing sstate objects which are to be installed"""
58 sstate_objects = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -050059 for k in update_dict:
60 files = set()
61 hashval = update_dict[k]
62 p = sstate_dir + '/' + hashval[:2] + '/*' + hashval + '*.tgz'
63 files |= set(glob.glob(p))
64 p = sstate_dir + '/*/' + hashval[:2] + '/*' + hashval + '*.tgz'
65 files |= set(glob.glob(p))
66 files = list(files)
67 if len(files) == 1:
68 sstate_objects.extend(files)
69 elif len(files) > 1:
70 logger.error("More than one matching sstate object found for %s" % hashval)
71
72 return sstate_objects
73
74def mkdir(d):
75 try:
76 os.makedirs(d)
77 except OSError as e:
78 if e.errno != errno.EEXIST:
79 raise e
80
81def install_sstate_objects(sstate_objects, src_sdk, dest_sdk):
82 """Install sstate objects into destination SDK"""
83 sstate_dir = os.path.join(dest_sdk, 'sstate-cache')
84 if not os.path.exists(sstate_dir):
85 logger.error("Missing sstate-cache directory in %s, it might not be an extensible SDK." % dest_sdk)
86 raise
87 for sb in sstate_objects:
88 dst = sb.replace(src_sdk, dest_sdk)
89 destdir = os.path.dirname(dst)
90 mkdir(destdir)
91 logger.debug("Copying %s to %s" % (sb, dst))
92 shutil.copy(sb, dst)
93
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050094def check_manifest(fn, basepath):
95 import bb.utils
96 changedfiles = []
97 with open(fn, 'r') as f:
98 for line in f:
99 splitline = line.split()
100 if len(splitline) > 1:
101 chksum = splitline[0]
102 fpath = splitline[1]
103 curr_chksum = bb.utils.sha256_file(os.path.join(basepath, fpath))
104 if chksum != curr_chksum:
105 logger.debug('File %s changed: old csum = %s, new = %s' % (os.path.join(basepath, fpath), curr_chksum, chksum))
106 changedfiles.append(fpath)
107 return changedfiles
108
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500109def sdk_update(args, config, basepath, workspace):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600110 """Entry point for devtool sdk-update command"""
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500111 updateserver = args.updateserver
112 if not updateserver:
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500113 updateserver = config.get('SDK', 'updateserver', '')
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500114 logger.debug("updateserver: %s" % updateserver)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500115
116 # Make sure we are using sdk-update from within SDK
117 logger.debug("basepath = %s" % basepath)
118 old_locked_sig_file_path = os.path.join(basepath, 'conf/locked-sigs.inc')
119 if not os.path.exists(old_locked_sig_file_path):
120 logger.error("Not using devtool's sdk-update command from within an extensible SDK. Please specify correct basepath via --basepath option")
121 return -1
122 else:
123 logger.debug("Found conf/locked-sigs.inc in %s" % basepath)
124
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600125 if not '://' in updateserver:
126 logger.error("Update server must be a URL")
127 return -1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500128
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500129 layers_dir = os.path.join(basepath, 'layers')
130 conf_dir = os.path.join(basepath, 'conf')
131
132 # Grab variable values
133 tinfoil = setup_tinfoil(config_only=True, basepath=basepath)
134 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500135 stamps_dir = tinfoil.config_data.getVar('STAMPS_DIR')
136 sstate_mirrors = tinfoil.config_data.getVar('SSTATE_MIRRORS')
137 site_conf_version = tinfoil.config_data.getVar('SITE_CONF_VERSION')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500138 finally:
139 tinfoil.shutdown()
140
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600141 tmpsdk_dir = tempfile.mkdtemp()
142 try:
143 os.makedirs(os.path.join(tmpsdk_dir, 'conf'))
144 new_locked_sig_file_path = os.path.join(tmpsdk_dir, 'conf', 'locked-sigs.inc')
145 # Fetch manifest from server
146 tmpmanifest = os.path.join(tmpsdk_dir, 'conf', 'sdk-conf-manifest')
147 ret = subprocess.call("wget -q -O %s %s/conf/sdk-conf-manifest" % (tmpmanifest, updateserver), shell=True)
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700148 if ret != 0:
149 logger.error("Cannot dowload files from %s" % updateserver)
150 return ret
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600151 changedfiles = check_manifest(tmpmanifest, basepath)
152 if not changedfiles:
153 logger.info("Already up-to-date")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500154 return 0
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600155 # Update metadata
156 logger.debug("Updating metadata via git ...")
157 #Check for the status before doing a fetch and reset
158 if os.path.exists(os.path.join(basepath, 'layers/.git')):
159 out = subprocess.check_output("git status --porcelain", shell=True, cwd=layers_dir)
160 if not out:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500161 ret = subprocess.call("git fetch --all; git reset --hard @{u}", shell=True, cwd=layers_dir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500162 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600163 logger.error("Failed to update metadata as there have been changes made to it. Aborting.");
164 logger.error("Changed files:\n%s" % out);
165 return -1
166 else:
167 ret = -1
168 if ret != 0:
169 ret = subprocess.call("git clone %s/layers/.git" % updateserver, shell=True, cwd=tmpsdk_dir)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500170 if ret != 0:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600171 logger.error("Updating metadata via git failed")
172 return ret
173 logger.debug("Updating conf files ...")
174 for changedfile in changedfiles:
175 ret = subprocess.call("wget -q -O %s %s/%s" % (changedfile, updateserver, changedfile), shell=True, cwd=tmpsdk_dir)
176 if ret != 0:
177 logger.error("Updating %s failed" % changedfile)
178 return ret
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500179
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600180 # Check if UNINATIVE_CHECKSUM changed
181 uninative = False
182 if 'conf/local.conf' in changedfiles:
183 def read_uninative_checksums(fn):
184 chksumitems = []
185 with open(fn, 'r') as f:
186 for line in f:
187 if line.startswith('UNINATIVE_CHECKSUM'):
188 splitline = re.split(r'[\[\]"\']', line)
189 if len(splitline) > 3:
190 chksumitems.append((splitline[1], splitline[3]))
191 return chksumitems
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500192
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600193 oldsums = read_uninative_checksums(os.path.join(basepath, 'conf/local.conf'))
194 newsums = read_uninative_checksums(os.path.join(tmpsdk_dir, 'conf/local.conf'))
195 if oldsums != newsums:
196 uninative = True
197 for buildarch, chksum in newsums:
198 uninative_file = os.path.join('downloads', 'uninative', chksum, '%s-nativesdk-libc.tar.bz2' % buildarch)
199 mkdir(os.path.join(tmpsdk_dir, os.path.dirname(uninative_file)))
200 ret = subprocess.call("wget -q -O %s %s/%s" % (uninative_file, updateserver, uninative_file), shell=True, cwd=tmpsdk_dir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500201
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600202 # Ok, all is well at this point - move everything over
203 tmplayers_dir = os.path.join(tmpsdk_dir, 'layers')
204 if os.path.exists(tmplayers_dir):
205 shutil.rmtree(layers_dir)
206 shutil.move(tmplayers_dir, layers_dir)
207 for changedfile in changedfiles:
208 destfile = os.path.join(basepath, changedfile)
209 os.remove(destfile)
210 shutil.move(os.path.join(tmpsdk_dir, changedfile), destfile)
211 os.remove(os.path.join(conf_dir, 'sdk-conf-manifest'))
212 shutil.move(tmpmanifest, conf_dir)
213 if uninative:
214 shutil.rmtree(os.path.join(basepath, 'downloads', 'uninative'))
215 shutil.move(os.path.join(tmpsdk_dir, 'downloads', 'uninative'), os.path.join(basepath, 'downloads'))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500216
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600217 if not sstate_mirrors:
218 with open(os.path.join(conf_dir, 'site.conf'), 'a') as f:
219 f.write('SCONF_VERSION = "%s"\n' % site_conf_version)
220 f.write('SSTATE_MIRRORS_append = " file://.* %s/sstate-cache/PATH \\n "\n' % updateserver)
221 finally:
222 shutil.rmtree(tmpsdk_dir)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500223
224 if not args.skip_prepare:
225 # Find all potentially updateable tasks
226 sdk_update_targets = []
227 tasks = ['do_populate_sysroot', 'do_packagedata']
228 for root, _, files in os.walk(stamps_dir):
229 for fn in files:
230 if not '.sigdata.' in fn:
231 for task in tasks:
232 if '.%s.' % task in fn or '.%s_setscene.' % task in fn:
233 sdk_update_targets.append('%s:%s' % (os.path.basename(root), task))
234 # Run bitbake command for the whole SDK
235 logger.info("Preparing build system... (This may take some time.)")
236 try:
237 exec_build_env_command(config.init_path, basepath, 'bitbake --setscene-only %s' % ' '.join(sdk_update_targets), stderr=subprocess.STDOUT)
238 output, _ = exec_build_env_command(config.init_path, basepath, 'bitbake -n %s' % ' '.join(sdk_update_targets), stderr=subprocess.STDOUT)
239 runlines = []
240 for line in output.splitlines():
241 if 'Running task ' in line:
242 runlines.append(line)
243 if runlines:
244 logger.error('Unexecuted tasks found in preparation log:\n %s' % '\n '.join(runlines))
245 return -1
246 except bb.process.ExecutionError as e:
247 logger.error('Preparation failed:\n%s' % e.stdout)
248 return -1
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500249 return 0
250
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500251def sdk_install(args, config, basepath, workspace):
252 """Entry point for the devtool sdk-install command"""
253
254 import oe.recipeutils
255 import bb.process
256
257 for recipe in args.recipename:
258 if recipe in workspace:
259 raise DevtoolError('recipe %s is a recipe in your workspace' % recipe)
260
261 tasks = ['do_populate_sysroot', 'do_packagedata']
262 stampprefixes = {}
263 def checkstamp(recipe):
264 stampprefix = stampprefixes[recipe]
265 stamps = glob.glob(stampprefix + '*')
266 for stamp in stamps:
267 if '.sigdata.' not in stamp and stamp.startswith((stampprefix + '.', stampprefix + '_setscene.')):
268 return True
269 else:
270 return False
271
272 install_recipes = []
273 tinfoil = setup_tinfoil(config_only=False, basepath=basepath)
274 try:
275 for recipe in args.recipename:
276 rd = parse_recipe(config, tinfoil, recipe, True)
277 if not rd:
278 return 1
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500279 stampprefixes[recipe] = '%s.%s' % (rd.getVar('STAMP'), tasks[0])
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500280 if checkstamp(recipe):
281 logger.info('%s is already installed' % recipe)
282 else:
283 install_recipes.append(recipe)
284 finally:
285 tinfoil.shutdown()
286
287 if install_recipes:
288 logger.info('Installing %s...' % ', '.join(install_recipes))
289 install_tasks = []
290 for recipe in install_recipes:
291 for task in tasks:
292 if recipe.endswith('-native') and 'package' in task:
293 continue
294 install_tasks.append('%s:%s' % (recipe, task))
295 options = ''
296 if not args.allow_build:
297 options += ' --setscene-only'
298 try:
299 exec_build_env_command(config.init_path, basepath, 'bitbake %s %s' % (options, ' '.join(install_tasks)), watch=True)
300 except bb.process.ExecutionError as e:
301 raise DevtoolError('Failed to install %s:\n%s' % (recipe, str(e)))
302 failed = False
303 for recipe in install_recipes:
304 if checkstamp(recipe):
305 logger.info('Successfully installed %s' % recipe)
306 else:
307 raise DevtoolError('Failed to install %s - unavailable' % recipe)
308 failed = True
309 if failed:
310 return 2
311
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500312 try:
313 exec_build_env_command(config.init_path, basepath, 'bitbake build-sysroots', watch=True)
314 except bb.process.ExecutionError as e:
315 raise DevtoolError('Failed to bitbake build-sysroots:\n%s' % (str(e)))
316
317
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500318def register_commands(subparsers, context):
319 """Register devtool subcommands from the sdk plugin"""
320 if context.fixed_setup:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500321 parser_sdk = subparsers.add_parser('sdk-update',
322 help='Update SDK components',
323 description='Updates installed SDK components from a remote server',
324 group='sdk')
325 updateserver = context.config.get('SDK', 'updateserver', '')
326 if updateserver:
327 parser_sdk.add_argument('updateserver', help='The update server to fetch latest SDK components from (default %s)' % updateserver, nargs='?')
328 else:
329 parser_sdk.add_argument('updateserver', help='The update server to fetch latest SDK components from')
330 parser_sdk.add_argument('--skip-prepare', action="store_true", help='Skip re-preparing the build system after updating (for debugging only)')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500331 parser_sdk.set_defaults(func=sdk_update)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500332
333 parser_sdk_install = subparsers.add_parser('sdk-install',
334 help='Install additional SDK components',
335 description='Installs additional recipe development files into the SDK. (You can use "devtool search" to find available recipes.)',
336 group='sdk')
337 parser_sdk_install.add_argument('recipename', help='Name of the recipe to install the development artifacts for', nargs='+')
338 parser_sdk_install.add_argument('-s', '--allow-build', help='Allow building requested item(s) from source', action='store_true')
339 parser_sdk_install.set_defaults(func=sdk_install)