You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

gbuild 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #!/usr/bin/ruby
  2. require 'optparse'
  3. require 'yaml'
  4. require 'fileutils'
  5. require 'pathname'
  6. @options = {:num_procs => 2, :memory => 2000}
  7. @bitness = {
  8. 'i386' => 32,
  9. 'amd64' => 64,
  10. }
  11. @arches = {
  12. 'i386' => 'i386',
  13. 'amd64' => 'x86_64',
  14. }
  15. def system!(cmd)
  16. system(cmd) or raise "failed to run #{cmd}"
  17. end
  18. def sanitize(str, where)
  19. raise "unsanitary string in #{where}" if (str =~ /[^\w.-]/)
  20. str
  21. end
  22. def sanitize_path(str, where)
  23. raise "unsanitary string in #{where}" if (str =~ /[^@\w\/.:+-]/)
  24. str
  25. end
  26. def info(str)
  27. puts str unless @options[:quiet]
  28. end
  29. def build_one_configuration(suite, arch, build_desc)
  30. FileUtils.rm_f("var/build.log")
  31. bits = @bitness[arch] or raise "unknown architecture ${arch}"
  32. if ENV["USE_LXC"]
  33. ENV["LXC_ARCH"] = arch
  34. ENV["LXC_SUITE"] = suite
  35. end
  36. suitearch = "#{suite}-#{arch}"
  37. info "Stopping target if it is up"
  38. system "stop-target"
  39. sleep 1
  40. unless @options[:skip_image]
  41. info "Making a new image copy"
  42. system! "make-clean-vm --suite #{suite} --arch #{arch}"
  43. end
  44. info "Starting target"
  45. system! "start-target #{bits} #{suitearch}&"
  46. $stdout.write "Checking if target is up"
  47. (1..30).each do
  48. system "on-target true 2> /dev/null" and break
  49. sleep 2
  50. $stdout.write '.'
  51. end
  52. info ''
  53. system! "on-target true"
  54. system! "on-target -u root tee -a /etc/sudoers.d/#{ENV['DISTRO'] || 'ubuntu'} > /dev/null << EOF
  55. %#{ENV['DISTRO'] || 'ubuntu'} ALL=(ALL) NOPASSWD: ALL
  56. EOF" if build_desc["sudo"] and @options[:allow_sudo]
  57. info "Preparing build environment"
  58. system! "on-target setarch #{@arches[arch]} bash < target-bin/init-build.sh"
  59. build_desc["files"].each do |filename|
  60. filename = sanitize(filename, "files section")
  61. system! "copy-to-target #{@quiet_flag} inputs/#{filename} build/"
  62. end
  63. if build_desc["enable_cache"]
  64. if File.directory?("cache/#{build_desc["name"]}")
  65. system! "copy-to-target #{@quiet_flag} cache/#{build_desc["name"]}/ cache/"
  66. end
  67. if File.directory?("cache/common")
  68. system! "copy-to-target #{@quiet_flag} cache/common/ cache/"
  69. end
  70. end
  71. info "Updating apt-get repository (log in var/install.log)"
  72. system! "on-target -u root apt-get update > var/install.log 2>&1"
  73. info "Installing additional packages (log in var/install.log)"
  74. system! "on-target -u root -e DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends -y install #{build_desc["packages"].join(" ")} > var/install.log 2>&1"
  75. if @options[:upgrade] || system("on-target -u root '[ ! -e /var/cache/gitian/initial-upgrade ]'")
  76. info "Upgrading system, may take a while"
  77. system! "on-target -u root bash < target-bin/upgrade-system.sh > var/install.log 2>&1"
  78. end
  79. info "Creating package manifest"
  80. system! "on-target -u root bash < target-bin/grab-packages.sh > var/base-#{suitearch}.manifest"
  81. info "Creating build script (var/build-script)"
  82. File.open("var/build-script", "w") do |script|
  83. script.puts "#!/bin/bash"
  84. script.puts "set -e"
  85. script.puts "export LANG='en_US.UTF-8'"
  86. script.puts "export LC_ALL='en_US.UTF-8'"
  87. script.puts "umask 002"
  88. script.puts "export OUTDIR=$HOME/out"
  89. script.puts "GBUILD_BITS=#{bits}"
  90. if build_desc["enable_cache"]
  91. script.puts "GBUILD_CACHE_ENABLED=1"
  92. script.puts "GBUILD_PACKAGE_CACHE=$HOME/cache/#{build_desc["name"]}"
  93. script.puts "GBUILD_COMMON_CACHE=$HOME/cache/common"
  94. end
  95. script.puts "MAKEOPTS=(-j#{@options[:num_procs]})"
  96. script.puts
  97. author_date = nil
  98. build_desc["remotes"].each do |remote|
  99. dir = sanitize(remote["dir"], remote["dir"])
  100. author_date = `cd inputs/#{dir} && git log --format=@%at -1 | date +"%F %T" -u -f -`.strip
  101. raise "error looking up author date in #{dir}" unless $?.exitstatus == 0
  102. system! "copy-to-target #{@quiet_flag} inputs/#{dir} build/"
  103. script.puts "(cd build/#{dir} && git reset -q --hard && git clean -q -f -d)"
  104. end
  105. script.puts
  106. ref_datetime = build_desc["reference_datetime"] || author_date
  107. (ref_date, ref_time) = ref_datetime.split
  108. script.puts "REFERENCE_DATETIME='#{ref_datetime}'"
  109. script.puts "REFERENCE_DATE='#{ref_date}'"
  110. script.puts "REFERENCE_TIME='#{ref_time}'"
  111. script.puts
  112. script.puts "cd build"
  113. script.puts build_desc["script"]
  114. end
  115. info "Running build script (log in var/build.log)"
  116. system! "on-target setarch #{@arches[arch]} bash -x < var/build-script > var/build.log 2>&1"
  117. end
  118. ################################
  119. OptionParser.new do |opts|
  120. opts.banner = "Usage: build [options] <build-description>.yml"
  121. opts.on("--allow-sudo", "override SECURITY on the target VM and allow the use of sudo with no password for the default user") do |v|
  122. @options[:allow_sudo] = v
  123. end
  124. opts.on("-i", "--skip-image", "reuse current target image") do |v|
  125. @options[:skip_image] = v
  126. end
  127. opts.on("--upgrade", "upgrade guest with latest packages") do |v|
  128. @options[:upgrade] = v
  129. end
  130. opts.on("-q", "--quiet", "be quiet") do |v|
  131. @options[:quiet] = v
  132. end
  133. opts.on("-j PROCS", "--num-make PROCS", "number of processes to use") do |v|
  134. @options[:num_procs] = v
  135. end
  136. opts.on("-m MEM", "--memory MEM", "memory to allocate in MiB") do |v|
  137. @options[:memory] = v
  138. end
  139. opts.on("-c PAIRS", "--commit PAIRS", "comma separated list of DIRECTORY=COMMIT pairs") do |v|
  140. @options[:commit] = v
  141. end
  142. opts.on("-u PAIRS", "--url PAIRS", "comma separated list of DIRECTORY=URL pairs") do |v|
  143. @options[:url] = v
  144. end
  145. opts.on("-o", "--cache-read-only", "only use existing cache files, do not update them") do |v|
  146. @options[:cache_ro] = v
  147. end
  148. end.parse!
  149. if !ENV["USE_LXC"] and !File.exist?("/dev/kvm")
  150. $stderr.puts "\n************* WARNING: kvm not loaded, this will probably not work out\n\n"
  151. end
  152. base_dir = Pathname.new(__FILE__).expand_path.dirname.parent
  153. libexec_dir = base_dir + 'libexec'
  154. ENV['PATH'] = libexec_dir.to_s + ":" + ENV['PATH']
  155. ENV['GITIAN_BASE'] = base_dir.to_s
  156. ENV['NPROCS'] = @options[:num_procs].to_s
  157. ENV['VMEM'] = @options[:memory].to_s
  158. @quiet_flag = @options[:quiet] ? "-q" : ""
  159. build_desc_file = ARGV.shift or raise "must supply YAML build description file"
  160. build_desc = YAML.load_file(build_desc_file)
  161. in_sums = []
  162. build_dir = 'build'
  163. result_dir = 'result'
  164. cache_dir = 'cache'
  165. enable_cache = build_desc["enable_cache"]
  166. FileUtils.rm_rf(build_dir)
  167. FileUtils.mkdir(build_dir)
  168. FileUtils.mkdir_p(result_dir)
  169. package_name = build_desc["name"] or raise "must supply name"
  170. package_name = sanitize(package_name, "package name")
  171. if enable_cache
  172. FileUtils.mkdir_p(File.join(cache_dir, "common"))
  173. FileUtils.mkdir_p(File.join(cache_dir, package_name))
  174. end
  175. distro = build_desc["distro"] || "ubuntu"
  176. suites = build_desc["suites"] or raise "must supply suites"
  177. archs = build_desc["architectures"] or raise "must supply architectures"
  178. build_desc["reference_datetime"] or build_desc["remotes"].size > 0 or raise "must supply `reference_datetime` or `remotes`"
  179. ENV['DISTRO'] = distro
  180. desc_sum = `sha256sum #{build_desc_file}`
  181. desc_sum = desc_sum.sub(build_desc_file, "#{package_name}-desc.yml")
  182. in_sums << desc_sum
  183. build_desc["files"].each do |filename|
  184. filename = sanitize(filename, "files section")
  185. in_sums << `cd inputs && sha256sum #{filename}`
  186. end
  187. commits = {}
  188. if @options[:commit]
  189. @options[:commit].split(',').each do |pair|
  190. (dir, commit) = pair.split('=')
  191. commits[dir] = commit
  192. end
  193. end
  194. urls = {}
  195. if @options[:url]
  196. @options[:url].split(',').each do |pair|
  197. (dir, url) = pair.split('=')
  198. urls[dir] = url
  199. end
  200. end
  201. build_desc["remotes"].each do |remote|
  202. if !remote["commit"]
  203. remote["commit"] = commits[remote["dir"]]
  204. raise "must specify a commit for directory #{remote["dir"]}" unless remote["commit"]
  205. end
  206. if urls[remote["dir"]]
  207. remote["url"] = urls[remote["dir"]]
  208. end
  209. dir = sanitize(remote["dir"], remote["dir"])
  210. unless File.exist?("inputs/#{dir}")
  211. system!("git init inputs/#{dir}")
  212. end
  213. system!("cd inputs/#{dir} && git fetch --update-head-ok #{sanitize_path(remote["url"], remote["url"])} +refs/tags/*:refs/tags/* +refs/heads/*:refs/heads/*")
  214. commit = sanitize(remote["commit"], remote["commit"])
  215. commit = `cd inputs/#{dir} && git log --format=%H -1 #{commit}`.strip
  216. raise "error looking up commit for tag #{remote["commit"]}" unless $?.exitstatus == 0
  217. system!("cd inputs/#{dir} && git checkout -q #{commit}")
  218. in_sums << "git:#{commit} #{dir}"
  219. end
  220. base_manifests = YAML::Omap.new
  221. suites.each do |suite|
  222. suite = sanitize(suite, "suite")
  223. archs.each do |arch|
  224. info "--- Building for #{suite} #{arch} ---"
  225. arch = sanitize(arch, "architecture")
  226. # Build!
  227. build_one_configuration(suite, arch, build_desc)
  228. info "Grabbing results from target"
  229. system! "copy-from-target #{@quiet_flag} out #{build_dir}"
  230. if enable_cache && !@options[:cache_ro]
  231. info "Grabbing cache from target"
  232. system! "copy-from-target #{@quiet_flag} cache/#{package_name}/ #{cache_dir}"
  233. system! "copy-from-target #{@quiet_flag} cache/common/ #{cache_dir}"
  234. end
  235. base_manifest = File.read("var/base-#{suite}-#{arch}.manifest")
  236. base_manifests["#{suite}-#{arch}"] = base_manifest
  237. end
  238. end
  239. out_dir = File.join(build_dir, "out")
  240. out_sums = {}
  241. cache_common_dir = File.join(cache_dir, "common")
  242. cache_package_dir = File.join(cache_dir, "#{package_name}")
  243. cache_common_sums = {}
  244. cache_package_sums = {}
  245. info "Generating report"
  246. Dir.glob(File.join(out_dir, '**', '*'), File::FNM_DOTMATCH).sort.each do |file_in_out|
  247. next if File.directory?(file_in_out)
  248. file = file_in_out.sub(out_dir + File::SEPARATOR, '')
  249. file = sanitize_path(file, file_in_out)
  250. out_sums[file] = `cd #{out_dir} && sha256sum #{file}`
  251. raise "failed to sum #{file}" unless $? == 0
  252. puts out_sums[file] unless @options[:quiet]
  253. end
  254. if enable_cache
  255. Dir.glob(File.join(cache_common_dir, '**', '*'), File::FNM_DOTMATCH).sort.each do |file_in_out|
  256. next if File.directory?(file_in_out)
  257. file = file_in_out.sub(cache_common_dir + File::SEPARATOR, '')
  258. file = sanitize_path(file, file_in_out)
  259. cache_common_sums[file] = `cd #{cache_common_dir} && sha256sum #{file}`
  260. raise "failed to sum #{file}" unless $? == 0
  261. end
  262. Dir.glob(File.join(cache_package_dir, '**', '*'), File::FNM_DOTMATCH).sort.each do |file_in_out|
  263. next if File.directory?(file_in_out)
  264. file = file_in_out.sub(cache_package_dir + File::SEPARATOR, '')
  265. file = sanitize_path(file, file_in_out)
  266. cache_package_sums[file] = `cd #{cache_package_dir} && sha256sum #{file}`
  267. raise "failed to sum #{file}" unless $? == 0
  268. end
  269. end
  270. out_manifest = out_sums.keys.sort.map { |key| out_sums[key] }.join('')
  271. in_manifest = in_sums.join('')
  272. cache_common_manifest = cache_common_sums.keys.sort.map { |key| cache_common_sums[key] }.join('')
  273. cache_package_manifest = cache_package_sums.keys.sort.map { |key| cache_package_sums[key] }.join('')
  274. # Use Omap to keep result deterministic
  275. report = YAML::Omap[
  276. 'out_manifest', out_manifest,
  277. 'in_manifest', in_manifest,
  278. 'base_manifests', base_manifests,
  279. 'cache_common_manifest', cache_common_manifest,
  280. 'cache_package_manifest', cache_package_manifest,
  281. ]
  282. result_file = "#{package_name}-res.yml"
  283. File.open(File.join(result_dir, result_file), "w") do |io|
  284. io.write report.to_yaml
  285. end
  286. system!("cd #{result_dir} && sha256sum #{result_file}") unless @options[:quiet]
  287. info "Done."