]> git.pld-linux.org Git - projects/pld-builder.new.git/blob - PLD_Builder/rpm_builder.py
fix cleanup, not to delete RPM's before they are copied ;)
[projects/pld-builder.new.git] / PLD_Builder / rpm_builder.py
1 # vi: encoding=utf-8 ts=8 sts=4 sw=4 et
2
3 import sys
4 import os
5 import atexit
6 import time
7 import datetime
8 import string
9 import urllib
10 import urllib2
11
12 from config import config, init_conf
13 from bqueue import B_Queue
14 import lock
15 import util
16 import loop
17 import path
18 import status
19 import log
20 import chroot
21 import ftp
22 import buildlogs
23 import notify
24 import build
25 import report
26 import install
27
28 # *HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*
29 import socket
30
31 socket.myorigsocket=socket.socket
32
33 def mysocket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0):
34     s=socket.myorigsocket(family, type, proto)
35     s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
36     return s
37
38 socket.socket=mysocket
39 # *HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*HACK*
40
41 # this code is duplicated in srpm_builder, but we
42 # might want to handle some cases differently here
43 def pick_request(q):
44     def mycmp(r1, r2):
45         if r1.kind != 'group' or r2.kind != 'group':
46             raise Exception, "non-group requests"
47         pri_diff = cmp(r1.priority, r2.priority)
48         if pri_diff == 0:
49             return cmp(r1.time, r2.time)
50         else:
51             return pri_diff
52     q.requests.sort(mycmp)
53     ret = q.requests[0]
54     return ret
55
56 def check_skip_build(r, b):
57     src_url = config.control_url + "/srpms/" + r.id + "/skipme"
58     good  = False
59     b.log_line("checking if we should skip the build")
60     while not good:
61         try:
62             headers = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
63             req = urllib2.Request(url=src_url, headers=headers)
64             f = urllib2.urlopen(req)
65             good = True
66         except urllib2.HTTPError, error:
67             return False
68         except urllib2.URLError, error:
69             # see errno.h
70             try:
71                 errno = error.errno
72             except AttributeError:
73                 # python 2.4
74                 errno = error.reason[0]
75
76             if errno in [-3, 60, 61, 110, 111]:
77                 b.log_line("unable to connect... trying again")
78                 continue
79             else:
80                 return False
81         f.close()
82         return True
83     return False
84
85 def fetch_src(r, b):
86     src_url = config.control_url + "/srpms/" + r.id + "/" + urllib.quote(b.src_rpm)
87     b.log_line("fetching %s" % src_url)
88     start = time.time()
89     good = False
90     while not good:
91         try:
92             headers = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' }
93             req = urllib2.Request(url=src_url, headers=headers)
94             f = urllib2.urlopen(req)
95             good = True
96         except urllib2.HTTPError, error:
97             # fail in a way where cron job will retry
98             msg = "unable to fetch url %s, http code: %d" % (src_url, error.code)
99             b.log_line(msg)
100             queue_time = time.time() - r.time
101             # 6 hours
102             if error.code != 404 or (queue_time >= 0 and queue_time < (6 * 60 * 60)):
103                 raise IOError, msg
104             else:
105                 msg = "in queue for more than 6 hours, download failing"
106                 b.log_line(msg)
107                 return False
108         except urllib2.URLError, error:
109             # see errno.h
110             try:
111                 errno = error.errno
112             except AttributeError:
113                 # python 2.4
114                 errno = error.reason[0]
115
116             if errno in [-3, 60, 61, 110, 111]:
117                 b.log_line("unable to connect to %s... trying again" % (src_url))
118                 continue
119             else:
120                 raise
121
122     o = chroot.popen("cat > %s" % b.src_rpm, mode = "w")
123
124     try:
125         bytes = util.sendfile(f, o)
126     except IOError, e:
127         b.log_line("error: unable to write to `%s': %s" % (b.src_rpm, e))
128         raise
129
130     f.close()
131     o.close()
132     t = time.time() - start
133     if t == 0:
134         b.log_line("fetched %d bytes" % bytes)
135     else:
136         b.log_line("fetched %d bytes, %.1f K/s" % (bytes, bytes / 1024.0 / t))
137
138 def prepare_env(logfile = None):
139     chroot.run("""
140         test ! -f /proc/uptime && mount /proc 2>/dev/null
141         test ! -c /dev/full && rm -f /dev/full && mknod -m 666 /dev/full c 1 7
142         test ! -c /dev/null && rm -f /dev/null && mknod -m 666 /dev/null c 1 3
143         test ! -c /dev/random && rm -f /dev/random && mknod -m 644 /dev/random c 1 8
144         test ! -c /dev/urandom && rm -f /dev/urandom && mknod -m 644 /dev/urandom c 1 9
145         test ! -c /dev/zero && rm -f /dev/zero && mknod -m 666 /dev/zero c 1 5
146
147         # need entry for "/" in mtab, for diskspace() to work in rpm
148         [ -z $(awk '$2 == "/" {print $1; exit}' /etc/mtab) ] && mount -f -t rootfs rootfs /
149
150         # make neccessary files readable for builder user
151         # TODO: see if they really aren't readable for builder
152         for db in Packages Name Basenames Providename Pubkeys; do
153             db=/var/lib/rpm/$db
154             test -f $db && chmod a+r $db
155         done
156
157         # try to limit network access for builder account
158         /bin/setfacl -m u:builder:--- /etc/resolv.conf
159     """, 'root', logfile = logfile)
160
161 def build_rpm(r, b):
162     packagename = b.get_package_name()
163     if not packagename:
164         # should not really get here
165         b.log_line("error: No .spec not given of malformed: '%s'" % b.spec)
166         res = "FAIL_INTERNAL"
167         return res
168
169     status.push("building %s (%s)" % (b.spec, packagename))
170     b.log_line("request from: %s" % r.requester)
171
172     if check_skip_build(r, b):
173         b.log_line("build skipped due to src builder request")
174         res = "SKIP_REQUESTED"
175         return res
176
177     b.log_line("started at: %s" % time.asctime())
178     fetch_src(r, b)
179     b.log_line("installing srpm: %s" % b.src_rpm)
180     res = chroot.run("""
181         set -ex;
182         install -d %(topdir)s/{BUILD,RPMS};
183         rpm -Uhv --nodeps %(rpmdefs)s %(src_rpm)s;
184         rm -f %(src_rpm)s;
185     """ % {
186         'topdir' : b._topdir,
187         'rpmdefs' : b.rpmbuild_opts(),
188         'src_rpm' : b.src_rpm
189     }, logfile = b.logfile)
190     b.files = []
191
192     tmpdir = b.tmpdir()
193     if res:
194         b.log_line("error: installing src rpm failed")
195         res = "FAIL_SRPM_INSTALL"
196     else:
197         prepare_env()
198         chroot.run("install -m 700 -d %s" % tmpdir)
199
200         b.default_target(config.arch)
201         # check for build arch before filling BR
202         cmd = "set -ex; TMPDIR=%(tmpdir)s exec nice -n %(nice)s " \
203             "rpmbuild -bp --short-circuit --nodeps %(rpmdefs)s --define 'prep exit 0' %(topdir)s/%(spec)s" % {
204             'tmpdir': tmpdir,
205             'nice' : config.nice,
206             'topdir' : b._topdir,
207             'rpmdefs' : b.rpmbuild_opts(),
208             'spec': b.spec,
209         }
210         res = chroot.run(cmd, logfile = b.logfile)
211         if res:
212             res = "UNSUPP"
213             b.log_line("error: build arch check (%s) failed" % cmd)
214
215         if not res:
216             if ("no-install-br" not in r.flags) and not install.uninstall_self_conflict(b):
217                 res = "FAIL_DEPS_UNINSTALL"
218             if ("no-install-br" not in r.flags) and not install.install_br(r, b):
219                 res = "FAIL_DEPS_INSTALL"
220             if not res:
221                 max_jobs = max(min(int(os.sysconf('SC_NPROCESSORS_ONLN') + 1), config.max_jobs), 1)
222                 if r.max_jobs > 0:
223                     max_jobs = max(min(config.max_jobs, r.max_jobs), 1)
224                 cmd = "set -ex; : build-id: %(r_id)s; TMPDIR=%(tmpdir)s exec nice -n %(nice)s " \
225                     "rpmbuild -bb --define '_smp_mflags -j%(max_jobs)d' %(rpmdefs)s %(topdir)s/%(spec)s" % {
226                     'r_id' : r.id,
227                     'tmpdir': tmpdir,
228                     'nice' : config.nice,
229                     'rpmdefs' : b.rpmbuild_opts(),
230                     'topdir' : b._topdir,
231                     'max_jobs' : max_jobs,
232                     'spec': b.spec,
233                 }
234                 b.log_line("building RPM using: %s" % cmd)
235                 begin_time = time.time()
236                 res = chroot.run(cmd, logfile = b.logfile)
237                 end_time = time.time()
238                 b.log_line("ended at: %s, done in %s" % (time.asctime(), datetime.timedelta(0, end_time - begin_time)))
239                 if res:
240                     res = "FAIL"
241                 files = util.collect_files(b.logfile, basedir = b._topdir)
242                 if len(files) > 0:
243                     r.chroot_files.extend(files)
244                 else:
245                     b.log_line("error: No files produced.")
246                     last_section = util.find_last_section(b.logfile)
247                     if last_section == None:
248                         res = "FAIL"
249                     else:
250                         res = "FAIL_%s" % last_section.upper()
251                 b.files = files
252
253     # cleanup tmp and build files
254     chroot.run("""
255         set -ex;
256         chmod -R u+rwX %(topdir)s/BUILD;
257         rm -rf %(topdir)s/{tmp,BUILD}
258     """ % {
259         'topdir' : b._topdir,
260     }, logfile = b.logfile)
261
262     def ll(l):
263         util.append_to(b.logfile, l)
264
265     if b.files != []:
266         rpm_cache_dir = config.rpm_cache_dir
267         if "test-build" not in r.flags:
268             # NOTE: copying to cache dir doesn't mean that build failed, so ignore result
269             b.log_line("copy rpm files to cache_dir: %s" % rpm_cache_dir)
270             chroot.run(
271                     "cp -f %s %s && poldek --mo=nodiff --mkidxz -s %s/" % \
272                         (string.join(b.files), rpm_cache_dir, rpm_cache_dir),
273                      logfile = b.logfile, user = "root"
274             )
275         else:
276             ll("test-build: not copying to " + rpm_cache_dir)
277         ll("Begin-PLD-Builder-Info")
278         if "upgrade" in r.flags:
279             b.upgraded = install.upgrade_from_batch(r, b)
280         else:
281             ll("not upgrading")
282         ll("End-PLD-Builder-Info")
283
284     for f in b.files:
285         local = r.tmp_dir + os.path.basename(f)
286         chroot.cp(f, outfile = local, rm = True)
287         ftp.add(local)
288
289     # cleanup all remains from this build
290     chroot.run("""
291         set -ex;
292         rm -rf %(topdir)s;
293     """ % {
294         'topdir' : b._topdir,
295     }, logfile = b.logfile)
296
297     def uploadinfo(b):
298         c="file:SRPMS:%s\n" % b.src_rpm
299         for f in b.files:
300             c=c + "file:ARCH:%s\n" % os.path.basename(f)
301         c=c + "END\n"
302         return c
303
304     if config.gen_upinfo and b.files != [] and 'test-build' not in r.flags:
305         fname = r.tmp_dir + b.src_rpm + ".uploadinfo"
306         f = open(fname, "w")
307         f.write(uploadinfo(b))
308         f.close()
309         ftp.add(fname, "uploadinfo")
310
311     status.pop()
312
313     return res
314
315 def handle_request(r):
316     ftp.init(r)
317     buildlogs.init(r)
318     build.build_all(r, build_rpm)
319     report.send_report(r, is_src = False)
320     ftp.flush()
321     notify.send(r)
322
323 def check_load():
324     do_exit = 0
325     try:
326         f = open("/proc/loadavg")
327         if float(string.split(f.readline())[2]) > config.max_load:
328             do_exit = 1
329     except:
330         pass
331     if do_exit:
332         sys.exit(0)
333
334 def main_for(builder):
335     msg = ""
336
337     init_conf(builder)
338
339     q = B_Queue(path.queue_file + "-" + config.builder)
340     q.lock(0)
341     q.read()
342     if q.requests == []:
343         q.unlock()
344         return
345     req = pick_request(q)
346     q.unlock()
347
348     # high priority tasks have priority < 0, normal tasks >= 0
349     if req.priority >= 0:
350
351         # allow only one build in given builder at once
352         if not lock.lock("building-rpm-for-%s" % config.builder, non_block = 1):
353             return
354         # don't kill server
355         check_load()
356         # not more then job_slots builds at once
357         locked = 0
358         for slot in range(config.job_slots):
359             if lock.lock("building-rpm-slot-%d" % slot, non_block = 1):
360                 locked = 1
361                 break
362         if not locked:
363             return
364
365         # record fact that we got lock for this builder, load balancer
366         # will use it for fair-queuing
367         l = lock.lock("got-lock")
368         f = open(path.got_lock_file, "a")
369         f.write(config.builder + "\n")
370         f.close()
371         l.close()
372     else:
373         msg = "HIGH PRIORITY: "
374
375     msg += "handling request %s (%d) for %s from %s, priority %s" \
376             % (req.id, req.no, config.builder, req.requester, req.priority)
377     log.notice(msg)
378     status.push(msg)
379     handle_request(req)
380     status.pop()
381
382     def otherreqs(r):
383         if r.no==req.no:
384             return False
385         else:
386             return True
387
388     q = B_Queue(path.queue_file + "-" + config.builder)
389     q.lock(0)
390     q.read()
391     previouslen=len(q.requests)
392     q.requests=filter(otherreqs, q.requests)
393     if len(q.requests)<previouslen:
394         q.write()
395     q.unlock()
396
397 def main():
398     if len(sys.argv) < 2:
399         raise Exception, "fatal: need to have builder name as first arg"
400     return main_for(sys.argv[1])
401
402 if __name__ == '__main__':
403     loop.run_loop(main)
This page took 0.119624 seconds and 4 git commands to generate.