append.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. # Recipe creation tool - append plugin
  2. #
  3. # Copyright (C) 2015 Intel Corporation
  4. #
  5. # SPDX-License-Identifier: GPL-2.0-only
  6. #
  7. import sys
  8. import os
  9. import argparse
  10. import glob
  11. import fnmatch
  12. import re
  13. import subprocess
  14. import logging
  15. import stat
  16. import shutil
  17. import scriptutils
  18. import errno
  19. from collections import defaultdict
  20. logger = logging.getLogger('recipetool')
  21. tinfoil = None
  22. def tinfoil_init(instance):
  23. global tinfoil
  24. tinfoil = instance
  25. # FIXME guessing when we don't have pkgdata?
  26. # FIXME mode to create patch rather than directly substitute
  27. class InvalidTargetFileError(Exception):
  28. pass
  29. def find_target_file(targetpath, d, pkglist=None):
  30. """Find the recipe installing the specified target path, optionally limited to a select list of packages"""
  31. import json
  32. pkgdata_dir = d.getVar('PKGDATA_DIR')
  33. # The mix between /etc and ${sysconfdir} here may look odd, but it is just
  34. # being consistent with usage elsewhere
  35. invalidtargets = {'${sysconfdir}/version': '${sysconfdir}/version is written out at image creation time',
  36. '/etc/timestamp': '/etc/timestamp is written out at image creation time',
  37. '/dev/*': '/dev is handled by udev (or equivalent) and the kernel (devtmpfs)',
  38. '/etc/passwd': '/etc/passwd should be managed through the useradd and extrausers classes',
  39. '/etc/group': '/etc/group should be managed through the useradd and extrausers classes',
  40. '/etc/shadow': '/etc/shadow should be managed through the useradd and extrausers classes',
  41. '/etc/gshadow': '/etc/gshadow should be managed through the useradd and extrausers classes',
  42. '${sysconfdir}/hostname': '${sysconfdir}/hostname contents should be set by setting hostname_pn-base-files = "value" in configuration',}
  43. for pthspec, message in invalidtargets.items():
  44. if fnmatch.fnmatchcase(targetpath, d.expand(pthspec)):
  45. raise InvalidTargetFileError(d.expand(message))
  46. targetpath_re = re.compile(r'\s+(\$D)?%s(\s|$)' % targetpath)
  47. recipes = defaultdict(list)
  48. for root, dirs, files in os.walk(os.path.join(pkgdata_dir, 'runtime')):
  49. if pkglist:
  50. filelist = pkglist
  51. else:
  52. filelist = files
  53. for fn in filelist:
  54. pkgdatafile = os.path.join(root, fn)
  55. if pkglist and not os.path.exists(pkgdatafile):
  56. continue
  57. with open(pkgdatafile, 'r') as f:
  58. pn = ''
  59. # This does assume that PN comes before other values, but that's a fairly safe assumption
  60. for line in f:
  61. if line.startswith('PN:'):
  62. pn = line.split(':', 1)[1].strip()
  63. elif line.startswith('FILES_INFO:'):
  64. val = line.split(':', 1)[1].strip()
  65. dictval = json.loads(val)
  66. for fullpth in dictval.keys():
  67. if fnmatch.fnmatchcase(fullpth, targetpath):
  68. recipes[targetpath].append(pn)
  69. elif line.startswith('pkg_preinst_') or line.startswith('pkg_postinst_'):
  70. scriptval = line.split(':', 1)[1].strip().encode('utf-8').decode('unicode_escape')
  71. if 'update-alternatives --install %s ' % targetpath in scriptval:
  72. recipes[targetpath].append('?%s' % pn)
  73. elif targetpath_re.search(scriptval):
  74. recipes[targetpath].append('!%s' % pn)
  75. return recipes
  76. def _parse_recipe(pn, tinfoil):
  77. try:
  78. rd = tinfoil.parse_recipe(pn)
  79. except bb.providers.NoProvider as e:
  80. logger.error(str(e))
  81. return None
  82. return rd
  83. def determine_file_source(targetpath, rd):
  84. """Assuming we know a file came from a specific recipe, figure out exactly where it came from"""
  85. import oe.recipeutils
  86. # See if it's in do_install for the recipe
  87. workdir = rd.getVar('WORKDIR')
  88. src_uri = rd.getVar('SRC_URI')
  89. srcfile = ''
  90. modpatches = []
  91. elements = check_do_install(rd, targetpath)
  92. if elements:
  93. logger.debug('do_install line:\n%s' % ' '.join(elements))
  94. srcpath = get_source_path(elements)
  95. logger.debug('source path: %s' % srcpath)
  96. if not srcpath.startswith('/'):
  97. # Handle non-absolute path
  98. srcpath = os.path.abspath(os.path.join(rd.getVarFlag('do_install', 'dirs').split()[-1], srcpath))
  99. if srcpath.startswith(workdir):
  100. # OK, now we have the source file name, look for it in SRC_URI
  101. workdirfile = os.path.relpath(srcpath, workdir)
  102. # FIXME this is where we ought to have some code in the fetcher, because this is naive
  103. for item in src_uri.split():
  104. localpath = bb.fetch2.localpath(item, rd)
  105. # Source path specified in do_install might be a glob
  106. if fnmatch.fnmatch(os.path.basename(localpath), workdirfile):
  107. srcfile = 'file://%s' % localpath
  108. elif '/' in workdirfile:
  109. if item == 'file://%s' % workdirfile:
  110. srcfile = 'file://%s' % localpath
  111. # Check patches
  112. srcpatches = []
  113. patchedfiles = oe.recipeutils.get_recipe_patched_files(rd)
  114. for patch, filelist in patchedfiles.items():
  115. for fileitem in filelist:
  116. if fileitem[0] == srcpath:
  117. srcpatches.append((patch, fileitem[1]))
  118. if srcpatches:
  119. addpatch = None
  120. for patch in srcpatches:
  121. if patch[1] == 'A':
  122. addpatch = patch[0]
  123. else:
  124. modpatches.append(patch[0])
  125. if addpatch:
  126. srcfile = 'patch://%s' % addpatch
  127. return (srcfile, elements, modpatches)
  128. def get_source_path(cmdelements):
  129. """Find the source path specified within a command"""
  130. command = cmdelements[0]
  131. if command in ['install', 'cp']:
  132. helptext = subprocess.check_output('LC_ALL=C %s --help' % command, shell=True).decode('utf-8')
  133. argopts = ''
  134. argopt_line_re = re.compile('^-([a-zA-Z0-9]), --[a-z-]+=')
  135. for line in helptext.splitlines():
  136. line = line.lstrip()
  137. res = argopt_line_re.search(line)
  138. if res:
  139. argopts += res.group(1)
  140. if not argopts:
  141. # Fallback
  142. if command == 'install':
  143. argopts = 'gmoSt'
  144. elif command == 'cp':
  145. argopts = 't'
  146. else:
  147. raise Exception('No fallback arguments for command %s' % command)
  148. skipnext = False
  149. for elem in cmdelements[1:-1]:
  150. if elem.startswith('-'):
  151. if len(elem) > 1 and elem[1] in argopts:
  152. skipnext = True
  153. continue
  154. if skipnext:
  155. skipnext = False
  156. continue
  157. return elem
  158. else:
  159. raise Exception('get_source_path: no handling for command "%s"')
  160. def get_func_deps(func, d):
  161. """Find the function dependencies of a shell function"""
  162. deps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func))
  163. deps |= set((d.getVarFlag(func, "vardeps") or "").split())
  164. funcdeps = []
  165. for dep in deps:
  166. if d.getVarFlag(dep, 'func'):
  167. funcdeps.append(dep)
  168. return funcdeps
  169. def check_do_install(rd, targetpath):
  170. """Look at do_install for a command that installs/copies the specified target path"""
  171. instpath = os.path.abspath(os.path.join(rd.getVar('D'), targetpath.lstrip('/')))
  172. do_install = rd.getVar('do_install')
  173. # Handle where do_install calls other functions (somewhat crudely, but good enough for this purpose)
  174. deps = get_func_deps('do_install', rd)
  175. for dep in deps:
  176. do_install = do_install.replace(dep, rd.getVar(dep))
  177. # Look backwards through do_install as we want to catch where a later line (perhaps
  178. # from a bbappend) is writing over the top
  179. for line in reversed(do_install.splitlines()):
  180. line = line.strip()
  181. if (line.startswith('install ') and ' -m' in line) or line.startswith('cp '):
  182. elements = line.split()
  183. destpath = os.path.abspath(elements[-1])
  184. if destpath == instpath:
  185. return elements
  186. elif destpath.rstrip('/') == os.path.dirname(instpath):
  187. # FIXME this doesn't take recursive copy into account; unsure if it's practical to do so
  188. srcpath = get_source_path(elements)
  189. if fnmatch.fnmatchcase(os.path.basename(instpath), os.path.basename(srcpath)):
  190. return elements
  191. return None
  192. def appendfile(args):
  193. import oe.recipeutils
  194. stdout = ''
  195. try:
  196. (stdout, _) = bb.process.run('LANG=C file -b %s' % args.newfile, shell=True)
  197. if 'cannot open' in stdout:
  198. raise bb.process.ExecutionError(stdout)
  199. except bb.process.ExecutionError as err:
  200. logger.debug('file command returned error: %s' % err)
  201. stdout = ''
  202. if stdout:
  203. logger.debug('file command output: %s' % stdout.rstrip())
  204. if ('executable' in stdout and not 'shell script' in stdout) or 'shared object' in stdout:
  205. logger.warning('This file looks like it is a binary or otherwise the output of compilation. If it is, you should consider building it properly instead of substituting a binary file directly.')
  206. if args.recipe:
  207. recipes = {args.targetpath: [args.recipe],}
  208. else:
  209. try:
  210. recipes = find_target_file(args.targetpath, tinfoil.config_data)
  211. except InvalidTargetFileError as e:
  212. logger.error('%s cannot be handled by this tool: %s' % (args.targetpath, e))
  213. return 1
  214. if not recipes:
  215. logger.error('Unable to find any package producing path %s - this may be because the recipe packaging it has not been built yet' % args.targetpath)
  216. return 1
  217. alternative_pns = []
  218. postinst_pns = []
  219. selectpn = None
  220. for targetpath, pnlist in recipes.items():
  221. for pn in pnlist:
  222. if pn.startswith('?'):
  223. alternative_pns.append(pn[1:])
  224. elif pn.startswith('!'):
  225. postinst_pns.append(pn[1:])
  226. elif selectpn:
  227. # hit here with multilibs
  228. continue
  229. else:
  230. selectpn = pn
  231. if not selectpn and len(alternative_pns) == 1:
  232. selectpn = alternative_pns[0]
  233. logger.error('File %s is an alternative possibly provided by recipe %s but seemingly no other, selecting it by default - you should double check other recipes' % (args.targetpath, selectpn))
  234. if selectpn:
  235. logger.debug('Selecting recipe %s for file %s' % (selectpn, args.targetpath))
  236. if postinst_pns:
  237. logger.warning('%s be modified by postinstall scripts for the following recipes:\n %s\nThis may or may not be an issue depending on what modifications these postinstall scripts make.' % (args.targetpath, '\n '.join(postinst_pns)))
  238. rd = _parse_recipe(selectpn, tinfoil)
  239. if not rd:
  240. # Error message already shown
  241. return 1
  242. sourcefile, instelements, modpatches = determine_file_source(args.targetpath, rd)
  243. sourcepath = None
  244. if sourcefile:
  245. sourcetype, sourcepath = sourcefile.split('://', 1)
  246. logger.debug('Original source file is %s (%s)' % (sourcepath, sourcetype))
  247. if sourcetype == 'patch':
  248. logger.warning('File %s is added by the patch %s - you may need to remove or replace this patch in order to replace the file.' % (args.targetpath, sourcepath))
  249. sourcepath = None
  250. else:
  251. logger.debug('Unable to determine source file, proceeding anyway')
  252. if modpatches:
  253. logger.warning('File %s is modified by the following patches:\n %s' % (args.targetpath, '\n '.join(modpatches)))
  254. if instelements and sourcepath:
  255. install = None
  256. else:
  257. # Auto-determine permissions
  258. # Check destination
  259. binpaths = '${bindir}:${sbindir}:${base_bindir}:${base_sbindir}:${libexecdir}:${sysconfdir}/init.d'
  260. perms = '0644'
  261. if os.path.abspath(os.path.dirname(args.targetpath)) in rd.expand(binpaths).split(':'):
  262. # File is going into a directory normally reserved for executables, so it should be executable
  263. perms = '0755'
  264. else:
  265. # Check source
  266. st = os.stat(args.newfile)
  267. if st.st_mode & stat.S_IXUSR:
  268. perms = '0755'
  269. install = {args.newfile: (args.targetpath, perms)}
  270. oe.recipeutils.bbappend_recipe(rd, args.destlayer, {args.newfile: sourcepath}, install, wildcardver=args.wildcard_version, machine=args.machine)
  271. return 0
  272. else:
  273. if alternative_pns:
  274. logger.error('File %s is an alternative possibly provided by the following recipes:\n %s\nPlease select recipe with -r/--recipe' % (targetpath, '\n '.join(alternative_pns)))
  275. elif postinst_pns:
  276. logger.error('File %s may be written out in a pre/postinstall script of the following recipes:\n %s\nPlease select recipe with -r/--recipe' % (targetpath, '\n '.join(postinst_pns)))
  277. return 3
  278. def appendsrc(args, files, rd, extralines=None):
  279. import oe.recipeutils
  280. srcdir = rd.getVar('S')
  281. workdir = rd.getVar('WORKDIR')
  282. import bb.fetch
  283. simplified = {}
  284. src_uri = rd.getVar('SRC_URI').split()
  285. for uri in src_uri:
  286. if uri.endswith(';'):
  287. uri = uri[:-1]
  288. simple_uri = bb.fetch.URI(uri)
  289. simple_uri.params = {}
  290. simplified[str(simple_uri)] = uri
  291. copyfiles = {}
  292. extralines = extralines or []
  293. for newfile, srcfile in files.items():
  294. src_destdir = os.path.dirname(srcfile)
  295. if not args.use_workdir:
  296. if rd.getVar('S') == rd.getVar('STAGING_KERNEL_DIR'):
  297. srcdir = os.path.join(workdir, 'git')
  298. if not bb.data.inherits_class('kernel-yocto', rd):
  299. logger.warning('S == STAGING_KERNEL_DIR and non-kernel-yocto, unable to determine path to srcdir, defaulting to ${WORKDIR}/git')
  300. src_destdir = os.path.join(os.path.relpath(srcdir, workdir), src_destdir)
  301. src_destdir = os.path.normpath(src_destdir)
  302. source_uri = 'file://{0}'.format(os.path.basename(srcfile))
  303. if src_destdir and src_destdir != '.':
  304. source_uri += ';subdir={0}'.format(src_destdir)
  305. simple = bb.fetch.URI(source_uri)
  306. simple.params = {}
  307. simple_str = str(simple)
  308. if simple_str in simplified:
  309. existing = simplified[simple_str]
  310. if source_uri != existing:
  311. logger.warning('{0!r} is already in SRC_URI, with different parameters: {1!r}, not adding'.format(source_uri, existing))
  312. else:
  313. logger.warning('{0!r} is already in SRC_URI, not adding'.format(source_uri))
  314. else:
  315. extralines.append('SRC_URI += {0}'.format(source_uri))
  316. copyfiles[newfile] = srcfile
  317. oe.recipeutils.bbappend_recipe(rd, args.destlayer, copyfiles, None, wildcardver=args.wildcard_version, machine=args.machine, extralines=extralines)
  318. def appendsrcfiles(parser, args):
  319. recipedata = _parse_recipe(args.recipe, tinfoil)
  320. if not recipedata:
  321. parser.error('RECIPE must be a valid recipe name')
  322. files = dict((f, os.path.join(args.destdir, os.path.basename(f)))
  323. for f in args.files)
  324. return appendsrc(args, files, recipedata)
  325. def appendsrcfile(parser, args):
  326. recipedata = _parse_recipe(args.recipe, tinfoil)
  327. if not recipedata:
  328. parser.error('RECIPE must be a valid recipe name')
  329. if not args.destfile:
  330. args.destfile = os.path.basename(args.file)
  331. elif args.destfile.endswith('/'):
  332. args.destfile = os.path.join(args.destfile, os.path.basename(args.file))
  333. return appendsrc(args, {args.file: args.destfile}, recipedata)
  334. def layer(layerpath):
  335. if not os.path.exists(os.path.join(layerpath, 'conf', 'layer.conf')):
  336. raise argparse.ArgumentTypeError('{0!r} must be a path to a valid layer'.format(layerpath))
  337. return layerpath
  338. def existing_path(filepath):
  339. if not os.path.exists(filepath):
  340. raise argparse.ArgumentTypeError('{0!r} must be an existing path'.format(filepath))
  341. return filepath
  342. def existing_file(filepath):
  343. filepath = existing_path(filepath)
  344. if os.path.isdir(filepath):
  345. raise argparse.ArgumentTypeError('{0!r} must be a file, not a directory'.format(filepath))
  346. return filepath
  347. def destination_path(destpath):
  348. if os.path.isabs(destpath):
  349. raise argparse.ArgumentTypeError('{0!r} must be a relative path, not absolute'.format(destpath))
  350. return destpath
  351. def target_path(targetpath):
  352. if not os.path.isabs(targetpath):
  353. raise argparse.ArgumentTypeError('{0!r} must be an absolute path, not relative'.format(targetpath))
  354. return targetpath
  355. def register_commands(subparsers):
  356. common = argparse.ArgumentParser(add_help=False)
  357. common.add_argument('-m', '--machine', help='Make bbappend changes specific to a machine only', metavar='MACHINE')
  358. common.add_argument('-w', '--wildcard-version', help='Use wildcard to make the bbappend apply to any recipe version', action='store_true')
  359. common.add_argument('destlayer', metavar='DESTLAYER', help='Base directory of the destination layer to write the bbappend to', type=layer)
  360. parser_appendfile = subparsers.add_parser('appendfile',
  361. parents=[common],
  362. help='Create/update a bbappend to replace a target file',
  363. description='Creates a bbappend (or updates an existing one) to replace the specified file that appears in the target system, determining the recipe that packages the file and the required path and name for the bbappend automatically. Note that the ability to determine the recipe packaging a particular file depends upon the recipe\'s do_packagedata task having already run prior to running this command (which it will have when the recipe has been built successfully, which in turn will have happened if one or more of the recipe\'s packages is included in an image that has been built successfully).')
  364. parser_appendfile.add_argument('targetpath', help='Path to the file to be replaced (as it would appear within the target image, e.g. /etc/motd)', type=target_path)
  365. parser_appendfile.add_argument('newfile', help='Custom file to replace the target file with', type=existing_file)
  366. parser_appendfile.add_argument('-r', '--recipe', help='Override recipe to apply to (default is to find which recipe already packages the file)')
  367. parser_appendfile.set_defaults(func=appendfile, parserecipes=True)
  368. common_src = argparse.ArgumentParser(add_help=False, parents=[common])
  369. common_src.add_argument('-W', '--workdir', help='Unpack file into WORKDIR rather than S', dest='use_workdir', action='store_true')
  370. common_src.add_argument('recipe', metavar='RECIPE', help='Override recipe to apply to')
  371. parser = subparsers.add_parser('appendsrcfiles',
  372. parents=[common_src],
  373. help='Create/update a bbappend to add or replace source files',
  374. description='Creates a bbappend (or updates an existing one) to add or replace the specified file in the recipe sources, either those in WORKDIR or those in the source tree. This command lets you specify multiple files with a destination directory, so cannot specify the destination filename. See the `appendsrcfile` command for the other behavior.')
  375. parser.add_argument('-D', '--destdir', help='Destination directory (relative to S or WORKDIR, defaults to ".")', default='', type=destination_path)
  376. parser.add_argument('files', nargs='+', metavar='FILE', help='File(s) to be added to the recipe sources (WORKDIR or S)', type=existing_path)
  377. parser.set_defaults(func=lambda a: appendsrcfiles(parser, a), parserecipes=True)
  378. parser = subparsers.add_parser('appendsrcfile',
  379. parents=[common_src],
  380. help='Create/update a bbappend to add or replace a source file',
  381. description='Creates a bbappend (or updates an existing one) to add or replace the specified files in the recipe sources, either those in WORKDIR or those in the source tree. This command lets you specify the destination filename, not just destination directory, but only works for one file. See the `appendsrcfiles` command for the other behavior.')
  382. parser.add_argument('file', metavar='FILE', help='File to be added to the recipe sources (WORKDIR or S)', type=existing_path)
  383. parser.add_argument('destfile', metavar='DESTFILE', nargs='?', help='Destination path (relative to S or WORKDIR, optional)', type=destination_path)
  384. parser.set_defaults(func=lambda a: appendsrcfile(parser, a), parserecipes=True)