1 # vi: encoding=utf-8 ts=8 sts=4 sw=4 et
3 from xml.dom.minidom import *
4 from datetime import datetime
7 import xml.sax.saxutils
18 from config import config
20 __all__ = ['parse_request', 'parse_requests']
24 for n in e.childNodes:
25 if n.nodeType != Element.TEXT_NODE:
26 log.panic("xml: text expected in <%s>, got %d" % (e.nodeName, n.nodeType))
30 def attr(e, a, default = None):
32 return e.attributes[a].value
39 return xml.sax.saxutils.escape(s)
41 # return timestamp with timezone information
42 # so we could parse it in javascript
44 # as strftime %z is unofficial, and does not work, need to make it numeric ourselves
45 date = time.strftime("%a %b %d %Y %H:%M:%S", time.localtime(t))
46 # NOTE: the altzone is showing CURRENT timezone, not what the "t" reflects
47 # NOTE: when DST is off timezone gets it right, altzone not
49 tzoffset = time.altzone
51 tzoffset = time.timezone
52 tz = '%+05d' % (-tzoffset / 3600 * 100)
53 return date + ' ' + tz
55 # return date in iso8601 format
56 def iso8601(ts, timezone='UTC'):
57 tz = pytz.timezone(timezone)
58 dt = datetime.fromtimestamp(ts, tz)
62 return e.nodeType == Element.TEXT_NODE and string.strip(e.nodeValue) == ""
65 def __init__(self, e):
68 self.id = attr(e, "id")
69 self.no = int(attr(e, "no"))
71 self.time = time.time()
74 self.requester_email = ""
75 self.flags = string.split(attr(e, "flags", ""))
76 for c in e.childNodes:
77 if is_blank(c): continue
79 if c.nodeType != Element.ELEMENT_NODE:
80 log.panic("xml: evil group child %d" % c.nodeType)
81 if c.nodeName == "batch":
82 self.batches.append(Batch(c))
83 elif c.nodeName == "requester":
84 self.requester = text(c)
85 self.requester_email = attr(c, "email", "")
86 elif c.nodeName == "priority":
87 self.priority = int(text(c))
88 elif c.nodeName == "time":
89 self.time = int(text(c))
90 elif c.nodeName == "maxjobs":
91 self.max_jobs = int(text(c))
93 log.panic("xml: evil group child (%s)" % c.nodeName)
94 # note that we also check that group is sorted WRT deps
96 for b in self.batches:
99 for dep in b.depends_on:
102 if id(m[dep]) != id(b):
105 log.panic("xml: dependency not found in group")
107 if self.requester_email == "" and self.requester != "":
108 self.requester_email = acl.user(self.requester).mail_to()
111 f.write("group: %d (id=%s pri=%d)\n" % (self.no, self.id, self.priority))
112 f.write(" from: %s\n" % self.requester)
113 f.write(" flags: %s\n" % string.join(self.flags))
114 f.write(" time: %s\n" % time.asctime(time.localtime(self.time)))
115 for b in self.batches:
119 # return structure usable for json encoding
122 for b in self.batches:
123 batches.append(b.dump_json())
129 requester=self.requester,
130 priority=self.priority,
131 max_jobs=self.max_jobs,
136 def dump_html(self, f):
138 "<div id=\"%(no)d\" class=\"request %(flags)s\">\n"
139 "<a href=\"#%(no)d\">%(no)d</a>. "
140 "<time class=\"timeago\" datetime=\"%(datetime)s\">%(time)s</time> "
141 "from <b class=requester>%(requester)s</b> "
142 "<small>%(id)s, prio=%(priority)d, jobs=%(max_jobs)d, %(flags)s</small>\n"
145 'id': '<a href="srpms/%(id)s">%(id)s</a>' % {'id': self.id},
146 'time': escape(tzdate(self.time)),
147 'datetime': escape(iso8601(self.time)),
148 'requester': escape(self.requester),
149 'priority': self.priority,
150 'max_jobs': self.max_jobs,
151 'flags': string.join(self.flags)
154 for b in self.batches:
155 b.dump_html(f, self.id)
159 def write_to(self, f):
161 <group id="%s" no="%d" flags="%s">
162 <requester email='%s'>%s</requester>
164 <priority>%d</priority>
165 <maxjobs>%d</maxjobs>\n""" % (self.id, self.no, string.join(self.flags),
166 escape(self.requester_email), escape(self.requester),
167 self.time, self.priority, self.max_jobs))
168 for b in self.batches:
170 f.write(" </group>\n\n")
174 for b in self.batches:
182 def __init__(self, e):
183 self.bconds_with = []
184 self.bconds_without = []
186 self.builders_status = {}
187 self.builders_status_time = {}
188 self.builders_status_buildtime = {}
197 self.command_flags = []
200 self.b_id = attr(e, "id")
201 self.depends_on = string.split(attr(e, "depends-on"))
208 def get_topdir(self):
209 if not self.__topdir:
210 self.__topdir = tempfile.mkdtemp(prefix='B.', dir='/tmp')
213 def parse_xml(self, e):
214 for c in e.childNodes:
215 if is_blank(c): continue
217 if c.nodeType != Element.ELEMENT_NODE:
218 log.panic("xml: evil batch child %d" % c.nodeType)
219 if c.nodeName == "src-rpm":
220 self.src_rpm = text(c)
221 elif c.nodeName == "spec":
222 # normalize specname, specname is used as buildlog and we don't
223 # want to be exposed to directory traversal attacks
224 self.spec = text(c).split('/')[-1]
225 elif c.nodeName == "command":
226 self.spec = "COMMAND"
227 self.command = text(c).strip()
228 self.command_flags = string.split(attr(c, "flags", ""))
229 elif c.nodeName == "info":
231 elif c.nodeName == "kernel":
232 self.kernel = text(c)
233 elif c.nodeName == "define":
234 define = attr(c, "name")
235 self.defines[define] = text(c)
236 elif c.nodeName == "target":
237 self.target.append(text(c))
238 elif c.nodeName == "skip":
239 self.skip.append(text(c))
240 elif c.nodeName == "branch":
241 self.branch = text(c)
242 elif c.nodeName == "builder":
244 self.builders.append(key)
245 self.builders_status[key] = attr(c, "status", "?")
246 self.builders_status_time[key] = attr(c, "time", "0")
247 self.builders_status_buildtime[key] = "0" #attr(c, "buildtime", "0")
248 elif c.nodeName == "with":
249 self.bconds_with.append(text(c))
250 elif c.nodeName == "without":
251 self.bconds_without.append(text(c))
253 log.panic("xml: evil batch child (%s)" % c.nodeName)
255 def get_package_name(self):
256 if len(self.spec) <= 5:
258 return self.spec[:-5]
262 return tmpdir for this batch job building
264 # it's better to have TMPDIR and BUILD dir on same partition:
265 # + /usr/bin/bzip2 -dc /home/services/builder/rpm/packages/kernel/patch-2.6.27.61.bz2
266 # patch: **** Can't rename file /tmp/B.a1b1d3/poKWwRlp to drivers/scsi/hosts.c : No such file or directory
267 path = os.path.join(self.get_topdir(), 'BUILD', 'tmp')
272 for b in self.builders:
273 s = self.builders_status[b]
274 if not s.startswith("OK") and not s.startswith("SKIP") and not s.startswith("UNSUPP") and not s.startswith("FAIL"):
279 f.write(" batch: %s/%s\n" % (self.src_rpm, self.spec))
280 f.write(" info: %s\n" % self.info)
281 f.write(" kernel: %s\n" % self.kernel)
282 f.write(" defines: %s\n" % self.defines_string())
283 f.write(" target: %s\n" % self.target_string())
284 f.write(" branch: %s\n" % self.branch)
285 f.write(" bconds: %s\n" % self.bconds_string())
287 for b in self.builders:
288 builders.append("%s:%s" % (b, self.builders_status[b]))
289 f.write(" builders: %s\n" % string.join(builders))
291 def is_command(self):
292 return self.command != ""
294 # return structure usable for json encoding
297 command=self.command,
298 command_flags=self.command_flags,
302 package=self.spec[:-5],
303 src_rpm=self.src_rpm,
305 bconds_with=self.bconds_with,
306 bconds_without=self.bconds_without,
310 defines=self.defines,
312 builders=self.builders,
313 builders_status=self.builders_status,
314 builders_status_time=self.builders_status_time,
315 builders_status_buildtime=self.builders_status_buildtime,
318 def dump_html(self, f, rid):
320 if self.is_command():
321 desc = "SH: <pre>%s</pre> flags: [%s]" % (self.command, ' '.join(self.command_flags))
323 package_url = "http://git.pld-linux.org/gitweb.cgi?p=packages/%(package)s.git;f=%(spec)s;h=%(branch)s;a=shortlog" % {
324 'spec': urllib.quote(self.spec),
325 'branch': urllib.quote(self.branch),
326 'package': urllib.quote(self.spec[:-5]),
328 desc = "%(src_rpm)s (<a href=\"%(package_url)s\">%(spec)s -r %(branch)s</a>%(rpmopts)s)" % {
329 'src_rpm': self.src_rpm,
331 'branch': self.branch,
332 'rpmopts': self.bconds_string() + self.kernel_string() + self.target_string() + self.defines_string(),
333 'package_url': package_url,
335 f.write("%s <small>[" % desc)
337 for b in self.builders:
338 s = self.builders_status[b]
339 if s.startswith("OK"):
341 elif s.startswith("FAIL"):
343 elif s.startswith("SKIP"):
345 elif s.startswith("UNSUPP"):
351 if (s.startswith("OK") or s.startswith("SKIP") or s.startswith("UNSUPP") or s.startswith("FAIL")) and len(self.spec) > 5:
352 if self.is_command():
355 bl_name = self.spec[:len(self.spec)-5]
356 lin_ar = b.replace('noauto-','')
357 path = "/%s/%s/%s,%s.bz2" % (lin_ar.replace('-','/'), s, bl_name, rid)
359 if s.startswith("OK"):
361 bld = lin_ar.split('-')
362 tree_name = '-'.join(bld[:-1])
363 tree_arch = '-'.join(bld[-1:])
364 link_pre = "<a href=\"%s/index.php?dist=%s&arch=%s&ok=%d&name=%s&id=%s&action=tail\">" \
365 % (config.buildlogs, urllib.quote(tree_name), urllib.quote(tree_arch), is_ok, urllib.quote(bl_name), urllib.quote(rid))
371 return time.asctime(time.localtime(t))
375 tooltip = "last update: %(time)s\nbuild time: %(buildtime)s" % {
376 'time' : ftime(self.builders_status_time[b]),
377 'buildtime' : ftime(self.builders_status_buildtime[b]),
379 builders.append(link_pre +
380 "<font color='%(color)s'><b title=\"%(tooltip)s\">%(builder)s:%(status)s</b></font>" % {
384 'tooltip' : cgi.escape(tooltip, True),
387 f.write("%s]</small></li>\n" % string.join(builders))
389 def rpmbuild_opts(self):
391 return all rpmbuild options related to this build
393 rpmopts = self.bconds_string() + self.kernel_string() + self.target_string() + self.defines_string()
395 "--define '_topdir %s' " % self.get_topdir() + \
396 "--define '_specdir %{_topdir}' " \
397 "--define '_sourcedir %{_specdir}' " \
398 "--define '_rpmdir %{_topdir}/RPMS' " \
399 "--define '_builddir %{_topdir}/BUILD' "
400 return rpmdefs + rpmopts
402 # transform php package name (52) to version (5.2)
403 def php_name_to_ver(v):
404 return '.'.join(list(v))
406 # transform php version (5.2) to package name (52)
407 def php_ver_to_name(v):
408 return v.replace('.', '')
410 def php_ignores(self, php_version):
411 # available php versions in distro
412 php_versions = ['4', '5.2', '5.3', '5.4', '5.5', '5.6', '7.0', '7.1', '7.2']
414 # remove current php version
416 php_versions.remove(php_version)
418 log.notice("Attempt to remove inexistent key '%s' from %s" % (php_version, php_versions))
421 # map them to poldek ignores
424 for v in map(php_ver_to_name, php_versions):
425 res.append("php%s-*" % v)
429 # build ignore package list
430 # currently only php ignore is filled based on build context
434 # add php version based ignores
435 if self.defines.has_key('php_suffix'):
436 # current version if -D php_suffix is present
437 php_version = php_name_to_ver(self.defines['php_suffix'])
439 php_version = self.DEFAULT_PHP
441 ignores.extend(self.php_ignores(php_version))
443 # return empty string if the list is empty
444 if len(ignores) == 0:
448 return "--ignore=%s" % s
450 return " ".join(map(add_ignore, ignores))
452 def kernel_string(self):
454 if self.kernel != "":
455 r = " --define 'alt_kernel " + self.kernel + "'"
458 def target_string(self):
459 if len(self.target) > 0:
460 return " --target " + ",".join(self.target)
464 def bconds_string(self):
466 for b in self.bconds_with:
467 r = r + " --with " + b
468 for b in self.bconds_without:
469 r = r + " --without " + b
472 def defines_string(self):
474 for key,value in self.defines.items():
475 r += " --define '%s %s'" % (key, value)
478 def defines_xml(self):
480 for key,value in self.defines.items():
481 r += "<define name='%s'>%s</define>\n" % (escape(key), escape(value))
484 def default_target(self, arch):
485 self.target.append("%s-pld-linux" % arch)
487 def write_to(self, f):
489 <batch id='%s' depends-on='%s'>
490 <src-rpm>%s</src-rpm>
491 <command flags="%s">%s</command>
494 <info>%s</info>\n""" % (self.b_id,
495 string.join(map(lambda (b): b.b_id, self.depends_on)),
496 escape(self.src_rpm),
497 escape(' '.join(self.command_flags)), escape(self.command),
498 escape(self.spec), escape(self.branch), escape(self.info)))
499 if self.kernel != "":
500 f.write(" <kernel>%s</kernel>\n" % escape(self.kernel))
501 for b in self.bconds_with:
502 f.write(" <with>%s</with>\n" % escape(b))
503 for b in self.target:
504 f.write(" <target>%s</target>\n" % escape(b))
505 for b in self.bconds_without:
506 f.write(" <without>%s</without>\n" % escape(b))
508 f.write(" %s\n" % self.defines_xml())
509 for b in self.builders:
510 if self.builders_status_buildtime.has_key(b):
511 t = self.builders_status_buildtime[b]
514 f.write(" <builder status='%s' time='%s' buildtime='%s'>%s</builder>\n" % \
515 (escape(self.builders_status[b]), self.builders_status_time[b], t, escape(b)))
516 f.write(" </batch>\n")
518 def log_line(self, l):
520 if self.logfile != None:
521 util.append_to(self.logfile, l)
523 def expand_builders(batch, all_builders):
525 for bld in batch.builders:
527 for my_bld in all_builders:
528 if fnmatch.fnmatch(my_bld, bld):
537 def __init__(self, e):
539 self.kind = 'notification'
540 self.group_id = attr(e, "group-id")
541 self.builder = attr(e, "builder")
543 self.batches_buildtime = {}
544 for c in e.childNodes:
545 if is_blank(c): continue
546 if c.nodeType != Element.ELEMENT_NODE:
547 log.panic("xml: evil notification child %d" % c.nodeType)
548 if c.nodeName == "batch":
550 status = attr(c, "status")
551 buildtime = attr(c, "buildtime", "0")
552 if not status.startswith("OK") and not status.startswith("SKIP") and not status.startswith("UNSUPP") and not status.startswith("FAIL"):
553 log.panic("xml notification: bad status: %s" % status)
554 self.batches[id] = status
555 self.batches_buildtime[id] = buildtime
557 log.panic("xml: evil notification child (%s)" % c.nodeName)
559 # return structure usable for json encoding
563 builder=self.builder,
564 batches=self.batches,
565 batches_buildtime=self.batches_buildtime,
568 def apply_to(self, q):
570 if r.kind == "group":
572 if self.batches.has_key(b.b_id):
573 b.builders_status[self.builder] = self.batches[b.b_id]
574 b.builders_status_time[self.builder] = time.time()
575 b.builders_status_buildtime[self.builder] = "0" #self.batches_buildtime[b.b_id]
577 def build_request(e):
578 if e.nodeType != Element.ELEMENT_NODE:
579 log.panic("xml: evil request element")
580 if e.nodeName == "group":
582 elif e.nodeName == "notification":
583 return Notification(e)
584 elif e.nodeName == "command":
588 log.panic("xml: evil request [%s]" % e.nodeName)
590 def parse_request(f):
592 return build_request(d.documentElement)
594 def parse_requests(f):
597 for r in d.documentElement.childNodes:
598 if is_blank(r): continue
599 res.append(build_request(r))