1 # vi: encoding=utf-8 ts=8 sts=4 sw=4 et
3 from __future__ import print_function
15 from config import config, init_conf
16 from bqueue import B_Queue
32 # *HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*
35 socket.myorigsocket=socket.socket
37 def mysocket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0):
38 s=socket.myorigsocket(family, type, proto)
39 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
42 socket.socket=mysocket
43 # *HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*
45 # this code is duplicated in srpm_builder, but we
46 # might want to handle some cases differently here
49 if r1.kind != 'group' or r2.kind != 'group':
50 raise Exception("non-group requests")
51 pri_diff = util.cmp(r1.priority, r2.priority)
53 return util.cmp(r1.time, r2.time)
56 q.requests.sort(key=util.cmp_to_key(mycmp))
60 def check_skip_build(r, b):
61 src_url = config.control_url + "/srpms/" + r.id + "/skipme"
63 b.log_line("checking if we should skip the build")
66 headers = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
67 req = urllib.request.Request(url=src_url, headers=headers)
68 f = urllib.request.urlopen(req)
70 except urllib.error.HTTPError as error:
72 except urllib.error.URLError as error:
76 except AttributeError:
78 errno = error.reason[0]
80 if errno in [-3, 60, 61, 110, 111]:
81 b.log_line("unable to connect... trying again")
90 src_url = config.control_url + "/srpms/" + r.id + "/" + urllib.parse.quote(b.src_rpm)
91 b.log_line("fetching %s" % src_url)
96 headers = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
97 req = urllib.request.Request(url=src_url, headers=headers)
98 f = urllib.request.urlopen(req)
100 except urllib.error.HTTPError as error:
101 # fail in a way where cron job will retry
102 msg = "unable to fetch url %s, http code: %d" % (src_url, error.code)
104 queue_time = time.time() - r.time
106 if error.code != 404 or (queue_time >= 0 and queue_time < (6 * 60 * 60)):
109 msg = "in queue for more than 6 hours, download failing"
112 except urllib.error.URLError as error:
114 if isinstance(error.args[0], IOError):
115 errno = error.args[0].errno
117 if errno in [-3, 60, 61, 110, 111]:
118 b.log_line("unable to connect to %s... trying again" % (src_url))
122 print("error.errno: %s" % str(error.errno))
123 except Exception as e:
124 print("error.errno: exception %s" % e)
126 print("error.reason %s" % str(error.reason))
127 except Exception as e:
128 print("error.reason exception %s" % e)
131 o = chroot.popen("cat > %s" % b.src_rpm, mode = "w")
134 shutil.copyfileobj(f, o)
136 b.log_line("error: unable to write to `%s': %s" % (b.src_rpm, e))
139 bytes = float(f.headers['content-length'])
142 t = time.time() - start
144 b.log_line("fetched %d bytes" % bytes)
146 b.log_line("fetched %d bytes, %.1f K/s" % (bytes, bytes / 1024.0 / t))
148 def prepare_env(logfile = None):
150 test ! -f /proc/uptime && mount /proc 2>/dev/null
151 test ! -c /dev/full && rm -f /dev/full && mknod -m 666 /dev/full c 1 7
152 test ! -c /dev/null && rm -f /dev/null && mknod -m 666 /dev/null c 1 3
153 test ! -c /dev/random && rm -f /dev/random && mknod -m 644 /dev/random c 1 8
154 test ! -c /dev/urandom && rm -f /dev/urandom && mknod -m 644 /dev/urandom c 1 9
155 test ! -c /dev/zero && rm -f /dev/zero && mknod -m 666 /dev/zero c 1 5
157 # need entry for "/" in mtab, for diskspace() to work in rpm
158 [ -z $(awk '$2 == "/" {print $1; exit}' /etc/mtab) ] && mount -f -t rootfs rootfs /
160 # make neccessary files readable for builder user
161 # TODO: see if they really aren't readable for builder
162 for db in Packages Name Basenames Providename Pubkeys; do
164 test -f $db && chmod a+r $db
167 # try to limit network access for builder account
168 /bin/setfacl -m u:builder:--- /etc/resolv.conf
169 """, 'root', logfile = logfile)
172 packagename = b.get_package_name()
174 # should not really get here
175 b.log_line("error: No .spec not given of malformed: '%s'" % b.spec)
176 res = "FAIL_INTERNAL"
179 status.push("building %s (%s)" % (b.spec, packagename))
180 b.log_line("request from: %s" % r.requester)
182 if check_skip_build(r, b):
183 b.log_line("build skipped due to src builder request")
184 res = "SKIP_REQUESTED"
187 b.log_line("started at: %s" % time.asctime())
189 b.log_line("cleaning up /tmp")
190 chroot.run("rm -rf /tmp/B.*", logfile = b.logfile)
193 b.log_line("installing srpm: %s" % b.src_rpm)
196 install -d %(topdir)s/{BUILD,RPMS};
197 LC_ALL=en_US.UTF-8 rpm -qp --changelog %(src_rpm)s;
198 rpm -Uhv --nodeps %(rpmdefs)s %(src_rpm)s;
201 'topdir' : b.get_topdir(),
202 'rpmdefs' : b.rpmbuild_opts(),
203 'src_rpm' : b.src_rpm
204 }, logfile = b.logfile)
209 b.log_line("error: installing src rpm failed")
210 res = "FAIL_SRPM_INSTALL"
213 chroot.run("set -x; install -m 700 -d %s" % tmpdir, logfile=b.logfile)
214 b.default_target(config.arch)
215 # check for build arch before filling BR
216 cmd = "set -ex; TMPDIR=%(tmpdir)s exec nice -n %(nice)s " \
217 "rpmbuild -bp --short-circuit --nodeps %(rpmdefs)s --define 'prep exit 0' %(topdir)s/%(spec)s" % {
219 'nice' : config.nice,
220 'topdir' : b.get_topdir(),
221 'rpmdefs' : b.rpmbuild_opts(),
224 res = chroot.run(cmd, logfile = b.logfile)
227 b.log_line("error: build arch check (%s) failed" % cmd)
230 if ("no-install-br" not in r.flags) and not install.uninstall_self_conflict(b):
231 res = "FAIL_DEPS_UNINSTALL"
232 if ("no-install-br" not in r.flags) and not install.install_br(r, b):
233 res = "FAIL_DEPS_INSTALL"
235 max_jobs = max(min(int(os.sysconf('SC_NPROCESSORS_ONLN') + 1), config.max_jobs), 1)
237 max_jobs = max(min(config.max_jobs, r.max_jobs), 1)
238 cmd = "set -ex; : build-id: %(r_id)s; TMPDIR=%(tmpdir)s exec nice -n %(nice)s " \
239 "rpmbuild -bb --define '_smp_mflags -j%(max_jobs)d' --define '_make_opts -Otarget' --define '_tld_builder 1' %(rpmdefs)s %(topdir)s/%(spec)s" % {
242 'nice' : config.nice,
243 'rpmdefs' : b.rpmbuild_opts(),
244 'topdir' : b.get_topdir(),
245 'max_jobs' : max_jobs,
248 b.log_line("building RPM using: %s" % cmd)
249 begin_time = time.time()
250 res = chroot.run(cmd, logfile = b.logfile)
251 end_time = time.time()
252 b.log_line("ended at: %s, done in %s" % (time.asctime(), datetime.timedelta(0, end_time - begin_time)))
255 files = util.collect_files(b.logfile, basedir = b.get_topdir())
257 r.chroot_files.extend(files)
259 b.log_line("error: No files produced.")
260 last_section = util.find_last_section(b.logfile)
261 if last_section == None:
264 res = "FAIL_%s" % last_section.upper()
267 # cleanup tmp and build files
270 chmod -R u+rwX %(topdir)s/BUILD;
271 rm -rf %(topdir)s/{tmp,BUILD}
273 'topdir' : b.get_topdir(),
274 }, logfile = b.logfile)
277 util.append_to(b.logfile, l)
280 rpm_cache_dir = config.rpm_cache_dir
281 if "test-build" not in r.flags:
282 # NOTE: copying to cache dir doesn't mean that build failed, so ignore result
283 b.log_line("copy rpm files to cache_dir: %s" % rpm_cache_dir)
285 "cp -f %s %s && poldek --mo=nodiff --mkidxz -s %s/" % \
286 (' '.join(b.files), rpm_cache_dir, rpm_cache_dir),
287 logfile = b.logfile, user = "root"
290 ll("test-build: not copying to " + rpm_cache_dir)
291 ll("Begin-TLD-Builder-Info")
292 if "upgrade" in r.flags:
293 b.upgraded = install.upgrade_from_batch(r, b)
296 ll("End-TLD-Builder-Info")
299 local = r.tmp_dir + os.path.basename(f)
300 chroot.cp(f, outfile = local, rm = True)
303 # cleanup all remains from this build
308 'topdir' : b.get_topdir(),
309 }, logfile = b.logfile)
312 c="file:SRPMS:%s\n" % b.src_rpm
314 c=c + "file:ARCH:%s\n" % os.path.basename(f)
318 if config.gen_upinfo and b.files != [] and 'test-build' not in r.flags:
319 fname = r.tmp_dir + b.src_rpm + ".uploadinfo"
321 f.write(uploadinfo(b))
323 ftp.add(fname, "uploadinfo")
329 def handle_request(r):
332 build.build_all(r, build_rpm)
333 report.send_report(r, is_src = False)
340 f = open("/proc/loadavg")
341 if float(f.readline().split()[2]) > config.max_load:
348 def main_for(builder):
353 q = B_Queue(path.queue_file + "-" + config.builder)
359 req = pick_request(q)
362 # high priority tasks have priority < 0, normal tasks >= 0
363 if req.priority >= 0:
365 # allow only one build in given builder at once
366 if not lock.lock("building-rpm-for-%s" % config.builder, non_block = 1):
370 # not more then job_slots builds at once
372 for slot in range(config.job_slots):
373 if lock.lock("building-rpm-slot-%d" % slot, non_block = 1):
379 # record fact that we got lock for this builder, load balancer
380 # will use it for fair-queuing
381 l = lock.lock("got-lock")
382 f = open(path.got_lock_file, "a")
383 f.write(config.builder + "\n")
387 # be able to avoid locking with very low priority
388 if req.priority > -1000:
391 # allow only one build in given builder at once
392 if not lock.lock("building-high-priority-rpm-for-%s" % config.builder, non_block = 1):
395 msg = "HIGH PRIORITY: "
397 msg += "handling request %s (%d) for %s from %s, priority %s" \
398 % (req.id, req.no, config.builder, req.requester, req.priority)
410 q = B_Queue(path.queue_file + "-" + config.builder)
413 previouslen=len(q.requests)
414 q.requests=list(filter(otherreqs, q.requests))
415 if len(q.requests)<previouslen:
420 if len(sys.argv) < 2:
421 raise Exception("fatal: need to have builder name as first arg")
422 return main_for(sys.argv[1])
424 if __name__ == '__main__':