1
0

buildpackage.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 OptionGroup, OptionParser
  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", dest="platform", help="Platform ('os' grain)")
  58. parser.add_option(
  59. "--log-level",
  60. dest="log_level",
  61. default="warning",
  62. help="Control verbosity of logging. Default: %default",
  63. )
  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(
  69. "--source-dir",
  70. default="/testing",
  71. help="Source directory. Must be a git checkout. " "(default: %default)",
  72. )
  73. path_group.add_option(
  74. "--build-dir",
  75. default="/tmp/salt-buildpackage",
  76. help="Build root, will be removed if it exists "
  77. "prior to running script. (default: %default)",
  78. )
  79. path_group.add_option(
  80. "--artifact-dir",
  81. default="/tmp/salt-packages",
  82. help="Location where build artifacts should be "
  83. "placed for Jenkins to retrieve them "
  84. "(default: %default)",
  85. )
  86. parser.add_option_group(path_group)
  87. # This group should also consist of nothing but file paths, which will be
  88. # normalized below.
  89. rpm_group = OptionGroup(parser, "RPM-specific File/Directory Options")
  90. rpm_group.add_option(
  91. "--spec",
  92. dest="spec_file",
  93. default="/tmp/salt.spec",
  94. help="Spec file to use as a template to build RPM. " "(default: %default)",
  95. )
  96. parser.add_option_group(rpm_group)
  97. opts = parser.parse_args()[0]
  98. # Expand any relative paths
  99. for group in (path_group, rpm_group):
  100. for path_opt in [opt.dest for opt in group.option_list]:
  101. path = getattr(opts, path_opt)
  102. if not os.path.isabs(path):
  103. # Expand ~ or ~user
  104. path = os.path.expanduser(path)
  105. if not os.path.isabs(path):
  106. # Still not absolute, resolve '..'
  107. path = os.path.realpath(path)
  108. # Update attribute with absolute path
  109. setattr(opts, path_opt, path)
  110. # Sanity checks
  111. problems = []
  112. if not opts.platform:
  113. problems.append("Platform ('os' grain) required")
  114. if not os.path.isdir(opts.source_dir):
  115. problems.append("Source directory {0} not found".format(opts.source_dir))
  116. try:
  117. shutil.rmtree(opts.build_dir)
  118. except OSError as exc:
  119. if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
  120. problems.append(
  121. "Unable to remove pre-existing destination "
  122. "directory {0}: {1}".format(opts.build_dir, exc)
  123. )
  124. finally:
  125. try:
  126. os.makedirs(opts.build_dir)
  127. except OSError as exc:
  128. problems.append(
  129. "Unable to create destination directory {0}: {1}".format(
  130. opts.build_dir, exc
  131. )
  132. )
  133. try:
  134. shutil.rmtree(opts.artifact_dir)
  135. except OSError as exc:
  136. if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
  137. problems.append(
  138. "Unable to remove pre-existing artifact directory "
  139. "{0}: {1}".format(opts.artifact_dir, exc)
  140. )
  141. finally:
  142. try:
  143. os.makedirs(opts.artifact_dir)
  144. except OSError as exc:
  145. problems.append(
  146. "Unable to create artifact directory {0}: {1}".format(
  147. opts.artifact_dir, exc
  148. )
  149. )
  150. # Create log file in the artifact dir so it is sent back to master if the
  151. # job fails
  152. opts.log_file = os.path.join(opts.artifact_dir, "salt-buildpackage.log")
  153. if problems:
  154. _abort(problems)
  155. return opts
  156. def _move(src, dst):
  157. """
  158. Wrapper around shutil.move()
  159. """
  160. try:
  161. os.remove(os.path.join(dst, os.path.basename(src)))
  162. except OSError as exc:
  163. if exc.errno != errno.ENOENT:
  164. _abort(exc)
  165. try:
  166. shutil.move(src, dst)
  167. except shutil.Error as exc:
  168. _abort(exc)
  169. def _run_command(args):
  170. log.info("Running command: {0}".format(args))
  171. proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  172. stdout, stderr = proc.communicate()
  173. if stdout:
  174. log.debug("Command output: \n{0}".format(stdout))
  175. if stderr:
  176. log.error(stderr)
  177. log.info("Return code: {0}".format(proc.returncode))
  178. return stdout, stderr, proc.returncode
  179. def _make_sdist(opts, python_bin="python"):
  180. os.chdir(opts.source_dir)
  181. stdout, stderr, rcode = _run_command([python_bin, "setup.py", "sdist"])
  182. if rcode == 0:
  183. # Find the sdist with the most recently-modified metadata
  184. sdist_path = max(
  185. glob.iglob(os.path.join(opts.source_dir, "dist", "salt-*.tar.gz")),
  186. key=os.path.getctime,
  187. )
  188. log.info("sdist is located at {0}".format(sdist_path))
  189. return sdist_path
  190. else:
  191. _abort("Failed to create sdist")
  192. # BUILDER FUNCTIONS
  193. def build_centos(opts):
  194. """
  195. Build an RPM
  196. """
  197. log.info("Building CentOS RPM")
  198. log.info("Detecting major release")
  199. try:
  200. with open("/etc/redhat-release", "r") as fp_:
  201. redhat_release = fp_.read().strip()
  202. major_release = int(redhat_release.split()[2].split(".")[0])
  203. except (ValueError, IndexError):
  204. _abort(
  205. "Unable to determine major release from /etc/redhat-release "
  206. "contents: '{0}'".format(redhat_release)
  207. )
  208. except IOError as exc:
  209. _abort("{0}".format(exc))
  210. log.info("major_release: {0}".format(major_release))
  211. define_opts = ["--define", "_topdir {0}".format(os.path.join(opts.build_dir))]
  212. build_reqs = ["rpm-build"]
  213. if major_release == 5:
  214. python_bin = "python26"
  215. define_opts.extend(["--define", "dist .el5"])
  216. if os.path.exists("/etc/yum.repos.d/saltstack.repo"):
  217. build_reqs.extend(["--enablerepo=saltstack"])
  218. build_reqs.extend(["python26-devel"])
  219. elif major_release == 6:
  220. build_reqs.extend(["python-devel"])
  221. elif major_release == 7:
  222. build_reqs.extend(["python-devel", "systemd-units"])
  223. else:
  224. _abort("Unsupported major release: {0}".format(major_release))
  225. # Install build deps
  226. _run_command(["yum", "-y", "install"] + build_reqs)
  227. # Make the sdist
  228. try:
  229. sdist = _make_sdist(opts, python_bin=python_bin)
  230. except NameError:
  231. sdist = _make_sdist(opts)
  232. # Example tarball names:
  233. # - Git checkout: salt-2014.7.0rc1-1584-g666602e.tar.gz
  234. # - Tagged release: salt-2014.7.0.tar.gz
  235. tarball_re = re.compile(r"^salt-([^-]+)(?:-(\d+)-(g[0-9a-f]+))?\.tar\.gz$")
  236. try:
  237. base, offset, oid = tarball_re.match(os.path.basename(sdist)).groups()
  238. except AttributeError:
  239. _abort("Unable to extract version info from sdist filename '{0}'".format(sdist))
  240. if offset is None:
  241. salt_pkgver = salt_srcver = base
  242. else:
  243. salt_pkgver = ".".join((base, offset, oid))
  244. salt_srcver = "-".join((base, offset, oid))
  245. log.info("salt_pkgver: {0}".format(salt_pkgver))
  246. log.info("salt_srcver: {0}".format(salt_srcver))
  247. # Setup build environment
  248. for build_dir in "BUILD BUILDROOT RPMS SOURCES SPECS SRPMS".split():
  249. path = os.path.join(opts.build_dir, build_dir)
  250. try:
  251. os.makedirs(path)
  252. except OSError:
  253. pass
  254. if not os.path.isdir(path):
  255. _abort("Unable to make directory: {0}".format(path))
  256. # Get sources into place
  257. build_sources_path = os.path.join(opts.build_dir, "SOURCES")
  258. rpm_sources_path = os.path.join(opts.source_dir, "pkg", "rpm")
  259. _move(sdist, build_sources_path)
  260. for src in (
  261. "salt-master",
  262. "salt-syndic",
  263. "salt-minion",
  264. "salt-api",
  265. "salt-master.service",
  266. "salt-syndic.service",
  267. "salt-minion.service",
  268. "salt-api.service",
  269. "README.fedora",
  270. "logrotate.salt",
  271. "salt.bash",
  272. ):
  273. shutil.copy(os.path.join(rpm_sources_path, src), build_sources_path)
  274. # Prepare SPEC file
  275. spec_path = os.path.join(opts.build_dir, "SPECS", "salt.spec")
  276. with open(opts.spec_file, "r") as spec:
  277. spec_lines = spec.read().splitlines()
  278. with open(spec_path, "w") as fp_:
  279. for line in spec_lines:
  280. if line.startswith("%global srcver "):
  281. line = "%global srcver {0}".format(salt_srcver)
  282. elif line.startswith("Version: "):
  283. line = "Version: {0}".format(salt_pkgver)
  284. fp_.write(line + "\n")
  285. # Do the thing
  286. cmd = ["rpmbuild", "-ba"]
  287. cmd.extend(define_opts)
  288. cmd.append(spec_path)
  289. stdout, stderr, rcode = _run_command(cmd)
  290. if rcode != 0:
  291. _abort("Build failed.")
  292. packages = glob.glob(
  293. os.path.join(
  294. opts.build_dir,
  295. "RPMS",
  296. "noarch",
  297. "salt-*{0}*.noarch.rpm".format(salt_pkgver),
  298. )
  299. )
  300. packages.extend(
  301. glob.glob(
  302. os.path.join(
  303. opts.build_dir, "SRPMS", "salt-{0}*.src.rpm".format(salt_pkgver)
  304. )
  305. )
  306. )
  307. return packages
  308. # MAIN
  309. if __name__ == "__main__":
  310. opts = _init()
  311. print(
  312. "Starting {0} build. Progress will be logged to {1}.".format(
  313. opts.platform, opts.log_file
  314. )
  315. )
  316. # Setup logging
  317. log_format = "%(asctime)s.%(msecs)03d %(levelname)s: %(message)s"
  318. log_datefmt = "%H:%M:%S"
  319. log_level = (
  320. LOG_LEVELS[opts.log_level]
  321. if opts.log_level in LOG_LEVELS
  322. else LOG_LEVELS["warning"]
  323. )
  324. logging.basicConfig(
  325. filename=opts.log_file,
  326. format=log_format,
  327. datefmt=log_datefmt,
  328. level=LOG_LEVELS[opts.log_level],
  329. )
  330. if opts.log_level not in LOG_LEVELS:
  331. log.error(
  332. "Invalid log level '{0}', falling back to 'warning'".format(opts.log_level)
  333. )
  334. # Build for the specified platform
  335. if not opts.platform:
  336. _abort("Platform required")
  337. elif opts.platform.lower() == "centos":
  338. artifacts = build_centos(opts)
  339. else:
  340. _abort("Unsupported platform '{0}'".format(opts.platform))
  341. msg = "Build complete. Artifacts will be stored in {0}".format(opts.artifact_dir)
  342. log.info(msg)
  343. print(msg) # pylint: disable=C0325
  344. for artifact in artifacts:
  345. shutil.copy(artifact, opts.artifact_dir)
  346. log.info("Copied {0} to artifact directory".format(artifact))
  347. log.info("Done!")