]> git.decadent.org.uk Git - dak.git/blob - daklib/queue.py
Remove more obsolete code.
[dak.git] / daklib / queue.py
1 #!/usr/bin/env python
2 # vim:set et sw=4:
3
4 """
5 Queue utility functions for dak
6
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
11 """
12
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.
17
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.
22
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
26
27 ###############################################################################
28
29 import errno
30 import os
31 import stat
32 import sys
33 import time
34 import apt_inst
35 import apt_pkg
36 import utils
37 import commands
38 import shutil
39 import textwrap
40 from types import *
41 from sqlalchemy.sql.expression import desc
42 from sqlalchemy.orm.exc import NoResultFound
43
44 from dak_exceptions import *
45 from changes import *
46 from regexes import *
47 from config import Config
48 from holding import Holding
49 from urgencylog import UrgencyLog
50 from dbconn import *
51 from summarystats import SummaryStats
52 from utils import parse_changes, check_dsc_files
53 from textutils import fix_maintainer
54 from lintian import parse_lintian_output, generate_reject_messages
55 from contents import UnpackedSource
56
57 ################################################################################
58
59 def check_valid(overrides, session):
60     """Check if section and priority for new overrides exist in database.
61
62     Additionally does sanity checks:
63       - debian-installer packages have to be udeb (or source)
64       - non debian-installer packages cannot be udeb
65
66     @type  overrides: list of dict
67     @param overrides: list of overrides to check. The overrides need
68                       to be given in form of a dict with the following keys:
69
70                       - package: package name
71                       - priority
72                       - section
73                       - component
74                       - type: type of requested override ('dsc', 'deb' or 'udeb')
75
76                       All values are strings.
77
78     @rtype:  bool
79     @return: C{True} if all overrides are valid, C{False} if there is any
80              invalid override.
81     """
82     all_valid = True
83     for o in overrides:
84         o['valid'] = True
85         if session.query(Priority).filter_by(priority=o['priority']).first() is None:
86             o['valid'] = False
87         if session.query(Section).filter_by(section=o['section']).first() is None:
88             o['valid'] = False
89         if get_mapped_component(o['component'], session) is None:
90             o['valid'] = False
91         if o['type'] not in ('dsc', 'deb', 'udeb'):
92             raise Exception('Unknown override type {0}'.format(o['type']))
93         if o['type'] == 'udeb' and o['section'] != 'debian-installer':
94             o['valid'] = False
95         if o['section'] == 'debian-installer' and o['type'] not in ('dsc', 'udeb'):
96             o['valid'] = False
97         all_valid = all_valid and o['valid']
98     return all_valid
99
100 ###############################################################################
101
102 def prod_maintainer(notes, upload):
103     cnf = Config()
104     changes = upload.changes
105     whitelists = [ upload.target_suite.mail_whitelist ]
106
107     # Here we prepare an editor and get them ready to prod...
108     (fd, temp_filename) = utils.temp_filename()
109     temp_file = os.fdopen(fd, 'w')
110     temp_file.write("\n\n=====\n\n".join([note.comment for note in notes]))
111     temp_file.close()
112     editor = os.environ.get("EDITOR","vi")
113     answer = 'E'
114     while answer == 'E':
115         os.system("%s %s" % (editor, temp_filename))
116         temp_fh = utils.open_file(temp_filename)
117         prod_message = "".join(temp_fh.readlines())
118         temp_fh.close()
119         print "Prod message:"
120         print utils.prefix_multi_line_string(prod_message,"  ",include_blank_lines=1)
121         prompt = "[P]rod, Edit, Abandon, Quit ?"
122         answer = "XXX"
123         while prompt.find(answer) == -1:
124             answer = utils.our_raw_input(prompt)
125             m = re_default_answer.search(prompt)
126             if answer == "":
127                 answer = m.group(1)
128             answer = answer[:1].upper()
129     os.unlink(temp_filename)
130     if answer == 'A':
131         return
132     elif answer == 'Q':
133         return 0
134     # Otherwise, do the proding...
135     user_email_address = utils.whoami() + " <%s>" % (
136         cnf["Dinstall::MyAdminAddress"])
137
138     changed_by = changes.changedby or changes.maintainer
139     maintainer = changes.maintainer
140     maintainer_to = utils.mail_addresses_for_upload(maintainer, changed_by, changes.fingerprint)
141
142     Subst = {
143         '__SOURCE__': upload.changes.source,
144         '__CHANGES_FILENAME__': upload.changes.changesname,
145         '__MAINTAINER_TO__': ", ".join(maintainer_to),
146         }
147
148     Subst["__FROM_ADDRESS__"] = user_email_address
149     Subst["__PROD_MESSAGE__"] = prod_message
150     Subst["__CC__"] = "Cc: " + cnf["Dinstall::MyEmailAddress"]
151
152     prod_mail_message = utils.TemplateSubst(
153         Subst,cnf["Dir::Templates"]+"/process-new.prod")
154
155     # Send the prod mail
156     utils.send_mail(prod_mail_message, whitelists=whitelists)
157
158     print "Sent prodding message"
159
160 ################################################################################
161
162 def edit_note(note, upload, session, trainee=False):
163     # Write the current data to a temporary file
164     (fd, temp_filename) = utils.temp_filename()
165     editor = os.environ.get("EDITOR","vi")
166     answer = 'E'
167     while answer == 'E':
168         os.system("%s %s" % (editor, temp_filename))
169         temp_file = utils.open_file(temp_filename)
170         newnote = temp_file.read().rstrip()
171         temp_file.close()
172         print "New Note:"
173         print utils.prefix_multi_line_string(newnote,"  ")
174         prompt = "[D]one, Edit, Abandon, Quit ?"
175         answer = "XXX"
176         while prompt.find(answer) == -1:
177             answer = utils.our_raw_input(prompt)
178             m = re_default_answer.search(prompt)
179             if answer == "":
180                 answer = m.group(1)
181             answer = answer[:1].upper()
182     os.unlink(temp_filename)
183     if answer == 'A':
184         return
185     elif answer == 'Q':
186         return 0
187
188     comment = NewComment()
189     comment.policy_queue = upload.policy_queue
190     comment.package = upload.changes.source
191     comment.version = upload.changes.version
192     comment.comment = newnote
193     comment.author  = utils.whoami()
194     comment.trainee = trainee
195     session.add(comment)
196     session.commit()
197
198 ###############################################################################
199
200 def get_suite_version_by_source(source, session):
201     'returns a list of tuples (suite_name, version) for source package'
202     q = session.query(Suite.suite_name, DBSource.version). \
203         join(Suite.sources).filter_by(source = source)
204     return q.all()
205
206 def get_suite_version_by_package(package, arch_string, session):
207     '''
208     returns a list of tuples (suite_name, version) for binary package and
209     arch_string
210     '''
211     return session.query(Suite.suite_name, DBBinary.version). \
212         join(Suite.binaries).filter_by(package = package). \
213         join(DBBinary.architecture). \
214         filter(Architecture.arch_string.in_([arch_string, 'all'])).all()
215
216 class Upload(object):
217     """
218     Everything that has to do with an upload processed.
219
220     """
221     def __init__(self):
222         self.logger = None
223         self.pkg = Changes()
224         self.reset()
225
226     ###########################################################################
227
228     def update_subst(self):
229         """ Set up the per-package template substitution mappings """
230         raise Exception('to be removed')
231
232         cnf = Config()
233
234         # If 'dak process-unchecked' crashed out in the right place, architecture may still be a string.
235         if not self.pkg.changes.has_key("architecture") or not \
236            isinstance(self.pkg.changes["architecture"], dict):
237             self.pkg.changes["architecture"] = { "Unknown" : "" }
238
239         # and maintainer2047 may not exist.
240         if not self.pkg.changes.has_key("maintainer2047"):
241             self.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
242
243         self.Subst["__ARCHITECTURE__"] = " ".join(self.pkg.changes["architecture"].keys())
244         self.Subst["__CHANGES_FILENAME__"] = os.path.basename(self.pkg.changes_file)
245         self.Subst["__FILE_CONTENTS__"] = self.pkg.changes.get("filecontents", "")
246
247         # For source uploads the Changed-By field wins; otherwise Maintainer wins.
248         if self.pkg.changes["architecture"].has_key("source") and \
249            self.pkg.changes["changedby822"] != "" and \
250            (self.pkg.changes["changedby822"] != self.pkg.changes["maintainer822"]):
251
252             self.Subst["__MAINTAINER_FROM__"] = self.pkg.changes["changedby2047"]
253             self.Subst["__MAINTAINER_TO__"] = "%s, %s" % (self.pkg.changes["changedby2047"], self.pkg.changes["maintainer2047"])
254             self.Subst["__MAINTAINER__"] = self.pkg.changes.get("changed-by", "Unknown")
255         else:
256             self.Subst["__MAINTAINER_FROM__"] = self.pkg.changes["maintainer2047"]
257             self.Subst["__MAINTAINER_TO__"] = self.pkg.changes["maintainer2047"]
258             self.Subst["__MAINTAINER__"] = self.pkg.changes.get("maintainer", "Unknown")
259
260         # Process policy doesn't set the fingerprint field and I don't want to make it
261         # do it for now as I don't want to have to deal with the case where we accepted
262         # the package into PU-NEW, but the fingerprint has gone away from the keyring in
263         # the meantime so the package will be remarked as rejectable.  Urgh.
264         # TODO: Fix this properly
265         if self.pkg.changes.has_key('fingerprint'):
266             session = DBConn().session()
267             fpr = get_fingerprint(self.pkg.changes['fingerprint'], session)
268             if fpr and self.check_if_upload_is_sponsored("%s@debian.org" % fpr.uid.uid, fpr.uid.name):
269                 if self.pkg.changes.has_key("sponsoremail"):
270                     self.Subst["__MAINTAINER_TO__"] += ", %s" % self.pkg.changes["sponsoremail"]
271             session.close()
272
273         if cnf.has_key("Dinstall::TrackingServer") and self.pkg.changes.has_key("source"):
274             self.Subst["__MAINTAINER_TO__"] += "\nBcc: %s@%s" % (self.pkg.changes["source"], cnf["Dinstall::TrackingServer"])
275
276         # Apply any global override of the Maintainer field
277         if cnf.get("Dinstall::OverrideMaintainer"):
278             self.Subst["__MAINTAINER_TO__"] = cnf["Dinstall::OverrideMaintainer"]
279             self.Subst["__MAINTAINER_FROM__"] = cnf["Dinstall::OverrideMaintainer"]
280
281         self.Subst["__REJECT_MESSAGE__"] = self.package_info()
282         self.Subst["__SOURCE__"] = self.pkg.changes.get("source", "Unknown")
283         self.Subst["__VERSION__"] = self.pkg.changes.get("version", "Unknown")
284         self.Subst["__SUITE__"] = ", ".join(self.pkg.changes["distribution"])
285
286     ###########################################################################
287
288     def check_if_upload_is_sponsored(self, uid_email, uid_name):
289         for key in "maintaineremail", "changedbyemail", "maintainername", "changedbyname":
290             if not self.pkg.changes.has_key(key):
291                 return False
292         uid_email = '@'.join(uid_email.split('@')[:2])
293         if uid_email in [self.pkg.changes["maintaineremail"], self.pkg.changes["changedbyemail"]]:
294             sponsored = False
295         elif uid_name in [self.pkg.changes["maintainername"], self.pkg.changes["changedbyname"]]:
296             sponsored = False
297             if uid_name == "":
298                 sponsored = True
299         else:
300             sponsored = True
301             sponsor_addresses = utils.gpg_get_key_addresses(self.pkg.changes["fingerprint"])
302             debian_emails = filter(lambda addr: addr.endswith('@debian.org'), sponsor_addresses)
303             if uid_email not in debian_emails:
304                 if debian_emails:
305                     uid_email = debian_emails[0]
306             if ("source" in self.pkg.changes["architecture"] and uid_email and utils.is_email_alias(uid_email)):
307                 if (self.pkg.changes["maintaineremail"] not in sponsor_addresses and
308                     self.pkg.changes["changedbyemail"] not in sponsor_addresses):
309                         self.pkg.changes["sponsoremail"] = uid_email
310
311         return sponsored
312
313     ###########################################################################
314     # End check_signed_by_key checks
315     ###########################################################################
316
317     def announce(self, short_summary, action):
318         """
319         Send an announce mail about a new upload.
320
321         @type short_summary: string
322         @param short_summary: Short summary text to include in the mail
323
324         @type action: bool
325         @param action: Set to false no real action will be done.
326
327         @rtype: string
328         @return: Textstring about action taken.
329
330         """
331
332         cnf = Config()
333
334         # Skip all of this if not sending mail to avoid confusing people
335         if cnf.has_key("Dinstall::Options::No-Mail") and cnf["Dinstall::Options::No-Mail"]:
336             return ""
337
338         # Only do announcements for source uploads with a recent dpkg-dev installed
339         if float(self.pkg.changes.get("format", 0)) < 1.6 or not \
340            self.pkg.changes["architecture"].has_key("source"):
341             return ""
342
343         announcetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.announce')
344
345         lists_todo = {}
346         summary = ""
347
348         # Get a unique list of target lists
349         for dist in self.pkg.changes["distribution"].keys():
350             suite = get_suite(dist)
351             if suite is None: continue
352             for tgt in suite.announce:
353                 lists_todo[tgt] = 1
354
355         self.Subst["__SHORT_SUMMARY__"] = short_summary
356
357         for announce_list in lists_todo.keys():
358             summary += "Announcing to %s\n" % (announce_list)
359
360             if action:
361                 self.update_subst()
362                 self.Subst["__ANNOUNCE_LIST_ADDRESS__"] = announce_list
363                 if cnf.get("Dinstall::TrackingServer") and \
364                    self.pkg.changes["architecture"].has_key("source"):
365                     trackingsendto = "Bcc: %s@%s" % (self.pkg.changes["source"], cnf["Dinstall::TrackingServer"])
366                     self.Subst["__ANNOUNCE_LIST_ADDRESS__"] += "\n" + trackingsendto
367
368                 mail_message = utils.TemplateSubst(self.Subst, announcetemplate)
369                 utils.send_mail(mail_message)
370
371                 del self.Subst["__ANNOUNCE_LIST_ADDRESS__"]
372
373         if cnf.find_b("Dinstall::CloseBugs") and cnf.has_key("Dinstall::BugServer"):
374             summary = self.close_bugs(summary, action)
375
376         del self.Subst["__SHORT_SUMMARY__"]
377
378         return summary
379
380     ###########################################################################
381
382     def check_override(self):
383         """
384         Checks override entries for validity. Mails "Override disparity" warnings,
385         if that feature is enabled.
386
387         Abandons the check if
388           - override disparity checks are disabled
389           - mail sending is disabled
390         """
391
392         cnf = Config()
393
394         # Abandon the check if override disparity checks have been disabled
395         if not cnf.find_b("Dinstall::OverrideDisparityCheck"):
396             return
397
398         summary = self.pkg.check_override()
399
400         if summary == "":
401             return
402
403         overridetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.override-disparity')
404
405         self.update_subst()
406         self.Subst["__SUMMARY__"] = summary
407         mail_message = utils.TemplateSubst(self.Subst, overridetemplate)
408         utils.send_mail(mail_message)
409         del self.Subst["__SUMMARY__"]