buildpackage.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # -*- coding: utf-8 -*-
  2. # Maintainer: Erik Johnson (https://github.com/terminalmage)
  3. #
  4. # WARNING: This script will recursively remove the build and artifact
  5. # directories.
  6. #
  7. # This script is designed for speed, therefore it does not use mock and does not
  8. # run tests. It *will* install the build deps on the machine running the script.
  9. #
  10. # pylint: disable=file-perms,resource-leakage
  11. from __future__ import absolute_import, print_function
  12. import errno
  13. import glob
  14. import logging
  15. import os
  16. import re
  17. import shutil
  18. import subprocess
  19. import sys
  20. from optparse import OptionParser, OptionGroup
  21. logging.QUIET = 0
  22. logging.GARBAGE = 1
  23. logging.TRACE = 5
  24. logging.addLevelName(logging.QUIET, 'QUIET')
  25. logging.addLevelName(logging.TRACE, 'TRACE')
  26. logging.addLevelName(logging.GARBAGE, 'GARBAGE')
  27. LOG_LEVELS = {
  28. 'all': logging.NOTSET,
  29. 'debug': logging.DEBUG,
  30. 'error': logging.ERROR,
  31. 'critical': logging.CRITICAL,
  32. 'garbage': logging.GARBAGE,
  33. 'info': logging.INFO,
  34. 'quiet': logging.QUIET,
  35. 'trace': logging.TRACE,
  36. 'warning': logging.WARNING,
  37. }
  38. log = logging.getLogger(__name__)
  39. # FUNCTIONS
  40. def _abort(msgs):
  41. '''
  42. Unrecoverable error, pull the plug
  43. '''
  44. if not isinstance(msgs, list):
  45. msgs = [msgs]
  46. for msg in msgs:
  47. log.error(msg)
  48. sys.stderr.write(msg + '\n\n')
  49. sys.stderr.write('Build failed. See log file for further details.\n')
  50. sys.exit(1)
  51. # HELPER FUNCTIONS
  52. def _init():
  53. '''
  54. Parse CLI options.
  55. '''
  56. parser = OptionParser()
  57. parser.add_option('--platform',
  58. dest='platform',
  59. help='Platform (\'os\' grain)')
  60. parser.add_option('--log-level',
  61. dest='log_level',
  62. default='warning',
  63. help='Control verbosity of logging. Default: %default')
  64. # All arguments dealing with file paths (except for platform-specific ones
  65. # like those for SPEC files) should be placed in this group so that
  66. # relative paths are properly expanded.
  67. path_group = OptionGroup(parser, 'File/Directory Options')
  68. path_group.add_option('--source-dir',
  69. default='/testing',
  70. help='Source directory. Must be a git checkout. '
  71. '(default: %default)')
  72. path_group.add_option('--build-dir',
  73. default='/tmp/salt-buildpackage',
  74. help='Build root, will be removed if it exists '
  75. 'prior to running script. (default: %default)')
  76. path_group.add_option('--artifact-dir',
  77. default='/tmp/salt-packages',
  78. help='Location where build artifacts should be '
  79. 'placed for Jenkins to retrieve them '
  80. '(default: %default)')
  81. parser.add_option_group(path_group)
  82. # This group should also consist of nothing but file paths, which will be
  83. # normalized below.
  84. rpm_group = OptionGroup(parser, 'RPM-specific File/Directory Options')
  85. rpm_group.add_option('--spec',
  86. dest='spec_file',
  87. default='/tmp/salt.spec',
  88. help='Spec file to use as a template to build RPM. '
  89. '(default: %default)')
  90. parser.add_option_group(rpm_group)
  91. opts = parser.parse_args()[0]
  92. # Expand any relative paths
  93. for group in (path_group, rpm_group):
  94. for path_opt in [opt.dest for opt in group.option_list]:
  95. path = getattr(opts, path_opt)
  96. if not os.path.isabs(path):
  97. # Expand ~ or ~user
  98. path = os.path.expanduser(path)
  99. if not os.path.isabs(path):
  100. # Still not absolute, resolve '..'
  101. path = os.path.realpath(path)
  102. # Update attribute with absolute path
  103. setattr(opts, path_opt, path)
  104. # Sanity checks
  105. problems = []
  106. if not opts.platform:
  107. problems.append('Platform (\'os\' grain) required')
  108. if not os.path.isdir(opts.source_dir):
  109. problems.append('Source directory {0} not found'
  110. .format(opts.source_dir))
  111. try:
  112. shutil.rmtree(opts.build_dir)
  113. except OSError as exc:
  114. if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
  115. problems.append('Unable to remove pre-existing destination '
  116. 'directory {0}: {1}'.format(opts.build_dir, exc))
  117. finally:
  118. try:
  119. os.makedirs(opts.build_dir)
  120. except OSError as exc:
  121. problems.append('Unable to create destination directory {0}: {1}'
  122. .format(opts.build_dir, exc))
  123. try:
  124. shutil.rmtree(opts.artifact_dir)
  125. except OSError as exc:
  126. if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
  127. problems.append('Unable to remove pre-existing artifact directory '
  128. '{0}: {1}'.format(opts.artifact_dir, exc))
  129. finally:
  130. try:
  131. os.makedirs(opts.artifact_dir)
  132. except OSError as exc:
  133. problems.append('Unable to create artifact directory {0}: {1}'
  134. .format(opts.artifact_dir, exc))
  135. # Create log file in the artifact dir so it is sent back to master if the
  136. # job fails
  137. opts.log_file = os.path.join(opts.artifact_dir, 'salt-buildpackage.log')
  138. if problems:
  139. _abort(problems)
  140. return opts
  141. def _move(src, dst):
  142. '''
  143. Wrapper around shutil.move()
  144. '''
  145. try:
  146. os.remove(os.path.join(dst, os.path.basename(src)))
  147. except OSError as exc:
  148. if exc.errno != errno.ENOENT:
  149. _abort(exc)
  150. try:
  151. shutil.move(src, dst)
  152. except shutil.Error as exc:
  153. _abort(exc)
  154. def _run_command(args):
  155. log.info('Running command: {0}'.format(args))
  156. proc = subprocess.Popen(args,
  157. stdout=subprocess.PIPE,
  158. stderr=subprocess.PIPE)
  159. stdout, stderr = proc.communicate()
  160. if stdout:
  161. log.debug('Command output: \n{0}'.format(stdout))
  162. if stderr:
  163. log.error(stderr)
  164. log.info('Return code: {0}'.format(proc.returncode))
  165. return stdout, stderr, proc.returncode
  166. def _make_sdist(opts, python_bin='python'):
  167. os.chdir(opts.source_dir)
  168. stdout, stderr, rcode = _run_command([python_bin, 'setup.py', 'sdist'])
  169. if rcode == 0:
  170. # Find the sdist with the most recently-modified metadata
  171. sdist_path = max(
  172. glob.iglob(os.path.join(opts.source_dir, 'dist', 'salt-*.tar.gz')),
  173. key=os.path.getctime
  174. )
  175. log.info('sdist is located at {0}'.format(sdist_path))
  176. return sdist_path
  177. else:
  178. _abort('Failed to create sdist')
  179. # BUILDER FUNCTIONS
  180. def build_centos(opts):
  181. '''
  182. Build an RPM
  183. '''
  184. log.info('Building CentOS RPM')
  185. log.info('Detecting major release')
  186. try:
  187. with open('/etc/redhat-release', 'r') as fp_:
  188. redhat_release = fp_.read().strip()
  189. major_release = int(redhat_release.split()[2].split('.')[0])
  190. except (ValueError, IndexError):
  191. _abort('Unable to determine major release from /etc/redhat-release '
  192. 'contents: \'{0}\''.format(redhat_release))
  193. except IOError as exc:
  194. _abort('{0}'.format(exc))
  195. log.info('major_release: {0}'.format(major_release))
  196. define_opts = [
  197. '--define',
  198. '_topdir {0}'.format(os.path.join(opts.build_dir))
  199. ]
  200. build_reqs = ['rpm-build']
  201. if major_release == 5:
  202. python_bin = 'python26'
  203. define_opts.extend(['--define', 'dist .el5'])
  204. if os.path.exists('/etc/yum.repos.d/saltstack.repo'):
  205. build_reqs.extend(['--enablerepo=saltstack'])
  206. build_reqs.extend(['python26-devel'])
  207. elif major_release == 6:
  208. build_reqs.extend(['python-devel'])
  209. elif major_release == 7:
  210. build_reqs.extend(['python-devel', 'systemd-units'])
  211. else:
  212. _abort('Unsupported major release: {0}'.format(major_release))
  213. # Install build deps
  214. _run_command(['yum', '-y', 'install'] + build_reqs)
  215. # Make the sdist
  216. try:
  217. sdist = _make_sdist(opts, python_bin=python_bin)
  218. except NameError:
  219. sdist = _make_sdist(opts)
  220. # Example tarball names:
  221. # - Git checkout: salt-2014.7.0rc1-1584-g666602e.tar.gz
  222. # - Tagged release: salt-2014.7.0.tar.gz
  223. tarball_re = re.compile(r'^salt-([^-]+)(?:-(\d+)-(g[0-9a-f]+))?\.tar\.gz$')
  224. try:
  225. base, offset, oid = tarball_re.match(os.path.basename(sdist)).groups()
  226. except AttributeError:
  227. _abort('Unable to extract version info from sdist filename \'{0}\''
  228. .format(sdist))
  229. if offset is None:
  230. salt_pkgver = salt_srcver = base
  231. else:
  232. salt_pkgver = '.'.join((base, offset, oid))
  233. salt_srcver = '-'.join((base, offset, oid))
  234. log.info('salt_pkgver: {0}'.format(salt_pkgver))
  235. log.info('salt_srcver: {0}'.format(salt_srcver))
  236. # Setup build environment
  237. for build_dir in 'BUILD BUILDROOT RPMS SOURCES SPECS SRPMS'.split():
  238. path = os.path.join(opts.build_dir, build_dir)
  239. try:
  240. os.makedirs(path)
  241. except OSError:
  242. pass
  243. if not os.path.isdir(path):
  244. _abort('Unable to make directory: {0}'.format(path))
  245. # Get sources into place
  246. build_sources_path = os.path.join(opts.build_dir, 'SOURCES')
  247. rpm_sources_path = os.path.join(opts.source_dir, 'pkg', 'rpm')
  248. _move(sdist, build_sources_path)
  249. for src in ('salt-master', 'salt-syndic', 'salt-minion', 'salt-api',
  250. 'salt-master.service', 'salt-syndic.service',
  251. 'salt-minion.service', 'salt-api.service',
  252. 'README.fedora', 'logrotate.salt', 'salt.bash'):
  253. shutil.copy(os.path.join(rpm_sources_path, src), build_sources_path)
  254. # Prepare SPEC file
  255. spec_path = os.path.join(opts.build_dir, 'SPECS', 'salt.spec')
  256. with open(opts.spec_file, 'r') as spec:
  257. spec_lines = spec.read().splitlines()
  258. with open(spec_path, 'w') as fp_:
  259. for line in spec_lines:
  260. if line.startswith('%global srcver '):
  261. line = '%global srcver {0}'.format(salt_srcver)
  262. elif line.startswith('Version: '):
  263. line = 'Version: {0}'.format(salt_pkgver)
  264. fp_.write(line + '\n')
  265. # Do the thing
  266. cmd = ['rpmbuild', '-ba']
  267. cmd.extend(define_opts)
  268. cmd.append(spec_path)
  269. stdout, stderr, rcode = _run_command(cmd)
  270. if rcode != 0:
  271. _abort('Build failed.')
  272. packages = glob.glob(
  273. os.path.join(
  274. opts.build_dir,
  275. 'RPMS',
  276. 'noarch',
  277. 'salt-*{0}*.noarch.rpm'.format(salt_pkgver)
  278. )
  279. )
  280. packages.extend(
  281. glob.glob(
  282. os.path.join(
  283. opts.build_dir,
  284. 'SRPMS',
  285. 'salt-{0}*.src.rpm'.format(salt_pkgver)
  286. )
  287. )
  288. )
  289. return packages
  290. # MAIN
  291. if __name__ == '__main__':
  292. opts = _init()
  293. print('Starting {0} build. Progress will be logged to {1}.'
  294. .format(opts.platform, opts.log_file))
  295. # Setup logging
  296. log_format = '%(asctime)s.%(msecs)03d %(levelname)s: %(message)s'
  297. log_datefmt = '%H:%M:%S'
  298. log_level = LOG_LEVELS[opts.log_level] \
  299. if opts.log_level in LOG_LEVELS \
  300. else LOG_LEVELS['warning']
  301. logging.basicConfig(filename=opts.log_file,
  302. format=log_format,
  303. datefmt=log_datefmt,
  304. level=LOG_LEVELS[opts.log_level])
  305. if opts.log_level not in LOG_LEVELS:
  306. log.error('Invalid log level \'{0}\', falling back to \'warning\''
  307. .format(opts.log_level))
  308. # Build for the specified platform
  309. if not opts.platform:
  310. _abort('Platform required')
  311. elif opts.platform.lower() == 'centos':
  312. artifacts = build_centos(opts)
  313. else:
  314. _abort('Unsupported platform \'{0}\''.format(opts.platform))
  315. msg = ('Build complete. Artifacts will be stored in {0}'
  316. .format(opts.artifact_dir))
  317. log.info(msg)
  318. print(msg) # pylint: disable=C0325
  319. for artifact in artifacts:
  320. shutil.copy(artifact, opts.artifact_dir)
  321. log.info('Copied {0} to artifact directory'.format(artifact))
  322. log.info('Done!')