deploy.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # Development tool - deploy/undeploy command plugin
  2. #
  3. # Copyright (C) 2014-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.
  17. """Devtool plugin containing the deploy subcommands"""
  18. import logging
  19. import os
  20. import shutil
  21. import subprocess
  22. import tempfile
  23. import bb.utils
  24. import argparse_oe
  25. import oe.types
  26. from devtool import exec_fakeroot, setup_tinfoil, check_workspace_recipe, DevtoolError
  27. logger = logging.getLogger('devtool')
  28. deploylist_path = '/.devtool'
  29. def _prepare_remote_script(deploy, verbose=False, dryrun=False, undeployall=False, nopreserve=False, nocheckspace=False):
  30. """
  31. Prepare a shell script for running on the target to
  32. deploy/undeploy files. We have to be careful what we put in this
  33. script - only commands that are likely to be available on the
  34. target are suitable (the target might be constrained, e.g. using
  35. busybox rather than bash with coreutils).
  36. """
  37. lines = []
  38. lines.append('#!/bin/sh')
  39. lines.append('set -e')
  40. if undeployall:
  41. # Yes, I know this is crude - but it does work
  42. lines.append('for entry in %s/*.list; do' % deploylist_path)
  43. lines.append('[ ! -f $entry ] && exit')
  44. lines.append('set `basename $entry | sed "s/.list//"`')
  45. if dryrun:
  46. if not deploy:
  47. lines.append('echo "Previously deployed files for $1:"')
  48. lines.append('manifest="%s/$1.list"' % deploylist_path)
  49. lines.append('preservedir="%s/$1.preserve"' % deploylist_path)
  50. lines.append('if [ -f $manifest ] ; then')
  51. # Read manifest in reverse and delete files / remove empty dirs
  52. lines.append(' sed \'1!G;h;$!d\' $manifest | while read file')
  53. lines.append(' do')
  54. if dryrun:
  55. lines.append(' if [ ! -d $file ] ; then')
  56. lines.append(' echo $file')
  57. lines.append(' fi')
  58. else:
  59. lines.append(' if [ -d $file ] ; then')
  60. # Avoid deleting a preserved directory in case it has special perms
  61. lines.append(' if [ ! -d $preservedir/$file ] ; then')
  62. lines.append(' rmdir $file > /dev/null 2>&1 || true')
  63. lines.append(' fi')
  64. lines.append(' else')
  65. lines.append(' rm -f $file')
  66. lines.append(' fi')
  67. lines.append(' done')
  68. if not dryrun:
  69. lines.append(' rm $manifest')
  70. if not deploy and not dryrun:
  71. # May as well remove all traces
  72. lines.append(' rmdir `dirname $manifest` > /dev/null 2>&1 || true')
  73. lines.append('fi')
  74. if deploy:
  75. if not nocheckspace:
  76. # Check for available space
  77. # FIXME This doesn't take into account files spread across multiple
  78. # partitions, but doing that is non-trivial
  79. # Find the part of the destination path that exists
  80. lines.append('checkpath="$2"')
  81. lines.append('while [ "$checkpath" != "/" ] && [ ! -e $checkpath ]')
  82. lines.append('do')
  83. lines.append(' checkpath=`dirname "$checkpath"`')
  84. lines.append('done')
  85. lines.append(r'freespace=$(df -P $checkpath | sed -nre "s/^(\S+\s+){3}([0-9]+).*/\2/p")')
  86. # First line of the file is the total space
  87. lines.append('total=`head -n1 $3`')
  88. lines.append('if [ $total -gt $freespace ] ; then')
  89. lines.append(' echo "ERROR: insufficient space on target (available ${freespace}, needed ${total})"')
  90. lines.append(' exit 1')
  91. lines.append('fi')
  92. if not nopreserve:
  93. # Preserve any files that exist. Note that this will add to the
  94. # preserved list with successive deployments if the list of files
  95. # deployed changes, but because we've deleted any previously
  96. # deployed files at this point it will never preserve anything
  97. # that was deployed, only files that existed prior to any deploying
  98. # (which makes the most sense)
  99. lines.append('cat $3 | sed "1d" | while read file fsize')
  100. lines.append('do')
  101. lines.append(' if [ -e $file ] ; then')
  102. lines.append(' dest="$preservedir/$file"')
  103. lines.append(' mkdir -p `dirname $dest`')
  104. lines.append(' mv $file $dest')
  105. lines.append(' fi')
  106. lines.append('done')
  107. lines.append('rm $3')
  108. lines.append('mkdir -p `dirname $manifest`')
  109. lines.append('mkdir -p $2')
  110. if verbose:
  111. lines.append(' tar xv -C $2 -f - | tee $manifest')
  112. else:
  113. lines.append(' tar xv -C $2 -f - > $manifest')
  114. lines.append('sed -i "s!^./!$2!" $manifest')
  115. elif not dryrun:
  116. # Put any preserved files back
  117. lines.append('if [ -d $preservedir ] ; then')
  118. lines.append(' cd $preservedir')
  119. # find from busybox might not have -exec, so we don't use that
  120. lines.append(' find . -type f | while read file')
  121. lines.append(' do')
  122. lines.append(' mv $file /$file')
  123. lines.append(' done')
  124. lines.append(' cd /')
  125. lines.append(' rm -rf $preservedir')
  126. lines.append('fi')
  127. if undeployall:
  128. if not dryrun:
  129. lines.append('echo "NOTE: Successfully undeployed $1"')
  130. lines.append('done')
  131. # Delete the script itself
  132. lines.append('rm $0')
  133. lines.append('')
  134. return '\n'.join(lines)
  135. def deploy(args, config, basepath, workspace):
  136. """Entry point for the devtool 'deploy' subcommand"""
  137. import math
  138. import oe.recipeutils
  139. import oe.package
  140. check_workspace_recipe(workspace, args.recipename, checksrc=False)
  141. try:
  142. host, destdir = args.target.split(':')
  143. except ValueError:
  144. destdir = '/'
  145. else:
  146. args.target = host
  147. if not destdir.endswith('/'):
  148. destdir += '/'
  149. tinfoil = setup_tinfoil(basepath=basepath)
  150. try:
  151. try:
  152. rd = tinfoil.parse_recipe(args.recipename)
  153. except Exception as e:
  154. raise DevtoolError('Exception parsing recipe %s: %s' %
  155. (args.recipename, e))
  156. recipe_outdir = rd.getVar('D')
  157. if not os.path.exists(recipe_outdir) or not os.listdir(recipe_outdir):
  158. raise DevtoolError('No files to deploy - have you built the %s '
  159. 'recipe? If so, the install step has not installed '
  160. 'any files.' % args.recipename)
  161. if args.strip and not args.dry_run:
  162. # Fakeroot copy to new destination
  163. srcdir = recipe_outdir
  164. recipe_outdir = os.path.join(rd.getVar('WORKDIR'), 'deploy-target-stripped')
  165. if os.path.isdir(recipe_outdir):
  166. bb.utils.remove(recipe_outdir, True)
  167. exec_fakeroot(rd, "cp -af %s %s" % (os.path.join(srcdir, '.'), recipe_outdir), shell=True)
  168. os.environ['PATH'] = ':'.join([os.environ['PATH'], rd.getVar('PATH') or ''])
  169. oe.package.strip_execs(args.recipename, recipe_outdir, rd.getVar('STRIP'), rd.getVar('libdir'),
  170. rd.getVar('base_libdir'), rd)
  171. filelist = []
  172. ftotalsize = 0
  173. for root, _, files in os.walk(recipe_outdir):
  174. for fn in files:
  175. # Get the size in kiB (since we'll be comparing it to the output of du -k)
  176. # MUST use lstat() here not stat() or getfilesize() since we don't want to
  177. # dereference symlinks
  178. fsize = int(math.ceil(float(os.lstat(os.path.join(root, fn)).st_size)/1024))
  179. ftotalsize += fsize
  180. # The path as it would appear on the target
  181. fpath = os.path.join(destdir, os.path.relpath(root, recipe_outdir), fn)
  182. filelist.append((fpath, fsize))
  183. if args.dry_run:
  184. print('Files to be deployed for %s on target %s:' % (args.recipename, args.target))
  185. for item, _ in filelist:
  186. print(' %s' % item)
  187. return 0
  188. extraoptions = ''
  189. if args.no_host_check:
  190. extraoptions += '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
  191. if not args.show_status:
  192. extraoptions += ' -q'
  193. scp_port = ''
  194. ssh_port = ''
  195. if args.port:
  196. scp_port = "-P %s" % args.port
  197. ssh_port = "-p %s" % args.port
  198. # In order to delete previously deployed files and have the manifest file on
  199. # the target, we write out a shell script and then copy it to the target
  200. # so we can then run it (piping tar output to it).
  201. # (We cannot use scp here, because it doesn't preserve symlinks.)
  202. tmpdir = tempfile.mkdtemp(prefix='devtool')
  203. try:
  204. tmpscript = '/tmp/devtool_deploy.sh'
  205. tmpfilelist = os.path.join(os.path.dirname(tmpscript), 'devtool_deploy.list')
  206. shellscript = _prepare_remote_script(deploy=True,
  207. verbose=args.show_status,
  208. nopreserve=args.no_preserve,
  209. nocheckspace=args.no_check_space)
  210. # Write out the script to a file
  211. with open(os.path.join(tmpdir, os.path.basename(tmpscript)), 'w') as f:
  212. f.write(shellscript)
  213. # Write out the file list
  214. with open(os.path.join(tmpdir, os.path.basename(tmpfilelist)), 'w') as f:
  215. f.write('%d\n' % ftotalsize)
  216. for fpath, fsize in filelist:
  217. f.write('%s %d\n' % (fpath, fsize))
  218. # Copy them to the target
  219. ret = subprocess.call("scp %s %s %s/* %s:%s" % (scp_port, extraoptions, tmpdir, args.target, os.path.dirname(tmpscript)), shell=True)
  220. if ret != 0:
  221. raise DevtoolError('Failed to copy script to %s - rerun with -s to '
  222. 'get a complete error message' % args.target)
  223. finally:
  224. shutil.rmtree(tmpdir)
  225. # Now run the script
  226. ret = exec_fakeroot(rd, 'tar cf - . | ssh %s %s %s \'sh %s %s %s %s\'' % (ssh_port, extraoptions, args.target, tmpscript, args.recipename, destdir, tmpfilelist), cwd=recipe_outdir, shell=True)
  227. if ret != 0:
  228. raise DevtoolError('Deploy failed - rerun with -s to get a complete '
  229. 'error message')
  230. logger.info('Successfully deployed %s' % recipe_outdir)
  231. files_list = []
  232. for root, _, files in os.walk(recipe_outdir):
  233. for filename in files:
  234. filename = os.path.relpath(os.path.join(root, filename), recipe_outdir)
  235. files_list.append(os.path.join(destdir, filename))
  236. finally:
  237. tinfoil.shutdown()
  238. return 0
  239. def undeploy(args, config, basepath, workspace):
  240. """Entry point for the devtool 'undeploy' subcommand"""
  241. if args.all and args.recipename:
  242. raise argparse_oe.ArgumentUsageError('Cannot specify -a/--all with a recipe name', 'undeploy-target')
  243. elif not args.recipename and not args.all:
  244. raise argparse_oe.ArgumentUsageError('If you don\'t specify a recipe, you must specify -a/--all', 'undeploy-target')
  245. extraoptions = ''
  246. if args.no_host_check:
  247. extraoptions += '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
  248. if not args.show_status:
  249. extraoptions += ' -q'
  250. scp_port = ''
  251. ssh_port = ''
  252. if args.port:
  253. scp_port = "-P %s" % args.port
  254. ssh_port = "-p %s" % args.port
  255. args.target = args.target.split(':')[0]
  256. tmpdir = tempfile.mkdtemp(prefix='devtool')
  257. try:
  258. tmpscript = '/tmp/devtool_undeploy.sh'
  259. shellscript = _prepare_remote_script(deploy=False, dryrun=args.dry_run, undeployall=args.all)
  260. # Write out the script to a file
  261. with open(os.path.join(tmpdir, os.path.basename(tmpscript)), 'w') as f:
  262. f.write(shellscript)
  263. # Copy it to the target
  264. ret = subprocess.call("scp %s %s %s/* %s:%s" % (scp_port, extraoptions, tmpdir, args.target, os.path.dirname(tmpscript)), shell=True)
  265. if ret != 0:
  266. raise DevtoolError('Failed to copy script to %s - rerun with -s to '
  267. 'get a complete error message' % args.target)
  268. finally:
  269. shutil.rmtree(tmpdir)
  270. # Now run the script
  271. ret = subprocess.call('ssh %s %s %s \'sh %s %s\'' % (ssh_port, extraoptions, args.target, tmpscript, args.recipename), shell=True)
  272. if ret != 0:
  273. raise DevtoolError('Undeploy failed - rerun with -s to get a complete '
  274. 'error message')
  275. if not args.all and not args.dry_run:
  276. logger.info('Successfully undeployed %s' % args.recipename)
  277. return 0
  278. def register_commands(subparsers, context):
  279. """Register devtool subcommands from the deploy plugin"""
  280. parser_deploy = subparsers.add_parser('deploy-target',
  281. help='Deploy recipe output files to live target machine',
  282. description='Deploys a recipe\'s build output (i.e. the output of the do_install task) to a live target machine over ssh. By default, any existing files will be preserved instead of being overwritten and will be restored if you run devtool undeploy-target. Note: this only deploys the recipe itself and not any runtime dependencies, so it is assumed that those have been installed on the target beforehand.',
  283. group='testbuild')
  284. parser_deploy.add_argument('recipename', help='Recipe to deploy')
  285. parser_deploy.add_argument('target', help='Live target machine running an ssh server: user@hostname[:destdir]')
  286. parser_deploy.add_argument('-c', '--no-host-check', help='Disable ssh host key checking', action='store_true')
  287. parser_deploy.add_argument('-s', '--show-status', help='Show progress/status output', action='store_true')
  288. parser_deploy.add_argument('-n', '--dry-run', help='List files to be deployed only', action='store_true')
  289. parser_deploy.add_argument('-p', '--no-preserve', help='Do not preserve existing files', action='store_true')
  290. parser_deploy.add_argument('--no-check-space', help='Do not check for available space before deploying', action='store_true')
  291. parser_deploy.add_argument('-P', '--port', help='Specify port to use for connection to the target')
  292. strip_opts = parser_deploy.add_mutually_exclusive_group(required=False)
  293. strip_opts.add_argument('-S', '--strip',
  294. help='Strip executables prior to deploying (default: %(default)s). '
  295. 'The default value of this option can be controlled by setting the strip option in the [Deploy] section to True or False.',
  296. default=oe.types.boolean(context.config.get('Deploy', 'strip', default='0')),
  297. action='store_true')
  298. strip_opts.add_argument('--no-strip', help='Do not strip executables prior to deploy', dest='strip', action='store_false')
  299. parser_deploy.set_defaults(func=deploy)
  300. parser_undeploy = subparsers.add_parser('undeploy-target',
  301. help='Undeploy recipe output files in live target machine',
  302. description='Un-deploys recipe output files previously deployed to a live target machine by devtool deploy-target.',
  303. group='testbuild')
  304. parser_undeploy.add_argument('recipename', help='Recipe to undeploy (if not using -a/--all)', nargs='?')
  305. parser_undeploy.add_argument('target', help='Live target machine running an ssh server: user@hostname')
  306. parser_undeploy.add_argument('-c', '--no-host-check', help='Disable ssh host key checking', action='store_true')
  307. parser_undeploy.add_argument('-s', '--show-status', help='Show progress/status output', action='store_true')
  308. parser_undeploy.add_argument('-a', '--all', help='Undeploy all recipes deployed on the target', action='store_true')
  309. parser_undeploy.add_argument('-n', '--dry-run', help='List files to be undeployed only', action='store_true')
  310. parser_undeploy.add_argument('-P', '--port', help='Specify port to use for connection to the target')
  311. parser_undeploy.set_defaults(func=undeploy)