append.py 22 KB

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