1 # vi: encoding=utf-8 ts=8 sts=4 sw=4 et
3 from __future__ import print_function
13 from config import config, init_conf
14 from bqueue import B_Queue
29 # *HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*
32 socket.myorigsocket=socket.socket
34 def mysocket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0):
35 s=socket.myorigsocket(family, type, proto)
36 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
39 socket.socket=mysocket
40 # *HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*
42 # this code is duplicated in srpm_builder, but we
43 # might want to handle some cases differently here
46 if r1.kind != 'group' or r2.kind != 'group':
47 raise Exception("non-group requests")
48 pri_diff = cmp(r1.priority, r2.priority)
50 return cmp(r1.time, r2.time)
53 q.requests.sort(key=util.cmp_to_key(mycmp))
57 def check_skip_build(r, b):
58 src_url = config.control_url + "/srpms/" + r.id + "/skipme"
60 b.log_line("checking if we should skip the build")
63 headers = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
64 req = urllib.request.Request(url=src_url, headers=headers)
65 f = urllib.request.urlopen(req)
67 except urllib.error.HTTPError as error:
69 except urllib.error.URLError as error:
73 except AttributeError:
75 errno = error.reason[0]
77 if errno in [-3, 60, 61, 110, 111]:
78 b.log_line("unable to connect... trying again")
87 src_url = config.control_url + "/srpms/" + r.id + "/" + urllib.parse.quote(b.src_rpm)
88 b.log_line("fetching %s" % src_url)
93 headers = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
94 req = urllib.request.Request(url=src_url, headers=headers)
95 f = urllib.request.urlopen(req)
97 except urllib.error.HTTPError as error:
98 # fail in a way where cron job will retry
99 msg = "unable to fetch url %s, http code: %d" % (src_url, error.code)
101 queue_time = time.time() - r.time
103 if error.code != 404 or (queue_time >= 0 and queue_time < (6 * 60 * 60)):
106 msg = "in queue for more than 6 hours, download failing"
109 except urllib.error.URLError as error:
111 if isinstance(error.args[0], IOError):
112 errno = error.args[0].errno
114 if errno in [-3, 60, 61, 110, 111]:
115 b.log_line("unable to connect to %s... trying again" % (src_url))
119 print("error.errno: %s" % str(error.errno))
120 except Exception as e:
121 print("error.errno: exception %s" % e)
123 print("error.reason %s" % str(error.reason))
124 except Exception as e:
125 print("error.reason exception %s" % e)
128 o = chroot.popen("cat > %s" % b.src_rpm, mode = "wb")
131 bytes = util.sendfile(f, o)
133 b.log_line("error: unable to write to `%s': %s" % (b.src_rpm, e))
138 t = time.time() - start
140 b.log_line("fetched %d bytes" % bytes)
142 b.log_line("fetched %d bytes, %.1f K/s" % (bytes, bytes / 1024.0 / t))
144 def prepare_env(logfile = None):
146 test ! -f /proc/uptime && mount /proc 2>/dev/null
147 test ! -c /dev/full && rm -f /dev/full && mknod -m 666 /dev/full c 1 7
148 test ! -c /dev/null && rm -f /dev/null && mknod -m 666 /dev/null c 1 3
149 test ! -c /dev/random && rm -f /dev/random && mknod -m 644 /dev/random c 1 8
150 test ! -c /dev/urandom && rm -f /dev/urandom && mknod -m 644 /dev/urandom c 1 9
151 test ! -c /dev/zero && rm -f /dev/zero && mknod -m 666 /dev/zero c 1 5
153 # need entry for "/" in mtab, for diskspace() to work in rpm
154 [ -z $(awk '$2 == "/" {print $1; exit}' /etc/mtab) ] && mount -f -t rootfs rootfs /
156 # make neccessary files readable for builder user
157 # TODO: see if they really aren't readable for builder
158 for db in Packages Name Basenames Providename Pubkeys; do
160 test -f $db && chmod a+r $db
163 # try to limit network access for builder account
164 /bin/setfacl -m u:builder:--- /etc/resolv.conf
165 """, 'root', logfile = logfile)
168 packagename = b.get_package_name()
170 # should not really get here
171 b.log_line("error: No .spec not given of malformed: '%s'" % b.spec)
172 res = "FAIL_INTERNAL"
175 status.push("building %s (%s)" % (b.spec, packagename))
176 b.log_line("request from: %s" % r.requester)
178 if check_skip_build(r, b):
179 b.log_line("build skipped due to src builder request")
180 res = "SKIP_REQUESTED"
183 b.log_line("started at: %s" % time.asctime())
185 b.log_line("killing old processes on a builder")
186 chroot.run("/bin/kill --verbose -9 -1", logfile = b.logfile)
188 b.log_line("cleaning up /tmp")
189 chroot.run("rm -rf /tmp/B.*", logfile = b.logfile)
192 b.log_line("installing srpm: %s" % b.src_rpm)
195 install -d %(topdir)s/{BUILD,RPMS};
196 LC_ALL=en_US.UTF-8 rpm -qp --changelog %(src_rpm)s;
197 rpm -Uhv --nodeps %(rpmdefs)s %(src_rpm)s;
200 'topdir' : b.get_topdir(),
201 'rpmdefs' : b.rpmbuild_opts(),
202 'src_rpm' : b.src_rpm
203 }, logfile = b.logfile)
208 b.log_line("error: installing src rpm failed")
209 res = "FAIL_SRPM_INSTALL"
212 chroot.run("set -x; install -m 700 -d %s" % tmpdir, logfile=b.logfile)
213 b.default_target(config.arch)
214 # check for build arch before filling BR
215 cmd = "set -ex; TMPDIR=%(tmpdir)s exec nice -n %(nice)s " \
216 "rpmbuild -bp --short-circuit --nodeps %(rpmdefs)s --define 'prep exit 0' %(topdir)s/%(spec)s" % {
218 'nice' : config.nice,
219 'topdir' : b.get_topdir(),
220 'rpmdefs' : b.rpmbuild_opts(),
223 res = chroot.run(cmd, logfile = b.logfile)
226 b.log_line("error: build arch check (%s) failed" % cmd)
229 if ("no-install-br" not in r.flags) and not install.uninstall_self_conflict(b):
230 res = "FAIL_DEPS_UNINSTALL"
231 if ("no-install-br" not in r.flags) and not install.install_br(r, b):
232 res = "FAIL_DEPS_INSTALL"
234 max_jobs = max(min(int(os.sysconf('SC_NPROCESSORS_ONLN') + 1), config.max_jobs), 1)
236 max_jobs = max(min(config.max_jobs, r.max_jobs), 1)
237 cmd = "set -ex; : build-id: %(r_id)s; TMPDIR=%(tmpdir)s exec nice -n %(nice)s " \
238 "rpmbuild -bb --define '_smp_mflags -j%(max_jobs)d' --define '_make_opts -Otarget' --define '_tld_builder 1' %(rpmdefs)s %(topdir)s/%(spec)s" % {
241 'nice' : config.nice,
242 'rpmdefs' : b.rpmbuild_opts(),
243 'topdir' : b.get_topdir(),
244 'max_jobs' : max_jobs,
247 b.log_line("building RPM using: %s" % cmd)
248 begin_time = time.time()
249 res = chroot.run(cmd, logfile = b.logfile)
250 end_time = time.time()
251 b.log_line("ended at: %s, done in %s" % (time.asctime(), datetime.timedelta(0, end_time - begin_time)))
254 files = util.collect_files(b.logfile, basedir = b.get_topdir())
256 r.chroot_files.extend(files)
258 b.log_line("error: No files produced.")
259 last_section = util.find_last_section(b.logfile)
260 if last_section == None:
263 res = "FAIL_%s" % last_section.upper()
266 # cleanup tmp and build files
269 chmod -R u+rwX %(topdir)s/BUILD;
270 rm -rf %(topdir)s/{tmp,BUILD}
272 'topdir' : b.get_topdir(),
273 }, logfile = b.logfile)
276 util.append_to(b.logfile, l)
279 rpm_cache_dir = config.rpm_cache_dir
280 if "test-build" not in r.flags:
281 # NOTE: copying to cache dir doesn't mean that build failed, so ignore result
282 b.log_line("copy rpm files to cache_dir: %s" % rpm_cache_dir)
284 "cp -f %s %s && poldek --mo=nodiff --mkidxz -s %s/" % \
285 (' '.join(b.files), rpm_cache_dir, rpm_cache_dir),
286 logfile = b.logfile, user = "root"
289 ll("test-build: not copying to " + rpm_cache_dir)
290 ll("Begin-TLD-Builder-Info")
291 if "upgrade" in r.flags:
292 b.upgraded = install.upgrade_from_batch(r, b)
295 ll("End-TLD-Builder-Info")
298 local = r.tmp_dir + os.path.basename(f)
299 chroot.cp(f, outfile = local, rm = True)
302 # cleanup all remains from this build
307 'topdir' : b.get_topdir(),
308 }, logfile = b.logfile)
311 c="file:SRPMS:%s\n" % b.src_rpm
313 c=c + "file:ARCH:%s\n" % os.path.basename(f)
317 if config.gen_upinfo and b.files != [] and 'test-build' not in r.flags:
318 fname = r.tmp_dir + b.src_rpm + ".uploadinfo"
320 f.write(uploadinfo(b))
322 ftp.add(fname, "uploadinfo")
328 def handle_request(r):
331 build.build_all(r, build_rpm)
332 report.send_report(r, is_src = False)
339 f = open("/proc/loadavg")
340 if float(f.readline().split()[2]) > config.max_load:
347 def main_for(builder):
352 q = B_Queue(path.queue_file + "-" + config.builder)
358 req = pick_request(q)
361 # high priority tasks have priority < 0, normal tasks >= 0
362 if req.priority >= 0:
364 # allow only one build in given builder at once
365 if not lock.lock("building-rpm-for-%s" % config.builder, non_block = 1):
369 # not more then job_slots builds at once
371 for slot in range(config.job_slots):
372 if lock.lock("building-rpm-slot-%d" % slot, non_block = 1):
378 # record fact that we got lock for this builder, load balancer
379 # will use it for fair-queuing
380 l = lock.lock("got-lock")
381 f = open(path.got_lock_file, "a")
382 f.write(config.builder + "\n")
386 # be able to avoid locking with very low priority
387 if req.priority > -1000:
390 # allow only one build in given builder at once
391 if not lock.lock("building-high-priority-rpm-for-%s" % config.builder, non_block = 1):
394 msg = "HIGH PRIORITY: "
396 msg += "handling request %s (%d) for %s from %s, priority %s" \
397 % (req.id, req.no, config.builder, req.requester, req.priority)
409 q = B_Queue(path.queue_file + "-" + config.builder)
412 previouslen=len(q.requests)
413 q.requests=list(filter(otherreqs, q.requests))
414 if len(q.requests)<previouslen:
419 if len(sys.argv) < 2:
420 raise Exception("fatal: need to have builder name as first arg")
421 return main_for(sys.argv[1])
423 if __name__ == '__main__':