append.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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')
  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 _parse_recipe(pn, tinfoil):
  87. try:
  88. rd = tinfoil.parse_recipe(pn)
  89. except bb.providers.NoProvider as e:
  90. logger.error(str(e))
  91. return None
  92. return rd
  93. def determine_file_source(targetpath, rd):
  94. """Assuming we know a file came from a specific recipe, figure out exactly where it came from"""
  95. import oe.recipeutils
  96. # See if it's in do_install for the recipe
  97. workdir = rd.getVar('WORKDIR')
  98. src_uri = rd.getVar('SRC_URI')
  99. srcfile = ''
  100. modpatches = []
  101. elements = check_do_install(rd, targetpath)
  102. if elements:
  103. logger.debug('do_install line:\n%s' % ' '.join(elements))
  104. srcpath = get_source_path(elements)
  105. logger.debug('source path: %s' % srcpath)
  106. if not srcpath.startswith('/'):
  107. # Handle non-absolute path
  108. srcpath = os.path.abspath(os.path.join(rd.getVarFlag('do_install', 'dirs').split()[-1], srcpath))
  109. if srcpath.startswith(workdir):
  110. # OK, now we have the source file name, look for it in SRC_URI
  111. workdirfile = os.path.relpath(srcpath, workdir)
  112. # FIXME this is where we ought to have some code in the fetcher, because this is naive
  113. for item in src_uri.split():
  114. localpath = bb.fetch2.localpath(item, rd)
  115. # Source path specified in do_install might be a glob
  116. if fnmatch.fnmatch(os.path.basename(localpath), workdirfile):
  117. srcfile = 'file://%s' % localpath
  118. elif '/' in workdirfile:
  119. if item == 'file://%s' % workdirfile:
  120. srcfile = 'file://%s' % localpath
  121. # Check patches
  122. srcpatches = []
  123. patchedfiles = oe.recipeutils.get_recipe_patched_files(rd)
  124. for patch, filelist in patchedfiles.items():
  125. for fileitem in filelist:
  126. if fileitem[0] == srcpath:
  127. srcpatches.append((patch, fileitem[1]))
  128. if srcpatches:
  129. addpatch = None
  130. for patch in srcpatches:
  131. if patch[1] == 'A':
  132. addpatch = patch[0]
  133. else:
  134. modpatches.append(patch[0])
  135. if addpatch:
  136. srcfile = 'patch://%s' % addpatch
  137. return (srcfile, elements, modpatches)
  138. def get_source_path(cmdelements):
  139. """Find the source path specified within a command"""
  140. command = cmdelements[0]
  141. if command in ['install', 'cp']:
  142. helptext = subprocess.check_output('LC_ALL=C %s --help' % command, shell=True).decode('utf-8')
  143. argopts = ''
  144. argopt_line_re = re.compile('^-([a-zA-Z0-9]), --[a-z-]+=')
  145. for line in helptext.splitlines():
  146. line = line.lstrip()
  147. res = argopt_line_re.search(line)
  148. if res:
  149. argopts += res.group(1)
  150. if not argopts:
  151. # Fallback
  152. if command == 'install':
  153. argopts = 'gmoSt'
  154. elif command == 'cp':
  155. argopts = 't'
  156. else:
  157. raise Exception('No fallback arguments for command %s' % command)
  158. skipnext = False
  159. for elem in cmdelements[1:-1]:
  160. if elem.startswith('-'):
  161. if len(elem) > 1 and elem[1] in argopts:
  162. skipnext = True
  163. continue
  164. if skipnext:
  165. skipnext = False
  166. continue
  167. return elem
  168. else:
  169. raise Exception('get_source_path: no handling for command "%s"')
  170. def get_func_deps(func, d):
  171. """Find the function dependencies of a shell function"""
  172. deps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func))
  173. deps |= set((d.getVarFlag(func, "vardeps") or "").split())
  174. funcdeps = []
  175. for dep in deps:
  176. if d.getVarFlag(dep, 'func'):
  177. funcdeps.append(dep)
  178. return funcdeps
  179. def check_do_install(rd, targetpath):
  180. """Look at do_install for a command that installs/copies the specified target path"""
  181. instpath = os.path.abspath(os.path.join(rd.getVar('D'), targetpath.lstrip('/')))
  182. do_install = rd.getVar('do_install')
  183. # Handle where do_install calls other functions (somewhat crudely, but good enough for this purpose)
  184. deps = get_func_deps('do_install', rd)
  185. for dep in deps:
  186. do_install = do_install.replace(dep, rd.getVar(dep))
  187. # Look backwards through do_install as we want to catch where a later line (perhaps
  188. # from a bbappend) is writing over the top
  189. for line in reversed(do_install.splitlines()):
  190. line = line.strip()
  191. if (line.startswith('install ') and ' -m' in line) or line.startswith('cp '):
  192. elements = line.split()
  193. destpath = os.path.abspath(elements[-1])
  194. if destpath == instpath:
  195. return elements
  196. elif destpath.rstrip('/') == os.path.dirname(instpath):
  197. # FIXME this doesn't take recursive copy into account; unsure if it's practical to do so
  198. srcpath = get_source_path(elements)
  199. if fnmatch.fnmatchcase(os.path.basename(instpath), os.path.basename(srcpath)):
  200. return elements
  201. return None
  202. def appendfile(args):
  203. import oe.recipeutils
  204. stdout = ''
  205. try:
  206. (stdout, _) = bb.process.run('LANG=C file -b %s' % args.newfile, shell=True)
  207. if 'cannot open' in stdout:
  208. raise bb.process.ExecutionError(stdout)
  209. except bb.process.ExecutionError as err:
  210. logger.debug('file command returned error: %s' % err)
  211. stdout = ''
  212. if stdout:
  213. logger.debug('file command output: %s' % stdout.rstrip())
  214. if ('executable' in stdout and not 'shell script' in stdout) or 'shared object' in stdout:
  215. 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.')
  216. if args.recipe:
  217. recipes = {args.targetpath: [args.recipe],}
  218. else:
  219. try:
  220. recipes = find_target_file(args.targetpath, tinfoil.config_data)
  221. except InvalidTargetFileError as e:
  222. logger.error('%s cannot be handled by this tool: %s' % (args.targetpath, e))
  223. return 1
  224. if not recipes:
  225. 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)
  226. return 1
  227. alternative_pns = []
  228. postinst_pns = []
  229. selectpn = None
  230. for targetpath, pnlist in recipes.items():
  231. for pn in pnlist:
  232. if pn.startswith('?'):
  233. alternative_pns.append(pn[1:])
  234. elif pn.startswith('!'):
  235. postinst_pns.append(pn[1:])
  236. elif selectpn:
  237. # hit here with multilibs
  238. continue
  239. else:
  240. selectpn = pn
  241. if not selectpn and len(alternative_pns) == 1:
  242. selectpn = alternative_pns[0]
  243. 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))
  244. if selectpn:
  245. logger.debug('Selecting recipe %s for file %s' % (selectpn, args.targetpath))
  246. if postinst_pns:
  247. 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)))
  248. rd = _parse_recipe(selectpn, tinfoil)
  249. if not rd:
  250. # Error message already shown
  251. return 1
  252. sourcefile, instelements, modpatches = determine_file_source(args.targetpath, rd)
  253. sourcepath = None
  254. if sourcefile:
  255. sourcetype, sourcepath = sourcefile.split('://', 1)
  256. logger.debug('Original source file is %s (%s)' % (sourcepath, sourcetype))
  257. if sourcetype == 'patch':
  258. 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))
  259. sourcepath = None
  260. else:
  261. logger.debug('Unable to determine source file, proceeding anyway')
  262. if modpatches:
  263. logger.warning('File %s is modified by the following patches:\n %s' % (args.targetpath, '\n '.join(modpatches)))
  264. if instelements and sourcepath:
  265. install = None
  266. else:
  267. # Auto-determine permissions
  268. # Check destination
  269. binpaths = '${bindir}:${sbindir}:${base_bindir}:${base_sbindir}:${libexecdir}:${sysconfdir}/init.d'
  270. perms = '0644'
  271. if os.path.abspath(os.path.dirname(args.targetpath)) in rd.expand(binpaths).split(':'):
  272. # File is going into a directory normally reserved for executables, so it should be executable
  273. perms = '0755'
  274. else:
  275. # Check source
  276. st = os.stat(args.newfile)
  277. if st.st_mode & stat.S_IXUSR:
  278. perms = '0755'
  279. install = {args.newfile: (args.targetpath, perms)}
  280. oe.recipeutils.bbappend_recipe(rd, args.destlayer, {args.newfile: sourcepath}, install, wildcardver=args.wildcard_version, machine=args.machine)
  281. return 0
  282. else:
  283. if alternative_pns:
  284. 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)))
  285. elif postinst_pns:
  286. 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)))
  287. return 3
  288. def appendsrc(args, files, rd, extralines=None):
  289. import oe.recipeutils
  290. srcdir = rd.getVar('S')
  291. workdir = rd.getVar('WORKDIR')
  292. import bb.fetch
  293. simplified = {}
  294. src_uri = rd.getVar('SRC_URI').split()
  295. for uri in src_uri:
  296. if uri.endswith(';'):
  297. uri = uri[:-1]
  298. simple_uri = bb.fetch.URI(uri)
  299. simple_uri.params = {}
  300. simplified[str(simple_uri)] = uri
  301. copyfiles = {}
  302. extralines = extralines or []
  303. for newfile, srcfile in files.items():
  304. src_destdir = os.path.dirname(srcfile)
  305. if not args.use_workdir:
  306. if rd.getVar('S') == rd.getVar('STAGING_KERNEL_DIR'):
  307. srcdir = os.path.join(workdir, 'git')
  308. if not bb.data.inherits_class('kernel-yocto', rd):
  309. logger.warning('S == STAGING_KERNEL_DIR and non-kernel-yocto, unable to determine path to srcdir, defaulting to ${WORKDIR}/git')
  310. src_destdir = os.path.join(os.path.relpath(srcdir, workdir), src_destdir)
  311. src_destdir = os.path.normpath(src_destdir)
  312. source_uri = 'file://{0}'.format(os.path.basename(srcfile))
  313. if src_destdir and src_destdir != '.':
  314. source_uri += ';subdir={0}'.format(src_destdir)
  315. simple = bb.fetch.URI(source_uri)
  316. simple.params = {}
  317. simple_str = str(simple)
  318. if simple_str in simplified:
  319. existing = simplified[simple_str]
  320. if source_uri != existing:
  321. logger.warning('{0!r} is already in SRC_URI, with different parameters: {1!r}, not adding'.format(source_uri, existing))
  322. else:
  323. logger.warning('{0!r} is already in SRC_URI, not adding'.format(source_uri))
  324. else:
  325. extralines.append('SRC_URI += {0}'.format(source_uri))
  326. copyfiles[newfile] = srcfile
  327. oe.recipeutils.bbappend_recipe(rd, args.destlayer, copyfiles, None, wildcardver=args.wildcard_version, machine=args.machine, extralines=extralines)
  328. def appendsrcfiles(parser, args):
  329. recipedata = _parse_recipe(args.recipe, tinfoil)
  330. if not recipedata:
  331. parser.error('RECIPE must be a valid recipe name')
  332. files = dict((f, os.path.join(args.destdir, os.path.basename(f)))
  333. for f in args.files)
  334. return appendsrc(args, files, recipedata)
  335. def appendsrcfile(parser, args):
  336. recipedata = _parse_recipe(args.recipe, tinfoil)
  337. if not recipedata:
  338. parser.error('RECIPE must be a valid recipe name')
  339. if not args.destfile:
  340. args.destfile = os.path.basename(args.file)
  341. elif args.destfile.endswith('/'):
  342. args.destfile = os.path.join(args.destfile, os.path.basename(args.file))
  343. return appendsrc(args, {args.file: args.destfile}, recipedata)
  344. def layer(layerpath):
  345. if not os.path.exists(os.path.join(layerpath, 'conf', 'layer.conf')):
  346. raise argparse.ArgumentTypeError('{0!r} must be a path to a valid layer'.format(layerpath))
  347. return layerpath
  348. def existing_path(filepath):
  349. if not os.path.exists(filepath):
  350. raise argparse.ArgumentTypeError('{0!r} must be an existing path'.format(filepath))
  351. return filepath
  352. def existing_file(filepath):
  353. filepath = existing_path(filepath)
  354. if os.path.isdir(filepath):
  355. raise argparse.ArgumentTypeError('{0!r} must be a file, not a directory'.format(filepath))
  356. return filepath
  357. def destination_path(destpath):
  358. if os.path.isabs(destpath):
  359. raise argparse.ArgumentTypeError('{0!r} must be a relative path, not absolute'.format(destpath))
  360. return destpath
  361. def target_path(targetpath):
  362. if not os.path.isabs(targetpath):
  363. raise argparse.ArgumentTypeError('{0!r} must be an absolute path, not relative'.format(targetpath))
  364. return targetpath
  365. def register_commands(subparsers):
  366. common = argparse.ArgumentParser(add_help=False)
  367. common.add_argument('-m', '--machine', help='Make bbappend changes specific to a machine only', metavar='MACHINE')
  368. common.add_argument('-w', '--wildcard-version', help='Use wildcard to make the bbappend apply to any recipe version', action='store_true')
  369. common.add_argument('destlayer', metavar='DESTLAYER', help='Base directory of the destination layer to write the bbappend to', type=layer)
  370. parser_appendfile = subparsers.add_parser('appendfile',
  371. parents=[common],
  372. help='Create/update a bbappend to replace a target file',
  373. 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).')
  374. 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)
  375. parser_appendfile.add_argument('newfile', help='Custom file to replace the target file with', type=existing_file)
  376. parser_appendfile.add_argument('-r', '--recipe', help='Override recipe to apply to (default is to find which recipe already packages the file)')
  377. parser_appendfile.set_defaults(func=appendfile, parserecipes=True)
  378. common_src = argparse.ArgumentParser(add_help=False, parents=[common])
  379. common_src.add_argument('-W', '--workdir', help='Unpack file into WORKDIR rather than S', dest='use_workdir', action='store_true')
  380. common_src.add_argument('recipe', metavar='RECIPE', help='Override recipe to apply to')
  381. parser = subparsers.add_parser('appendsrcfiles',
  382. parents=[common_src],
  383. help='Create/update a bbappend to add or replace source files',
  384. 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.')
  385. parser.add_argument('-D', '--destdir', help='Destination directory (relative to S or WORKDIR, defaults to ".")', default='', type=destination_path)
  386. parser.add_argument('files', nargs='+', metavar='FILE', help='File(s) to be added to the recipe sources (WORKDIR or S)', type=existing_path)
  387. parser.set_defaults(func=lambda a: appendsrcfiles(parser, a), parserecipes=True)
  388. parser = subparsers.add_parser('appendsrcfile',
  389. parents=[common_src],
  390. help='Create/update a bbappend to add or replace a source file',
  391. 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.')
  392. parser.add_argument('file', metavar='FILE', help='File to be added to the recipe sources (WORKDIR or S)', type=existing_path)
  393. parser.add_argument('destfile', metavar='DESTFILE', nargs='?', help='Destination path (relative to S or WORKDIR, optional)', type=destination_path)
  394. parser.set_defaults(func=lambda a: appendsrcfile(parser, a), parserecipes=True)