queue.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #!/usr/bin/env python
  2. # vim:set et sw=4:
  3. """
  4. Queue utility functions for dak
  5. @contact: Debian FTP Master <ftpmaster@debian.org>
  6. @copyright: 2001 - 2006 James Troup <james@nocrew.org>
  7. @copyright: 2009, 2010 Joerg Jaspert <joerg@debian.org>
  8. @license: GNU General Public License version 2 or later
  9. """
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation; either version 2 of the License, or
  13. # (at your option) any later version.
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. ###############################################################################
  22. from __future__ import absolute_import, print_function
  23. import os
  24. from . import utils
  25. from types import *
  26. from .dak_exceptions import *
  27. from .changes import *
  28. from .regexes import *
  29. from .config import Config
  30. from .dbconn import *
  31. ################################################################################
  32. def check_valid(overrides, session):
  33. """Check if section and priority for new overrides exist in database.
  34. Additionally does sanity checks:
  35. - debian-installer packages have to be udeb (or source)
  36. - non debian-installer packages cannot be udeb
  37. @type overrides: list of dict
  38. @param overrides: list of overrides to check. The overrides need
  39. to be given in form of a dict with the following keys:
  40. - package: package name
  41. - priority
  42. - section
  43. - component
  44. - type: type of requested override ('dsc', 'deb' or 'udeb')
  45. All values are strings.
  46. @rtype: bool
  47. @return: C{True} if all overrides are valid, C{False} if there is any
  48. invalid override.
  49. """
  50. all_valid = True
  51. for o in overrides:
  52. o['valid'] = True
  53. if session.query(Priority).filter_by(priority=o['priority']).first() is None:
  54. o['valid'] = False
  55. if session.query(Section).filter_by(section=o['section']).first() is None:
  56. o['valid'] = False
  57. if get_mapped_component(o['component'], session) is None:
  58. o['valid'] = False
  59. if o['type'] not in ('dsc', 'deb', 'udeb'):
  60. raise Exception('Unknown override type {0}'.format(o['type']))
  61. if o['type'] == 'udeb' and o['section'] != 'debian-installer':
  62. o['valid'] = False
  63. if o['section'] == 'debian-installer' and o['type'] not in ('dsc', 'udeb'):
  64. o['valid'] = False
  65. all_valid = all_valid and o['valid']
  66. return all_valid
  67. ###############################################################################
  68. def prod_maintainer(notes, upload):
  69. cnf = Config()
  70. changes = upload.changes
  71. whitelists = [upload.target_suite.mail_whitelist]
  72. # Here we prepare an editor and get them ready to prod...
  73. (fd, temp_filename) = utils.temp_filename()
  74. temp_file = os.fdopen(fd, 'w')
  75. temp_file.write("\n\n=====\n\n".join([note.comment for note in notes]))
  76. temp_file.close()
  77. editor = os.environ.get("EDITOR", "vi")
  78. answer = 'E'
  79. while answer == 'E':
  80. os.system("%s %s" % (editor, temp_filename))
  81. temp_fh = utils.open_file(temp_filename)
  82. prod_message = "".join(temp_fh.readlines())
  83. temp_fh.close()
  84. print("Prod message:")
  85. print(utils.prefix_multi_line_string(prod_message, " ", include_blank_lines=1))
  86. prompt = "[P]rod, Edit, Abandon, Quit ?"
  87. answer = "XXX"
  88. while prompt.find(answer) == -1:
  89. answer = utils.our_raw_input(prompt)
  90. m = re_default_answer.search(prompt)
  91. if answer == "":
  92. answer = m.group(1)
  93. answer = answer[:1].upper()
  94. os.unlink(temp_filename)
  95. if answer == 'A':
  96. return
  97. elif answer == 'Q':
  98. return 0
  99. # Otherwise, do the proding...
  100. user_email_address = utils.whoami() + " <%s>" % (
  101. cnf["Dinstall::MyAdminAddress"])
  102. changed_by = changes.changedby or changes.maintainer
  103. maintainer = changes.maintainer
  104. maintainer_to = utils.mail_addresses_for_upload(maintainer, changed_by, changes.fingerprint)
  105. Subst = {
  106. '__SOURCE__': upload.changes.source,
  107. '__CHANGES_FILENAME__': upload.changes.changesname,
  108. '__MAINTAINER_TO__': ", ".join(maintainer_to),
  109. }
  110. Subst["__FROM_ADDRESS__"] = user_email_address
  111. Subst["__PROD_MESSAGE__"] = prod_message
  112. Subst["__CC__"] = "Cc: " + cnf["Dinstall::MyEmailAddress"]
  113. prod_mail_message = utils.TemplateSubst(
  114. Subst, cnf["Dir::Templates"] + "/process-new.prod")
  115. # Send the prod mail
  116. utils.send_mail(prod_mail_message, whitelists=whitelists)
  117. print("Sent prodding message")
  118. ################################################################################
  119. def edit_note(note, upload, session, trainee=False):
  120. # Write the current data to a temporary file
  121. (fd, temp_filename) = utils.temp_filename()
  122. editor = os.environ.get("EDITOR", "vi")
  123. answer = 'E'
  124. while answer == 'E':
  125. os.system("%s %s" % (editor, temp_filename))
  126. temp_file = utils.open_file(temp_filename)
  127. newnote = temp_file.read().rstrip()
  128. temp_file.close()
  129. print("New Note:")
  130. print(utils.prefix_multi_line_string(newnote, " "))
  131. prompt = "[D]one, Edit, Abandon, Quit ?"
  132. answer = "XXX"
  133. while prompt.find(answer) == -1:
  134. answer = utils.our_raw_input(prompt)
  135. m = re_default_answer.search(prompt)
  136. if answer == "":
  137. answer = m.group(1)
  138. answer = answer[:1].upper()
  139. os.unlink(temp_filename)
  140. if answer == 'A':
  141. return
  142. elif answer == 'Q':
  143. return 0
  144. comment = NewComment()
  145. comment.policy_queue = upload.policy_queue
  146. comment.package = upload.changes.source
  147. comment.version = upload.changes.version
  148. comment.comment = newnote
  149. comment.author = utils.whoami()
  150. comment.trainee = trainee
  151. session.add(comment)
  152. session.commit()
  153. ###############################################################################
  154. def get_suite_version_by_source(source, session):
  155. 'returns a list of tuples (suite_name, version) for source package'
  156. q = session.query(Suite.suite_name, DBSource.version). \
  157. join(Suite.sources).filter_by(source=source)
  158. return q.all()
  159. def get_suite_version_by_package(package, arch_string, session):
  160. '''
  161. returns a list of tuples (suite_name, version) for binary package and
  162. arch_string
  163. '''
  164. return session.query(Suite.suite_name, DBBinary.version). \
  165. join(Suite.binaries).filter_by(package=package). \
  166. join(DBBinary.architecture). \
  167. filter(Architecture.arch_string.in_([arch_string, 'all'])).all()
  168. class Upload(object):
  169. """
  170. Everything that has to do with an upload processed.
  171. """
  172. def __init__(self):
  173. self.logger = None
  174. self.pkg = Changes()
  175. self.reset()
  176. ###########################################################################
  177. def update_subst(self):
  178. """ Set up the per-package template substitution mappings """
  179. raise Exception('to be removed')
  180. cnf = Config()
  181. # If 'dak process-unchecked' crashed out in the right place, architecture may still be a string.
  182. if "architecture" not in self.pkg.changes or not \
  183. isinstance(self.pkg.changes["architecture"], dict):
  184. self.pkg.changes["architecture"] = {"Unknown": ""}
  185. # and maintainer2047 may not exist.
  186. if "maintainer2047" not in self.pkg.changes:
  187. self.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
  188. self.Subst["__ARCHITECTURE__"] = " ".join(self.pkg.changes["architecture"].keys())
  189. self.Subst["__CHANGES_FILENAME__"] = os.path.basename(self.pkg.changes_file)
  190. self.Subst["__FILE_CONTENTS__"] = self.pkg.changes.get("filecontents", "")
  191. # For source uploads the Changed-By field wins; otherwise Maintainer wins.
  192. if "source" in self.pkg.changes["architecture"] and \
  193. self.pkg.changes["changedby822"] != "" and \
  194. (self.pkg.changes["changedby822"] != self.pkg.changes["maintainer822"]):
  195. self.Subst["__MAINTAINER_FROM__"] = self.pkg.changes["changedby2047"]
  196. self.Subst["__MAINTAINER_TO__"] = "%s, %s" % (self.pkg.changes["changedby2047"], self.pkg.changes["maintainer2047"])
  197. self.Subst["__MAINTAINER__"] = self.pkg.changes.get("changed-by", "Unknown")
  198. else:
  199. self.Subst["__MAINTAINER_FROM__"] = self.pkg.changes["maintainer2047"]
  200. self.Subst["__MAINTAINER_TO__"] = self.pkg.changes["maintainer2047"]
  201. self.Subst["__MAINTAINER__"] = self.pkg.changes.get("maintainer", "Unknown")
  202. # Process policy doesn't set the fingerprint field and I don't want to make it
  203. # do it for now as I don't want to have to deal with the case where we accepted
  204. # the package into PU-NEW, but the fingerprint has gone away from the keyring in
  205. # the meantime so the package will be remarked as rejectable. Urgh.
  206. # TODO: Fix this properly
  207. if 'fingerprint' in self.pkg.changes:
  208. session = DBConn().session()
  209. fpr = get_fingerprint(self.pkg.changes['fingerprint'], session)
  210. if fpr and self.check_if_upload_is_sponsored("%s@debian.org" % fpr.uid.uid, fpr.uid.name):
  211. if "sponsoremail" in self.pkg.changes:
  212. self.Subst["__MAINTAINER_TO__"] += ", %s" % self.pkg.changes["sponsoremail"]
  213. session.close()
  214. if "Dinstall::TrackingServer" in cnf and "source" in self.pkg.changes:
  215. self.Subst["__MAINTAINER_TO__"] += "\nBcc: dispatch@%s" % (cnf["Dinstall::TrackingServer"])
  216. # Apply any global override of the Maintainer field
  217. if cnf.get("Dinstall::OverrideMaintainer"):
  218. self.Subst["__MAINTAINER_TO__"] = cnf["Dinstall::OverrideMaintainer"]
  219. self.Subst["__MAINTAINER_FROM__"] = cnf["Dinstall::OverrideMaintainer"]
  220. self.Subst["__REJECT_MESSAGE__"] = self.package_info()
  221. self.Subst["__SOURCE__"] = self.pkg.changes.get("source", "Unknown")
  222. self.Subst["__VERSION__"] = self.pkg.changes.get("version", "Unknown")
  223. self.Subst["__SUITE__"] = ", ".join(self.pkg.changes["distribution"])
  224. ###########################################################################
  225. def check_if_upload_is_sponsored(self, uid_email, uid_name):
  226. for key in "maintaineremail", "changedbyemail", "maintainername", "changedbyname":
  227. if key not in self.pkg.changes:
  228. return False
  229. uid_email = '@'.join(uid_email.split('@')[:2])
  230. if uid_email in [self.pkg.changes["maintaineremail"], self.pkg.changes["changedbyemail"]]:
  231. sponsored = False
  232. elif uid_name in [self.pkg.changes["maintainername"], self.pkg.changes["changedbyname"]]:
  233. sponsored = False
  234. if uid_name == "":
  235. sponsored = True
  236. else:
  237. sponsored = True
  238. sponsor_addresses = utils.gpg_get_key_addresses(self.pkg.changes["fingerprint"])
  239. debian_emails = filter(lambda addr: addr.endswith('@debian.org'), sponsor_addresses)
  240. if uid_email not in debian_emails:
  241. if debian_emails:
  242. uid_email = debian_emails[0]
  243. if ("source" in self.pkg.changes["architecture"] and uid_email and utils.is_email_alias(uid_email)):
  244. if (self.pkg.changes["maintaineremail"] not in sponsor_addresses and
  245. self.pkg.changes["changedbyemail"] not in sponsor_addresses):
  246. self.pkg.changes["sponsoremail"] = uid_email
  247. return sponsored
  248. ###########################################################################
  249. # End check_signed_by_key checks
  250. ###########################################################################
  251. def announce(self, short_summary, action):
  252. """
  253. Send an announce mail about a new upload.
  254. @type short_summary: string
  255. @param short_summary: Short summary text to include in the mail
  256. @type action: bool
  257. @param action: Set to false no real action will be done.
  258. @rtype: string
  259. @return: Textstring about action taken.
  260. """
  261. cnf = Config()
  262. # Skip all of this if not sending mail to avoid confusing people
  263. if "Dinstall::Options::No-Mail" in cnf and cnf["Dinstall::Options::No-Mail"]:
  264. return ""
  265. # Only do announcements for source uploads with a recent dpkg-dev installed
  266. if float(self.pkg.changes.get("format", 0)) < 1.6 or \
  267. "source" not in self.pkg.changes["architecture"]:
  268. return ""
  269. announcetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.announce')
  270. lists_todo = {}
  271. summary = ""
  272. # Get a unique list of target lists
  273. for dist in self.pkg.changes["distribution"].keys():
  274. suite = get_suite(dist)
  275. if suite is None:
  276. continue
  277. for tgt in suite.announce:
  278. lists_todo[tgt] = 1
  279. self.Subst["__SHORT_SUMMARY__"] = short_summary
  280. for announce_list in lists_todo.keys():
  281. summary += "Announcing to %s\n" % (announce_list)
  282. if action:
  283. self.update_subst()
  284. self.Subst["__ANNOUNCE_LIST_ADDRESS__"] = announce_list
  285. if cnf.get("Dinstall::TrackingServer") and \
  286. "source" in self.pkg.changes["architecture"]:
  287. trackingsendto = "Bcc: dispatch@%s" % (cnf["Dinstall::TrackingServer"])
  288. self.Subst["__ANNOUNCE_LIST_ADDRESS__"] += "\n" + trackingsendto
  289. mail_message = utils.TemplateSubst(self.Subst, announcetemplate)
  290. utils.send_mail(mail_message)
  291. del self.Subst["__ANNOUNCE_LIST_ADDRESS__"]
  292. if cnf.find_b("Dinstall::CloseBugs") and "Dinstall::BugServer" in cnf:
  293. summary = self.close_bugs(summary, action)
  294. del self.Subst["__SHORT_SUMMARY__"]
  295. return summary
  296. ###########################################################################
  297. def check_override(self):
  298. """
  299. Checks override entries for validity. Mails "Override disparity" warnings,
  300. if that feature is enabled.
  301. Abandons the check if
  302. - override disparity checks are disabled
  303. - mail sending is disabled
  304. """
  305. cnf = Config()
  306. # Abandon the check if override disparity checks have been disabled
  307. if not cnf.find_b("Dinstall::OverrideDisparityCheck"):
  308. return
  309. summary = self.pkg.check_override()
  310. if summary == "":
  311. return
  312. overridetemplate = os.path.join(cnf["Dir::Templates"], 'process-unchecked.override-disparity')
  313. self.update_subst()
  314. self.Subst["__SUMMARY__"] = summary
  315. mail_message = utils.TemplateSubst(self.Subst, overridetemplate)
  316. utils.send_mail(mail_message)
  317. del self.Subst["__SUMMARY__"]