5 Queue utility functions for dak
7 @contact: Debian FTP Master <ftpmaster@debian.org>
8 @copyright: 2001 - 2006 James Troup <james@nocrew.org>
9 @copyright: 2009, 2010 Joerg Jaspert <joerg@debian.org>
10 @license: GNU General Public License version 2 or later
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 ###############################################################################
41 from sqlalchemy.sql.expression import desc
42 from sqlalchemy.orm.exc import NoResultFound
46 from dak_exceptions import *
49 from config import Config
50 from holding import Holding
51 from urgencylog import UrgencyLog
53 from summarystats import SummaryStats
54 from utils import parse_changes, check_dsc_files, build_package_list
55 from textutils import fix_maintainer
56 from lintian import parse_lintian_output, generate_reject_messages
57 from contents import UnpackedSource
59 ################################################################################
61 def check_valid(overrides, session):
62 """Check if section and priority for new overrides exist in database.
64 Additionally does sanity checks:
65 - debian-installer packages have to be udeb (or source)
66 - non debian-installer packages cannot be udeb
68 @type overrides: list of dict
69 @param overrides: list of overrides to check. The overrides need
70 to be given in form of a dict with the following keys:
72 - package: package name
76 - type: type of requested override ('dsc', 'deb' or 'udeb')
78 All values are strings.
81 @return: C{True} if all overrides are valid, C{False} if there is any
87 if session.query(Priority).filter_by(priority=o['priority']).first() is None:
89 if session.query(Section).filter_by(section=o['section']).first() is None:
91 if get_mapped_component(o['component'], session) is None:
93 if o['type'] not in ('dsc', 'deb', 'udeb'):
94 raise Exception('Unknown override type {0}'.format(o['type']))
95 if o['type'] == 'udeb' and o['section'] != 'debian-installer':
97 if o['section'] == 'debian-installer' and o['type'] not in ('dsc', 'udeb'):
99 all_valid = all_valid and o['valid']
102 ###############################################################################
104 def prod_maintainer(notes, upload):
106 changes = upload.changes
107 whitelists = [ upload.target_suite.mail_whitelist ]
109 # Here we prepare an editor and get them ready to prod...
110 (fd, temp_filename) = utils.temp_filename()
111 temp_file = os.fdopen(fd, 'w')
112 temp_file.write("\n\n=====\n\n".join([note.comment for note in notes]))
114 editor = os.environ.get("EDITOR","vi")
117 os.system("%s %s" % (editor, temp_filename))
118 temp_fh = utils.open_file(temp_filename)
119 prod_message = "".join(temp_fh.readlines())
121 print "Prod message:"
122 print utils.prefix_multi_line_string(prod_message," ",include_blank_lines=1)
123 prompt = "[P]rod, Edit, Abandon, Quit ?"
125 while prompt.find(answer) == -1:
126 answer = utils.our_raw_input(prompt)
127 m = re_default_answer.search(prompt)
130 answer = answer[:1].upper()
131 os.unlink(temp_filename)
136 # Otherwise, do the proding...
137 user_email_address = utils.whoami() + " <%s>" % (
138 cnf["Dinstall::MyAdminAddress"])
140 changed_by = changes.changedby or changes.maintainer
141 maintainer = changes.maintainer
142 maintainer_to = utils.mail_addresses_for_upload(maintainer, changed_by, changes.fingerprint)
145 '__SOURCE__': upload.changes.source,
146 '__CHANGES_FILENAME__': upload.changes.changesname,
147 '__MAINTAINER_TO__': ", ".join(maintainer_to),
150 Subst["__FROM_ADDRESS__"] = user_email_address
151 Subst["__PROD_MESSAGE__"] = prod_message
152 Subst["__CC__"] = "Cc: " + cnf["Dinstall::MyEmailAddress"]
154 prod_mail_message = utils.TemplateSubst(
155 Subst,cnf["Dir::Templates"]+"/process-new.prod")
158 utils.send_mail(prod_mail_message, whitelists=whitelists)
160 print "Sent prodding message"
162 ################################################################################
164 def edit_note(note, upload, session, trainee=False):
165 # Write the current data to a temporary file
166 (fd, temp_filename) = utils.temp_filename()
167 editor = os.environ.get("EDITOR","vi")
170 os.system("%s %s" % (editor, temp_filename))
171 temp_file = utils.open_file(temp_filename)
172 newnote = temp_file.read().rstrip()
175 print utils.prefix_multi_line_string(newnote," ")
176 prompt = "[D]one, Edit, Abandon, Quit ?"
178 while prompt.find(answer) == -1:
179 answer = utils.our_raw_input(prompt)
180 m = re_default_answer.search(prompt)
183 answer = answer[:1].upper()
184 os.unlink(temp_filename)
190 comment = NewComment()
191 comment.package = upload.changes.source
192 comment.version = upload.changes.version
193 comment.comment = newnote
194 comment.author = utils.whoami()
195 comment.trainee = trainee
199 ###############################################################################
201 # FIXME: Should move into the database
202 # suite names DMs can upload to
203 dm_suites = ['unstable', 'experimental', 'squeeze-backports']
205 def get_newest_source(source, session):
206 'returns the newest DBSource object in dm_suites'
207 ## the most recent version of the package uploaded to unstable or
208 ## experimental includes the field "DM-Upload-Allowed: yes" in the source
209 ## section of its control file
210 q = session.query(DBSource).filter_by(source = source). \
211 filter(DBSource.suites.any(Suite.suite_name.in_(dm_suites))). \
212 order_by(desc('source.version'))
215 def get_suite_version_by_source(source, session):
216 'returns a list of tuples (suite_name, version) for source package'
217 q = session.query(Suite.suite_name, DBSource.version). \
218 join(Suite.sources).filter_by(source = source)
221 def get_source_by_package_and_suite(package, suite_name, session):
223 returns a DBSource query filtered by DBBinary.package and this package's
226 return session.query(DBSource). \
227 join(DBSource.binaries).filter_by(package = package). \
228 join(DBBinary.suites).filter_by(suite_name = suite_name)
230 def get_suite_version_by_package(package, arch_string, session):
232 returns a list of tuples (suite_name, version) for binary package and
235 return session.query(Suite.suite_name, DBBinary.version). \
236 join(Suite.binaries).filter_by(package = package). \
237 join(DBBinary.architecture). \
238 filter(Architecture.arch_string.in_([arch_string, 'all'])).all()
240 class Upload(object):
242 Everything that has to do with an upload processed.
250 ###########################################################################
252 def update_subst(self):
253 """ Set up the per-package template substitution mappings """
254 raise Exception('to be removed')
258 # If 'dak process-unchecked' crashed out in the right place, architecture may still be a string.
259 if not self.pkg.changes.has_key("architecture") or not \
260 isinstance(self.pkg.changes["architecture"], dict):
261 self.pkg.changes["architecture"] = { "Unknown" : "" }
263 # and maintainer2047 may not exist.
264 if not self.pkg.changes.has_key("maintainer2047"):
265 self.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
267 self.Subst["__ARCHITECTURE__"] = " ".join(self.pkg.changes["architecture"].keys())
268 self.Subst["__CHANGES_FILENAME__"] = os.path.basename(self.pkg.changes_file)
269 self.Subst["__FILE_CONTENTS__"] = self.pkg.changes.get("filecontents", "")
271 # For source uploads the Changed-By field wins; otherwise Maintainer wins.
272 if self.pkg.changes["architecture"].has_key("source") and \
273 self.pkg.changes["changedby822"] != "" and \
274 (self.pkg.changes["changedby822"] != self.pkg.changes["maintainer822"]):
276 self.Subst["__MAINTAINER_FROM__"] = self.pkg.changes["changedby2047"]
277 self.Subst["__MAINTAINER_TO__"] = "%s, %s" % (self.pkg.changes["changedby2047"], self.pkg.changes["maintainer2047"])
278 self.Subst["__MAINTAINER__"] = self.pkg.changes.get("changed-by", "Unknown")
280 self.Subst["__MAINTAINER_FROM__"] = self.pkg.changes["maintainer2047"]
281 self.Subst["__MAINTAINER_TO__"] = self.pkg.changes["maintainer2047"]
282 self.Subst["__MAINTAINER__"] = self.pkg.changes.get("maintainer", "Unknown")
284 # Process policy doesn't set the fingerprint field and I don't want to make it
285 # do it for now as I don't want to have to deal with the case where we accepted
286 # the package into PU-NEW, but the fingerprint has gone away from the keyring in
287 # the meantime so the package will be remarked as rejectable. Urgh.
288 # TODO: Fix this properly
289 if self.pkg.changes.has_key('fingerprint'):
290 session = DBConn().session()
291 fpr = get_fingerprint(self.pkg.changes['fingerprint'], session)
292 if fpr and self.check_if_upload_is_sponsored("%s@debian.org" % fpr.uid.uid, fpr.uid.name):
293 if self.pkg.changes.has_key("sponsoremail"):
294 self.Subst["__MAINTAINER_TO__"] += ", %s" % self.pkg.changes["sponsoremail"]
297 if cnf.has_key("Dinstall::TrackingServer") and self.pkg.changes.has_key("source"):
298 self.Subst["__MAINTAINER_TO__"] += "\nBcc: %s@%s" % (self.pkg.changes["source"], cnf["Dinstall::TrackingServer"])
300 # Apply any global override of the Maintainer field
301 if cnf.get("Dinstall::OverrideMaintainer"):
302 self.Subst["__MAINTAINER_TO__"] = cnf["Dinstall::OverrideMaintainer"]
303 self.Subst["__MAINTAINER_FROM__"] = cnf["Dinstall::OverrideMaintainer"]
305 self.Subst["__REJECT_MESSAGE__"] = self.package_info()
306 self.Subst["__SOURCE__"] = self.pkg.changes.get("source", "Unknown")
307 self.Subst["__VERSION__"] = self.pkg.changes.get("version", "Unknown")
308 self.Subst["__SUITE__"] = ", ".join(self.pkg.changes["distribution"])
310 ###########################################################################
312 def check_distributions(self):
313 "Check and map the Distribution field"
317 # Handle suite mappings
318 for m in Cnf.value_list("SuiteMappings"):
321 if mtype == "map" or mtype == "silent-map":
322 (source, dest) = args[1:3]
323 if self.pkg.changes["distribution"].has_key(source):
324 del self.pkg.changes["distribution"][source]
325 self.pkg.changes["distribution"][dest] = 1
326 if mtype != "silent-map":
327 self.notes.append("Mapping %s to %s." % (source, dest))
328 if self.pkg.changes.has_key("distribution-version"):
329 if self.pkg.changes["distribution-version"].has_key(source):
330 self.pkg.changes["distribution-version"][source]=dest
331 elif mtype == "map-unreleased":
332 (source, dest) = args[1:3]
333 if self.pkg.changes["distribution"].has_key(source):
334 for arch in self.pkg.changes["architecture"].keys():
335 if arch not in [ a.arch_string for a in get_suite_architectures(source) ]:
336 self.notes.append("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch))
337 del self.pkg.changes["distribution"][source]
338 self.pkg.changes["distribution"][dest] = 1
340 elif mtype == "ignore":
342 if self.pkg.changes["distribution"].has_key(suite):
343 del self.pkg.changes["distribution"][suite]
344 self.warnings.append("Ignoring %s as a target suite." % (suite))
345 elif mtype == "reject":
347 if self.pkg.changes["distribution"].has_key(suite):
348 self.rejects.append("Uploads to %s are not accepted." % (suite))
349 elif mtype == "propup-version":
350 # give these as "uploaded-to(non-mapped) suites-to-add-when-upload-obsoletes"
352 # changes["distribution-version"] looks like: {'testing': 'testing-proposed-updates'}
353 if self.pkg.changes["distribution"].has_key(args[1]):
354 self.pkg.changes.setdefault("distribution-version", {})
355 for suite in args[2:]:
356 self.pkg.changes["distribution-version"][suite] = suite
358 # Ensure there is (still) a target distribution
359 if len(self.pkg.changes["distribution"].keys()) < 1:
360 self.rejects.append("No valid distribution remaining.")
362 # Ensure target distributions exist
363 for suite in self.pkg.changes["distribution"].keys():
364 if not get_suite(suite.lower()):
365 self.rejects.append("Unknown distribution `%s'." % (suite))
367 ###########################################################################
369 def per_suite_file_checks(self, f, suite, session):
370 raise Exception('removed')
372 # Handle component mappings
373 for m in cnf.value_list("ComponentMappings"):
374 (source, dest) = m.split()
375 if entry["component"] == source:
376 entry["original component"] = source
377 entry["component"] = dest
379 ###########################################################################
381 # Sanity check the time stamps of files inside debs.
382 # [Files in the near future cause ugly warnings and extreme time
383 # travel can cause errors on extraction]
385 def check_if_upload_is_sponsored(self, uid_email, uid_name):
386 for key in "maintaineremail", "changedbyemail", "maintainername", "changedbyname":
387 if not self.pkg.changes.has_key(key):
389 uid_email = '@'.join(uid_email.split('@')[:2])
390 if uid_email in [self.pkg.changes["maintaineremail"], self.pkg.changes["changedbyemail"]]:
392 elif uid_name in [self.pkg.changes["maintainername"], self.pkg.changes["changedbyname"]]:
398 sponsor_addresses = utils.gpg_get_key_addresses(self.pkg.changes["fingerprint"])
399 debian_emails = filter(lambda addr: addr.endswith('@debian.org'), sponsor_addresses)
400 if uid_email not in debian_emails:
402 uid_email = debian_emails[0]
403 if ("source" in self.pkg.changes["architecture"] and uid_email and utils.is_email_alias(uid_email)):
404 if (self.pkg.changes["maintaineremail"] not in sponsor_addresses and
405 self.pkg.changes["changedbyemail"] not in sponsor_addresses):
406 self.pkg.changes["sponsoremail"] = uid_email
410 def check_dm_upload(self, fpr, session):
411 # Quoth the GR (http://www.debian.org/vote/2007/vote_003):
412 ## none of the uploaded packages are NEW
413 ## none of the packages are being taken over from other source packages
414 for b in self.pkg.changes["binary"].keys():
415 for suite in self.pkg.changes["distribution"].keys():
416 for s in get_source_by_package_and_suite(b, suite, session):
417 if s.source != self.pkg.changes["source"]:
418 self.rejects.append("%s may not hijack %s from source package %s in suite %s" % (fpr.uid.uid, b, s, suite))
420 ###########################################################################
421 # End check_signed_by_key checks
422 ###########################################################################
424 def build_summaries(self):
425 """ Build a summary of changes the upload introduces. """
427 (byhand, new, summary, override_summary) = self.pkg.file_summary()
429 short_summary = summary
431 # This is for direport's benefit...
432 f = re_fdnic.sub("\n .\n", self.pkg.changes.get("changes", ""))
434 summary += "\n\nChanges:\n" + f
436 summary += "\n\nOverride entries for your package:\n" + override_summary + "\n"
438 summary += self.announce(short_summary, 0)
440 return (summary, short_summary)
442 ###########################################################################
444 def announce(self, short_summary, action):
446 Send an announce mail about a new upload.
448 @type short_summary: string
449 @param short_summary: Short summary text to include in the mail
452 @param action: Set to false no real action will be done.
455 @return: Textstring about action taken.
461 # Skip all of this if not sending mail to avoid confusing people
462 if cnf.has_key("Dinstall::Options::No-Mail") and cnf["Dinstall::Options::No-Mail"]:
465 # Only do announcements for source uploads with a recent dpkg-dev installed
466 if float(self.pkg.changes.get("format", 0)) < 1.6 or not \
467 self.pkg.changes["architecture"].has_key("source"):
470 announcetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.announce')
475 # Get a unique list of target lists
476 for dist in self.pkg.changes["distribution"].keys():
477 suite = get_suite(dist)
478 if suite is None: continue
479 for tgt in suite.announce:
482 self.Subst["__SHORT_SUMMARY__"] = short_summary
484 for announce_list in lists_todo.keys():
485 summary += "Announcing to %s\n" % (announce_list)
489 self.Subst["__ANNOUNCE_LIST_ADDRESS__"] = announce_list
490 if cnf.get("Dinstall::TrackingServer") and \
491 self.pkg.changes["architecture"].has_key("source"):
492 trackingsendto = "Bcc: %s@%s" % (self.pkg.changes["source"], cnf["Dinstall::TrackingServer"])
493 self.Subst["__ANNOUNCE_LIST_ADDRESS__"] += "\n" + trackingsendto
495 mail_message = utils.TemplateSubst(self.Subst, announcetemplate)
496 utils.send_mail(mail_message)
498 del self.Subst["__ANNOUNCE_LIST_ADDRESS__"]
500 if cnf.find_b("Dinstall::CloseBugs") and cnf.has_key("Dinstall::BugServer"):
501 summary = self.close_bugs(summary, action)
503 del self.Subst["__SHORT_SUMMARY__"]
507 ###########################################################################
509 def check_override(self):
511 Checks override entries for validity. Mails "Override disparity" warnings,
512 if that feature is enabled.
514 Abandons the check if
515 - override disparity checks are disabled
516 - mail sending is disabled
521 # Abandon the check if override disparity checks have been disabled
522 if not cnf.find_b("Dinstall::OverrideDisparityCheck"):
525 summary = self.pkg.check_override()
530 overridetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.override-disparity')
533 self.Subst["__SUMMARY__"] = summary
534 mail_message = utils.TemplateSubst(self.Subst, overridetemplate)
535 utils.send_mail(mail_message)
536 del self.Subst["__SUMMARY__"]
538 ################################################################################
539 def get_anyversion(self, sv_list, suite):
542 @param sv_list: list of (suite, version) tuples to check
545 @param suite: suite name
551 anysuite = [suite] + [ vc.reference.suite_name for vc in get_version_checks(suite, "Enhances") ]
552 for (s, v) in sv_list:
553 if s in [ x.lower() for x in anysuite ]:
554 if not anyversion or apt_pkg.version_compare(anyversion, v) <= 0:
559 ################################################################################
561 def cross_suite_version_check(self, sv_list, filename, new_version, sourceful=False):
564 @param sv_list: list of (suite, version) tuples to check
566 @type filename: string
569 @type new_version: string
570 @param new_version: XXX
572 Ensure versions are newer than existing packages in target
573 suites and that cross-suite version checking rules as
574 set out in the conf file are satisfied.
579 # Check versions for each target suite
580 for target_suite in self.pkg.changes["distribution"].keys():
581 # Check we can find the target suite
582 ts = get_suite(target_suite)
584 self.rejects.append("Cannot find target suite %s to perform version checks" % target_suite)
587 must_be_newer_than = [ vc.reference.suite_name for vc in get_version_checks(target_suite, "MustBeNewerThan") ]
588 must_be_older_than = [ vc.reference.suite_name for vc in get_version_checks(target_suite, "MustBeOlderThan") ]
590 # Enforce "must be newer than target suite" even if conffile omits it
591 if target_suite not in must_be_newer_than:
592 must_be_newer_than.append(target_suite)
594 for (suite, existent_version) in sv_list:
595 vercmp = apt_pkg.version_compare(new_version, existent_version)
597 if suite in must_be_newer_than and sourceful and vercmp < 1:
598 self.rejects.append("%s: old version (%s) in %s >= new version (%s) targeted at %s." % (filename, existent_version, suite, new_version, target_suite))
600 if suite in must_be_older_than and vercmp > -1:
603 if self.pkg.changes.get('distribution-version', {}).has_key(suite):
604 # we really use the other suite, ignoring the conflicting one ...
605 addsuite = self.pkg.changes["distribution-version"][suite]
607 add_version = self.get_anyversion(sv_list, addsuite)
608 target_version = self.get_anyversion(sv_list, target_suite)
611 # not add_version can only happen if we map to a suite
612 # that doesn't enhance the suite we're propup'ing from.
613 # so "propup-ver x a b c; map a d" is a problem only if
614 # d doesn't enhance a.
616 # i think we could always propagate in this case, rather
617 # than complaining. either way, this isn't a REJECT issue
619 # And - we really should complain to the dorks who configured dak
620 self.warnings.append("%s is mapped to, but not enhanced by %s - adding anyways" % (suite, addsuite))
621 self.pkg.changes.setdefault("propdistribution", {})
622 self.pkg.changes["propdistribution"][addsuite] = 1
624 elif not target_version:
625 # not targets_version is true when the package is NEW
626 # we could just stick with the "...old version..." REJECT
628 self.rejects.append("Won't propogate NEW packages.")
629 elif apt_pkg.version_compare(new_version, add_version) < 0:
630 # propogation would be redundant. no need to reject though.
631 self.warnings.append("ignoring versionconflict: %s: old version (%s) in %s <= new version (%s) targeted at %s." % (filename, existent_version, suite, new_version, target_suite))
633 elif apt_pkg.version_compare(new_version, add_version) > 0 and \
634 apt_pkg.version_compare(add_version, target_version) >= 0:
636 self.warnings.append("Propogating upload to %s" % (addsuite))
637 self.pkg.changes.setdefault("propdistribution", {})
638 self.pkg.changes["propdistribution"][addsuite] = 1
642 self.rejects.append("%s: old version (%s) in %s <= new version (%s) targeted at %s." % (filename, existent_version, suite, new_version, target_suite))
644 ################################################################################
646 def accepted_checks(self, overwrite_checks, session):
647 # Recheck anything that relies on the database; since that's not
648 # frozen between accept and our run time when called from p-a.
650 # overwrite_checks is set to False when installing to stable/oldstable
655 for checkfile in self.pkg.files.keys():
656 # The .orig.tar.gz can disappear out from under us is it's a
657 # duplicate of one in the archive.
658 if not self.pkg.files.has_key(checkfile):
661 entry = self.pkg.files[checkfile]
663 # propogate in the case it is in the override tables:
664 for suite in self.pkg.changes.get("propdistribution", {}).keys():
665 if self.in_override_p(entry["package"], entry["component"], suite, entry.get("dbtype",""), checkfile, session):
668 nopropogate[suite] = 1
670 for suite in propogate.keys():
671 if suite in nopropogate:
673 self.pkg.changes["distribution"][suite] = 1
675 for checkfile in self.pkg.files.keys():
676 # Check the package is still in the override tables
677 for suite in self.pkg.changes["distribution"].keys():
678 if not self.in_override_p(entry["package"], entry["component"], suite, entry.get("dbtype",""), checkfile, session):
679 self.rejects.append("%s is NEW for %s." % (checkfile, suite))