]> git.decadent.org.uk Git - dak.git/blob - dak/process_unchecked.py
Merge branch 'merge'
[dak.git] / dak / process_unchecked.py
1 #!/usr/bin/env python
2
3 """
4 Checks Debian packages from Incoming
5 @contact: Debian FTP Master <ftpmaster@debian.org>
6 @copyright: 2000, 2001, 2002, 2003, 2004, 2005, 2006  James Troup <james@nocrew.org>
7 @copyright: 2009  Joerg Jaspert <joerg@debian.org>
8 @copyright: 2009  Mark Hymers <mhy@debian.org>
9 @license: GNU General Public License version 2 or later
10 """
11
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
26 # Originally based on dinstall by Guy Maor <maor@debian.org>
27
28 ################################################################################
29
30 # Computer games don't affect kids. I mean if Pacman affected our generation as
31 # kids, we'd all run around in a darkened room munching pills and listening to
32 # repetitive music.
33 #         -- Unknown
34
35 ################################################################################
36
37 import errno
38 import fcntl
39 import os
40 import sys
41 import traceback
42 import apt_pkg
43
44 from daklib.dbconn import *
45 from daklib import daklog
46 from daklib.queue import *
47 from daklib import utils
48 from daklib.textutils import fix_maintainer
49 from daklib.dak_exceptions import *
50 from daklib.regexes import re_default_answer
51 from daklib.summarystats import SummaryStats
52 from daklib.holding import Holding
53 from daklib.config import Config
54
55 from types import *
56
57 ################################################################################
58
59
60 ################################################################################
61
62 # Globals
63 Options = None
64 Logger = None
65
66 ###############################################################################
67
68 def init():
69     global Options
70
71     apt_pkg.init()
72     cnf = Config()
73
74     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
75                  ('h',"help","Dinstall::Options::Help"),
76                  ('n',"no-action","Dinstall::Options::No-Action"),
77                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
78                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
79                  ('d',"directory", "Dinstall::Options::Directory", "HasArg")]
80
81     for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
82               "override-distribution", "version", "directory"]:
83         cnf["Dinstall::Options::%s" % (i)] = ""
84
85     changes_files = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
86     Options = cnf.SubTree("Dinstall::Options")
87
88     if Options["Help"]:
89         usage()
90
91     # If we have a directory flag, use it to find our files
92     if cnf["Dinstall::Options::Directory"] != "":
93         # Note that we clobber the list of files we were given in this case
94         # so warn if the user has done both
95         if len(changes_files) > 0:
96             utils.warn("Directory provided so ignoring files given on command line")
97
98         changes_files = utils.get_changes_files(cnf["Dinstall::Options::Directory"])
99
100     return changes_files
101
102 ################################################################################
103
104 def usage (exit_code=0):
105     print """Usage: dinstall [OPTION]... [CHANGES]...
106   -a, --automatic           automatic run
107   -h, --help                show this help and exit.
108   -n, --no-action           don't do anything
109   -p, --no-lock             don't check lockfile !! for cron.daily only !!
110   -s, --no-mail             don't send any mail
111   -V, --version             display the version number and exit"""
112     sys.exit(exit_code)
113
114 ################################################################################
115
116 def action(u):
117     cnf = Config()
118
119     # changes["distribution"] may not exist in corner cases
120     # (e.g. unreadable changes files)
121     if not u.pkg.changes.has_key("distribution") or not isinstance(u.pkg.changes["distribution"], DictType):
122         u.pkg.changes["distribution"] = {}
123
124     (summary, short_summary) = u.build_summaries()
125
126     # q-unapproved hax0ring
127     queue_info = {
128          "New": { "is": is_new, "process": acknowledge_new },
129          "Autobyhand" : { "is" : is_autobyhand, "process": do_autobyhand },
130          "Byhand" : { "is": is_byhand, "process": do_byhand },
131          "OldStableUpdate" : { "is": is_oldstableupdate,
132                                "process": do_oldstableupdate },
133          "StableUpdate" : { "is": is_stableupdate, "process": do_stableupdate },
134          "Unembargo" : { "is": is_unembargo, "process": queue_unembargo },
135          "Embargo" : { "is": is_embargo, "process": queue_embargo },
136     }
137
138     queues = [ "New", "Autobyhand", "Byhand" ]
139     if cnf.FindB("Dinstall::SecurityQueueHandling"):
140         queues += [ "Unembargo", "Embargo" ]
141     else:
142         queues += [ "OldStableUpdate", "StableUpdate" ]
143
144     (prompt, answer) = ("", "XXX")
145     if Options["No-Action"] or Options["Automatic"]:
146         answer = 'S'
147
148     queuekey = ''
149
150     pi = u.package_info()
151
152     if len(u.rejects) > 0:
153         if u.upload_too_new():
154             print "SKIP (too new)\n" + pi,
155             prompt = "[S]kip, Quit ?"
156         else:
157             print "REJECT\n" + pi
158             prompt = "[R]eject, Skip, Quit ?"
159             if Options["Automatic"]:
160                 answer = 'R'
161     else:
162         qu = None
163         for q in queues:
164             if queue_info[q]["is"](u):
165                 qu = q
166                 break
167         if qu:
168             print "%s for %s\n%s%s" % ( qu.upper(), ", ".join(u.pkg.changes["distribution"].keys()), pi, summary)
169             queuekey = qu[0].upper()
170             if queuekey in "RQSA":
171                 queuekey = "D"
172                 prompt = "[D]ivert, Skip, Quit ?"
173             else:
174                 prompt = "[%s]%s, Skip, Quit ?" % (queuekey, qu[1:].lower())
175             if Options["Automatic"]:
176                 answer = queuekey
177         else:
178             print "ACCEPT\n" + pi + summary,
179             prompt = "[A]ccept, Skip, Quit ?"
180             if Options["Automatic"]:
181                 answer = 'A'
182
183     while prompt.find(answer) == -1:
184         answer = utils.our_raw_input(prompt)
185         m = re_default_answer.match(prompt)
186         if answer == "":
187             answer = m.group(1)
188         answer = answer[:1].upper()
189
190     if answer == 'R':
191         os.chdir(u.pkg.directory)
192         u.do_reject(0, pi)
193     elif answer == 'A':
194         u.accept(summary, short_summary)
195         u.check_override()
196         u.remove()
197     elif answer == queuekey:
198         queue_info[qu]["process"](u, summary, short_summary)
199         u.remove()
200     elif answer == 'Q':
201         sys.exit(0)
202
203 ################################################################################
204
205 def package_to_suite(u, suite):
206     if not u.pkg.changes["distribution"].has_key(suite):
207         return False
208
209     ret = True
210
211     if not u.pkg.changes["architecture"].has_key("source"):
212         s = DBConn().session()
213         q = s.query(SrcAssociation.sa_id)
214         q = q.join(Suite).filter_by(suite_name=suite)
215         q = q.join(DBSource).filter_by(source=u.pkg.changes['source'])
216         q = q.filter_by(version=u.pkg.changes['version']).limit(1)
217
218         # NB: Careful, this logic isn't what you would think it is
219         # Source is already in {old-,}proposed-updates so no need to hold
220         # Instead, we don't move to the holding area, we just do an ACCEPT
221         if q.count() > 0:
222             ret = False
223
224         s.close()
225
226     return ret
227
228 def package_to_queue(u, summary, short_summary, queue, perms=0660, build=True, announce=None):
229     cnf = Config()
230     dir = cnf["Dir::Queue::%s" % queue]
231
232     print "Moving to %s holding area" % queue.upper()
233     Logger.log(["Moving to %s" % queue, u.pkg.changes_file])
234
235     u.pkg.write_dot_dak(dir)
236     u.move_to_dir(dir, perms=perms)
237     if build:
238         get_or_set_queue(queue.lower()).autobuild_upload(u.pkg, dir)
239
240     # Check for override disparities
241     u.check_override()
242
243     # Send accept mail, announce to lists and close bugs
244     if announce and not cnf["Dinstall::Options::No-Mail"]:
245         template = os.path.join(cnf["Dir::Templates"], announce)
246         u.update_subst()
247         u.Subst["__SUITE__"] = ""
248         mail_message = utils.TemplateSubst(u.Subst, template)
249         utils.send_mail(mail_message)
250         u.announce(short_summary, True)
251
252 ################################################################################
253
254 def is_unembargo(u):
255     session = DBConn().session()
256     cnf = Config()
257
258     q = session.execute("SELECT package FROM disembargo WHERE package = :source AND version = :version", u.pkg.changes)
259     if q.rowcount > 0:
260         session.close()
261         return True
262
263     oldcwd = os.getcwd()
264     os.chdir(cnf["Dir::Queue::Disembargo"])
265     disdir = os.getcwd()
266     os.chdir(oldcwd)
267
268     ret = False
269
270     if u.pkg.directory == disdir:
271         if u.pkg.changes["architecture"].has_key("source"):
272             if not Options["No-Action"]:
273                 session.execute("INSERT INTO disembargo (package, version) VALUES (:package, :version)", u.pkg.changes)
274                 session.commit()
275
276             ret = True
277
278     session.close()
279
280     return ret
281
282 def queue_unembargo(u, summary, short_summary):
283     return package_to_queue(u, summary, short_summary, "Unembargoed",
284                             perms=0660, build=True, announce='process-unchecked.accepted')
285
286 ################################################################################
287
288 def is_embargo(u):
289     # if embargoed queues are enabled always embargo
290     return True
291
292 def queue_embargo(u, summary, short_summary):
293     return package_to_queue(u, summary, short_summary, "Unembargoed",
294                             perms=0660, build=True, announce='process-unchecked.accepted')
295
296 ################################################################################
297
298 def is_stableupdate(u):
299     return package_to_suite(u, 'proposed-updates')
300
301 def do_stableupdate(u, summary, short_summary):
302     return package_to_queue(u, summary, short_summary, "ProposedUpdates",
303                             perms=0664, build=False, announce=None)
304
305 ################################################################################
306
307 def is_oldstableupdate(u):
308     return package_to_suite(u, 'oldstable-proposed-updates')
309
310 def do_oldstableupdate(u, summary, short_summary):
311     return package_to_queue(u, summary, short_summary, "OldProposedUpdates",
312                             perms=0664, build=False, announce=None)
313
314 ################################################################################
315
316 def is_autobyhand(u):
317     cnf = Config()
318
319     all_auto = 1
320     any_auto = 0
321     for f in u.pkg.files.keys():
322         if u.pkg.files[f].has_key("byhand"):
323             any_auto = 1
324
325             # filename is of form "PKG_VER_ARCH.EXT" where PKG, VER and ARCH
326             # don't contain underscores, and ARCH doesn't contain dots.
327             # further VER matches the .changes Version:, and ARCH should be in
328             # the .changes Architecture: list.
329             if f.count("_") < 2:
330                 all_auto = 0
331                 continue
332
333             (pckg, ver, archext) = f.split("_", 2)
334             if archext.count(".") < 1 or u.pkg.changes["version"] != ver:
335                 all_auto = 0
336                 continue
337
338             ABH = cnf.SubTree("AutomaticByHandPackages")
339             if not ABH.has_key(pckg) or \
340               ABH["%s::Source" % (pckg)] != u.pkg.changes["source"]:
341                 print "not match %s %s" % (pckg, u.pkg.changes["source"])
342                 all_auto = 0
343                 continue
344
345             (arch, ext) = archext.split(".", 1)
346             if arch not in u.pkg.changes["architecture"]:
347                 all_auto = 0
348                 continue
349
350             u.pkg.files[f]["byhand-arch"] = arch
351             u.pkg.files[f]["byhand-script"] = ABH["%s::Script" % (pckg)]
352
353     return any_auto and all_auto
354
355 def do_autobyhand(u, summary, short_summary):
356     print "Attempting AUTOBYHAND."
357     byhandleft = True
358     for f, entry in u.pkg.files.items():
359         byhandfile = f
360
361         if not entry.has_key("byhand"):
362             continue
363
364         if not entry.has_key("byhand-script"):
365             byhandleft = True
366             continue
367
368         os.system("ls -l %s" % byhandfile)
369
370         result = os.system("%s %s %s %s %s" % (
371                 entry["byhand-script"],
372                 byhandfile,
373                 u.pkg.changes["version"],
374                 entry["byhand-arch"],
375                 os.path.abspath(u.pkg.changes_file)))
376
377         if result == 0:
378             os.unlink(byhandfile)
379             del entry
380         else:
381             print "Error processing %s, left as byhand." % (f)
382             byhandleft = True
383
384     if byhandleft:
385         do_byhand(u, summary, short_summary)
386     else:
387         u.accept(summary, short_summary)
388         u.check_override()
389         # XXX: We seem to be missing a u.remove() here
390         #      This might explain why we get byhand leftovers in unchecked - mhy
391
392 ################################################################################
393
394 def is_byhand(u):
395     for f in u.pkg.files.keys():
396         if u.pkg.files[f].has_key("byhand"):
397             return True
398     return False
399
400 def do_byhand(u, summary, short_summary):
401     return package_to_queue(u, summary, short_summary, "Byhand",
402                             perms=0660, build=False, announce=None)
403
404 ################################################################################
405
406 def is_new(u):
407     for f in u.pkg.files.keys():
408         if u.pkg.files[f].has_key("new"):
409             return True
410     return False
411
412 def acknowledge_new(u, summary, short_summary):
413     cnf = Config()
414
415     print "Moving to NEW holding area."
416     Logger.log(["Moving to new", u.pkg.changes_file])
417
418     u.pkg.write_dot_dak(cnf["Dir::Queue::New"])
419     u.move_to_dir(cnf["Dir::Queue::New"], perms=0640, changesperms=0644)
420
421     if not Options["No-Mail"]:
422         print "Sending new ack."
423         template = os.path.join(cnf["Dir::Templates"], 'process-unchecked.new')
424         u.update_subst()
425         u.Subst["__SUMMARY__"] = summary
426         new_ack_message = utils.TemplateSubst(u.Subst, template)
427         utils.send_mail(new_ack_message)
428
429 ################################################################################
430
431 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
432 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
433 # Upload.check_dsc_against_db() can find the .orig.tar.gz but it will
434 # not have processed it during it's checks of -2.  If -1 has been
435 # deleted or otherwise not checked by 'dak process-unchecked', the
436 # .orig.tar.gz will not have been checked at all.  To get round this,
437 # we force the .orig.tar.gz into the .changes structure and reprocess
438 # the .changes file.
439
440 def process_it(changes_file):
441     global Logger
442
443     cnf = Config()
444
445     holding = Holding()
446
447     u = Upload()
448     u.pkg.changes_file = changes_file
449     u.pkg.directory = os.getcwd()
450     u.logger = Logger
451     origchanges = os.path.join(u.pkg.directory, u.pkg.changes_file)
452
453     # Some defaults in case we can't fully process the .changes file
454     u.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
455     u.pkg.changes["changedby2047"] = cnf["Dinstall::MyEmailAddress"]
456
457     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
458     bcc = "X-DAK: dak process-unchecked"
459     if cnf.has_key("Dinstall::Bcc"):
460         u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
461     else:
462         u.Subst["__BCC__"] = bcc
463
464     # Remember where we are so we can come back after cd-ing into the
465     # holding directory.  TODO: Fix this stupid hack
466     u.prevdir = os.getcwd()
467
468     # TODO: Figure out something better for this (or whether it's even
469     #       necessary - it seems to have been for use when we were
470     #       still doing the is_unchecked check; reprocess = 2)
471     u.reprocess = 1
472
473     try:
474         # If this is the Real Thing(tm), copy things into a private
475         # holding directory first to avoid replacable file races.
476         if not Options["No-Action"]:
477             os.chdir(cnf["Dir::Queue::Holding"])
478
479             # Absolutize the filename to avoid the requirement of being in the
480             # same directory as the .changes file.
481             holding.copy_to_holding(origchanges)
482
483             # Relativize the filename so we use the copy in holding
484             # rather than the original...
485             changespath = os.path.basename(u.pkg.changes_file)
486
487         (u.pkg.changes["fingerprint"], rejects) = utils.check_signature(changespath)
488
489         if u.pkg.changes["fingerprint"]:
490             valid_changes_p = u.load_changes(changespath)
491         else:
492             valid_changes_p = False
493             u.rejects.extend(rejects)
494
495         if valid_changes_p:
496             while u.reprocess:
497                 u.check_distributions()
498                 u.check_files(not Options["No-Action"])
499                 valid_dsc_p = u.check_dsc(not Options["No-Action"])
500                 if valid_dsc_p and not Options["No-Action"]:
501                     u.check_source()
502                     u.check_lintian()
503                 u.check_hashes()
504                 u.check_urgency()
505                 u.check_timestamps()
506                 u.check_signed_by_key()
507
508         action(u)
509
510     except SystemExit:
511         raise
512
513     except:
514         print "ERROR"
515         traceback.print_exc(file=sys.stderr)
516
517     # Restore previous WD
518     os.chdir(u.prevdir)
519
520 ###############################################################################
521
522 def main():
523     global Options, Logger
524
525     cnf = Config()
526     changes_files = init()
527
528     # -n/--dry-run invalidates some other options which would involve things happening
529     if Options["No-Action"]:
530         Options["Automatic"] = ""
531
532     # Initialize our Holding singleton
533     holding = Holding()
534
535     # Ensure all the arguments we were given are .changes files
536     for f in changes_files:
537         if not f.endswith(".changes"):
538             utils.warn("Ignoring '%s' because it's not a .changes file." % (f))
539             changes_files.remove(f)
540
541     if changes_files == []:
542         if cnf["Dinstall::Options::Directory"] == "":
543             utils.fubar("Need at least one .changes file as an argument.")
544         else:
545             sys.exit(0)
546
547     # Check that we aren't going to clash with the daily cron job
548     if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (cnf["Dir::Lock"])) and not Options["No-Lock"]:
549         utils.fubar("Archive maintenance in progress.  Try again later.")
550
551     # Obtain lock if not in no-action mode and initialize the log
552     if not Options["No-Action"]:
553         lock_fd = os.open(cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
554         try:
555             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
556         except IOError, e:
557             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
558                 utils.fubar("Couldn't obtain lock; assuming another 'dak process-unchecked' is already running.")
559             else:
560                 raise
561         Logger = daklog.Logger(cnf, "process-unchecked")
562
563     # Sort the .changes files so that we process sourceful ones first
564     changes_files.sort(utils.changes_compare)
565
566     # Process the changes files
567     for changes_file in changes_files:
568         print "\n" + changes_file
569         try:
570             process_it (changes_file)
571         finally:
572             if not Options["No-Action"]:
573                 holding.clean()
574
575     accept_count = SummaryStats().accept_count
576     accept_bytes = SummaryStats().accept_bytes
577
578     if accept_count:
579         sets = "set"
580         if accept_count > 1:
581             sets = "sets"
582         print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)))
583         Logger.log(["total",accept_count,accept_bytes])
584
585     if not Options["No-Action"]:
586         Logger.close()
587
588 ################################################################################
589
590 if __name__ == '__main__':
591     main()