]> git.decadent.org.uk Git - dak.git/blob - dak/process_upload.py
dak/process_upload.py: only send mail to tracking server if accepted to real suite
[dak.git] / dak / process_upload.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 @copyright: 2009  Frank Lichtenheld <djpig@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 # based on process-unchecked and process-accepted
28
29 ## pu|pa: locking (daily.lock)
30 ## pu|pa: parse arguments -> list of changes files
31 ## pa: initialize urgency log
32 ## pu|pa: sort changes list
33
34 ## foreach changes:
35 ###  pa: load dak file
36 ##   pu: copy CHG to tempdir
37 ##   pu: check CHG signature
38 ##   pu: parse changes file
39 ##   pu: checks:
40 ##     pu: check distribution (mappings, rejects)
41 ##     pu: copy FILES to tempdir
42 ##     pu: check whether CHG already exists in CopyChanges
43 ##     pu: check whether FILES already exist in one of the policy queues
44 ##     for deb in FILES:
45 ##       pu: extract control information
46 ##       pu: various checks on control information
47 ##       pu|pa: search for source (in CHG, projectb, policy queues)
48 ##       pu|pa: check whether "Version" fulfills target suite requirements/suite propagation
49 ##       pu|pa: check whether deb already exists in the pool
50 ##     for src in FILES:
51 ##       pu: various checks on filenames and CHG consistency
52 ##       pu: if isdsc: check signature
53 ##     for file in FILES:
54 ##       pu: various checks
55 ##       pu: NEW?
56 ##       //pu: check whether file already exists in the pool
57 ##       pu: store what "Component" the package is currently in
58 ##     pu: check whether we found everything we were looking for in CHG
59 ##     pu: check the DSC:
60 ##       pu: check whether we need and have ONE DSC
61 ##       pu: parse the DSC
62 ##       pu: various checks //maybe drop some of the in favor of lintian
63 ##       pu|pa: check whether "Version" fulfills target suite requirements/suite propagation
64 ##       pu: check whether DSC_FILES is consistent with "Format"
65 ##       for src in DSC_FILES:
66 ##         pu|pa: check whether file already exists in the pool (with special handling for .orig.tar.gz)
67 ##     pu: create new tempdir
68 ##     pu: create symlink mirror of source
69 ##     pu: unpack source
70 ##     pu: extract changelog information for BTS
71 ##     //pu: create missing .orig symlink
72 ##     pu: check with lintian
73 ##     for file in FILES:
74 ##       pu: check checksums and sizes
75 ##     for file in DSC_FILES:
76 ##       pu: check checksums and sizes
77 ##     pu: CHG: check urgency
78 ##     for deb in FILES:
79 ##       pu: extract contents list and check for dubious timestamps
80 ##     pu: check that the uploader is actually allowed to upload the package
81 ###  pa: install:
82 ###    if stable_install:
83 ###      pa: remove from p-u
84 ###      pa: add to stable
85 ###      pa: move CHG to morgue
86 ###      pa: append data to ChangeLog
87 ###      pa: send mail
88 ###      pa: remove .dak file
89 ###    else:
90 ###      pa: add dsc to db:
91 ###        for file in DSC_FILES:
92 ###          pa: add file to file
93 ###          pa: add file to dsc_files
94 ###        pa: create source entry
95 ###        pa: update source associations
96 ###        pa: update src_uploaders
97 ###      for deb in FILES:
98 ###        pa: add deb to db:
99 ###          pa: add file to file
100 ###          pa: find source entry
101 ###          pa: create binaries entry
102 ###          pa: update binary associations
103 ###      pa: .orig component move
104 ###      pa: move files to pool
105 ###      pa: save CHG
106 ###      pa: move CHG to done/
107 ###      pa: change entry in queue_build
108 ##   pu: use dispatch table to choose target queue:
109 ##     if NEW:
110 ##       pu: write .dak file
111 ##       pu: move to NEW
112 ##       pu: send mail
113 ##     elsif AUTOBYHAND:
114 ##       pu: run autobyhand script
115 ##       pu: if stuff left, do byhand or accept
116 ##     elsif targetqueue in (oldstable, stable, embargo, unembargo):
117 ##       pu: write .dak file
118 ##       pu: check overrides
119 ##       pu: move to queue
120 ##       pu: send mail
121 ##     else:
122 ##       pu: write .dak file
123 ##       pu: move to ACCEPTED
124 ##       pu: send mails
125 ##       pu: create files for BTS
126 ##       pu: create entry in queue_build
127 ##       pu: check overrides
128
129 # Integrity checks
130 ## GPG
131 ## Parsing changes (check for duplicates)
132 ## Parse dsc
133 ## file list checks
134
135 # New check layout (TODO: Implement)
136 ## Permission checks
137 ### suite mappings
138 ### ACLs
139 ### version checks (suite)
140 ### override checks
141
142 ## Source checks
143 ### copy orig
144 ### unpack
145 ### BTS changelog
146 ### src contents
147 ### lintian
148 ### urgency log
149
150 ## Binary checks
151 ### timestamps
152 ### control checks
153 ### src relation check
154 ### contents
155
156 ## Database insertion (? copy from stuff)
157 ### BYHAND / NEW / Policy queues
158 ### Pool
159
160 ## Queue builds
161
162 import datetime
163 import errno
164 from errno import EACCES, EAGAIN
165 import fcntl
166 import os
167 import sys
168 import traceback
169 import apt_pkg
170 import time
171 from sqlalchemy.orm.exc import NoResultFound
172
173 from daklib import daklog
174 from daklib.dbconn import *
175 from daklib.urgencylog import UrgencyLog
176 from daklib.summarystats import SummaryStats
177 from daklib.config import Config
178 import daklib.utils as utils
179 from daklib.textutils import fix_maintainer
180 from daklib.regexes import *
181
182 import daklib.archive
183 import daklib.upload
184
185 ###############################################################################
186
187 Options = None
188 Logger = None
189
190 ###############################################################################
191
192 def usage (exit_code=0):
193     print """Usage: dak process-upload [OPTION]... [CHANGES]...
194   -a, --automatic           automatic run
195   -d, --directory <DIR>     process uploads in <DIR>
196   -h, --help                show this help and exit.
197   -n, --no-action           don't do anything
198   -p, --no-lock             don't check lockfile !! for cron.daily only !!
199   -s, --no-mail             don't send any mail
200   -V, --version             display the version number and exit"""
201     sys.exit(exit_code)
202
203 ###############################################################################
204
205 def try_or_reject(function):
206     """Try to call function or reject the upload if that fails
207     """
208     def wrapper(directory, upload, *args, **kwargs):
209         try:
210             return function(directory, upload, *args, **kwargs)
211         except Exception as e:
212             try:
213                 reason = "There was an uncaught exception when processing your upload:\n{0}\nAny original reject reason follows below.".format(traceback.format_exc())
214                 upload.rollback()
215                 return real_reject(directory, upload, reason=reason)
216             except Exception as e:
217                 reason = "In addition there was an exception when rejecting the package:\n{0}\nPrevious reasons:\n{1}".format(traceback.format_exc(), reason)
218                 upload.rollback()
219                 return real_reject(directory, upload, reason=reason, notify=False)
220
221     return wrapper
222
223 def subst_for_upload(upload):
224     cnf = Config()
225
226     changes = upload.changes
227     control = upload.changes.changes
228
229     if upload.final_suites is None or len(upload.final_suites) == 0:
230         suite_name = '(unknown)'
231     else:
232         suite_names = []
233         for suite in upload.final_suites:
234             if suite.policy_queue:
235                 suite_names.append("{0}->{1}".format(suite.suite_name, suite.policy_queue.queue_name))
236             else:
237                 suite_names.append(suite.suite_name)
238         suite_name = ','.join(suite_names)
239
240     maintainer_field = control.get('Changed-By', control.get('Maintainer', cnf['Dinstall::MyEmailAddress']))
241     maintainer = fix_maintainer(maintainer_field)
242     addresses = utils.mail_addresses_for_upload(control.get('Maintainer', cnf['Dinstall::MyEmailAddress']), maintainer_field, changes.primary_fingerprint)
243
244     bcc = 'X-DAK: dak process-upload'
245     if 'Dinstall::Bcc' in cnf:
246         bcc = '{0}\nBcc: {1}'.format(bcc, cnf['Dinstall::Bcc'])
247
248     subst = {
249         '__DISTRO__': cnf['Dinstall::MyDistribution'],
250         '__ADMIN_ADDRESS__': cnf['Dinstall::MyAdminAddress'],
251
252         '__CHANGES_FILENAME__': upload.changes.filename,
253
254         '__SOURCE__': control.get('Source', '(unknown)'),
255         '__ARCHITECTURE__': control.get('Architecture', '(unknown)'),
256         '__VERSION__': control.get('Version', '(unknown)'),
257
258         '__SUITE__': suite_name,
259
260         '__DAK_ADDRESS__': cnf['Dinstall::MyEmailAddress'],
261         '__MAINTAINER_FROM__': maintainer[1],
262         '__MAINTAINER_TO__': ", ".join(addresses),
263         '__MAINTAINER__': maintainer_field,
264         '__BCC__': bcc,
265
266         '__BUG_SERVER__': cnf.get('Dinstall::BugServer'),
267
268         # TODO: don't use private member
269         '__FILE_CONTENTS__': upload.changes._signed_file.contents,
270
271         # __REJECT_MESSAGE__
272         }
273
274     override_maintainer = cnf.get('Dinstall::OverrideMaintainer')
275     if override_maintainer:
276         subst['__MAINTAINER_TO__'] = subst['__MAINTAINER_FROM__'] = override_maintainer
277
278     return subst
279
280 @try_or_reject
281 def accept(directory, upload):
282     cnf = Config()
283
284     Logger.log(['ACCEPT', upload.changes.filename])
285
286     upload.install()
287
288     accepted_to_real_suite = False
289     for suite in upload.final_suites:
290         accepted_to_real_suite = accepted_to_real_suite or suite.policy_queue is None
291
292     control = upload.changes.changes
293     if 'source' in upload.changes.architectures and not Options['No-Action']:
294         urgency = control.get('Urgency')
295         if urgency not in cnf.value_list('Urgency::Valid'):
296             urgency = cnf['Urgency::Default']
297         UrgencyLog().log(control['Source'], control['Version'], urgency)
298
299     # send mail to maintainer
300     subst = subst_for_upload(upload)
301     message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.accepted'))
302     utils.send_mail(message)
303
304     # send mail to announce lists and tracking server
305     if  accepted_to_real_suite:
306         subst = subst_for_upload(upload)
307         announce = set()
308         for suite in upload.final_suites:
309             if suite.policy_queue is not None:
310                 continue
311             announce.update(suite.announce or [])
312         announce_address = ", ".join(announce)
313
314         tracking = cnf.get('Dinstall::TrackingServer')
315         if tracking and 'source' in upload.changes.architectures:
316             announce_address = '{0}\nBcc: {1}@{2}'.format(announce_address, control['Source'], tracking)
317
318         subst['__ANNOUNCE_LIST_ADDRESS__'] = announce_address
319
320         message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.announce'))
321         utils.send_mail(message)
322
323     # Only close bugs for uploads that were not redirected to a policy queue.
324     # process-policy will close bugs for those once they are accepted.
325     subst = subst_for_upload(upload)
326     if accepted_to_real_suite and cnf.find_b('Dinstall::CloseBugs') and upload.changes.source is not None:
327         for bugnum in upload.changes.closed_bugs:
328             subst['__BUG_NUMBER__'] = str(bugnum)
329
330             message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.bug-close'))
331             utils.send_mail(message)
332
333             del subst['__BUG_NUMBER__']
334
335     # Move .changes to done, but only for uploads that were accepted to a
336     # real suite.  process-policy will handle this for uploads to queues.
337     if accepted_to_real_suite:
338         src = os.path.join(upload.directory, upload.changes.filename)
339
340         now = datetime.datetime.now()
341         donedir = os.path.join(cnf['Dir::Done'], now.strftime('%Y/%m/%d'))
342         dst = os.path.join(donedir, upload.changes.filename)
343         dst = utils.find_next_free(dst)
344
345         upload.transaction.fs.copy(src, dst, mode=0o644)
346
347     SummaryStats().accept_count += 1
348     SummaryStats().accept_bytes += upload.changes.bytes
349
350 @try_or_reject
351 def accept_to_new(directory, upload):
352     cnf = Config()
353
354     Logger.log(['ACCEPT-TO-NEW', upload.changes.filename])
355
356     upload.install_to_new()
357     # TODO: tag bugs pending, send announcement
358
359     subst = subst_for_upload(upload)
360     message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.new'))
361     utils.send_mail(message)
362
363     SummaryStats().accept_count += 1
364     SummaryStats().accept_bytes += upload.changes.bytes
365
366 @try_or_reject
367 def reject(directory, upload, reason=None, notify=True):
368     real_reject(directory, upload, reason, notify)
369
370 def real_reject(directory, upload, reason=None, notify=True):
371     # XXX: rejection itself should go to daklib.archive.ArchiveUpload
372     cnf = Config()
373
374     Logger.log(['REJECT', upload.changes.filename])
375
376     fs = upload.transaction.fs
377     rejectdir = cnf['Dir::Reject']
378
379     files = [ f.filename for f in upload.changes.files.itervalues() ]
380     files.append(upload.changes.filename)
381
382     for fn in files:
383         src = os.path.join(upload.directory, fn)
384         dst = utils.find_next_free(os.path.join(rejectdir, fn))
385         if not os.path.exists(src):
386             continue
387         fs.copy(src, dst)
388
389     if upload.reject_reasons is not None:
390         if reason is None:
391             reason = ''
392         reason = reason + '\n' + '\n'.join(upload.reject_reasons)
393
394     if reason is None:
395         reason = '(Unknown reason. Please check logs.)'
396
397     dst = utils.find_next_free(os.path.join(rejectdir, '{0}.reason'.format(upload.changes.filename)))
398     fh = fs.create(dst)
399     fh.write(reason)
400     fh.close()
401
402     # TODO: fix
403     if notify:
404         subst = subst_for_upload(upload)
405         subst['__REJECTOR_ADDRESS__'] = cnf['Dinstall::MyEmailAddress']
406         subst['__MANUAL_REJECT_MESSAGE__'] = ''
407         subst['__REJECT_MESSAGE__'] = reason
408         subst['__CC__'] = 'X-DAK-Rejection: automatic (moo)'
409
410         message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'queue.rejected'))
411         utils.send_mail(message)
412
413     SummaryStats().reject_count += 1
414
415 ###############################################################################
416
417 def action(directory, upload):
418     changes = upload.changes
419     processed = True
420
421     global Logger
422
423     cnf = Config()
424
425     okay = upload.check()
426
427     summary = changes.changes.get('Changes', '')
428
429     package_info = []
430     if okay:
431         if changes.source is not None:
432             package_info.append("source:{0}".format(changes.source.dsc['Source']))
433         for binary in changes.binaries:
434             package_info.append("binary:{0}".format(binary.control['Package']))
435
436     (prompt, answer) = ("", "XXX")
437     if Options["No-Action"] or Options["Automatic"]:
438         answer = 'S'
439
440     queuekey = ''
441
442     print summary
443     print
444     print "\n".join(package_info)
445     print
446
447     if len(upload.reject_reasons) > 0:
448         print "Reason:"
449         print "\n".join(upload.reject_reasons)
450         print
451
452         path = os.path.join(directory, changes.filename)
453         created = os.stat(path).st_mtime
454         now = time.time()
455         too_new = (now - created < int(cnf['Dinstall::SkipTime']))
456
457         if too_new:
458             print "SKIP (too new)"
459             prompt = "[S]kip, Quit ?"
460         else:
461             prompt = "[R]eject, Skip, Quit ?"
462             if Options["Automatic"]:
463                 answer = 'R'
464     elif upload.new:
465         prompt = "[N]ew, Skip, Quit ?"
466         if Options['Automatic']:
467             answer = 'N'
468     else:
469         prompt = "[A]ccept, Skip, Quit ?"
470         if Options['Automatic']:
471             answer = 'A'
472
473     while prompt.find(answer) == -1:
474         answer = utils.our_raw_input(prompt)
475         m = re_default_answer.match(prompt)
476         if answer == "":
477             answer = m.group(1)
478         answer = answer[:1].upper()
479
480     if answer == 'R':
481         reject(directory, upload)
482     elif answer == 'A':
483         # upload.try_autobyhand must not be run with No-Action.
484         if Options['No-Action']:
485             accept(directory, upload)
486         elif upload.try_autobyhand():
487             accept(directory, upload)
488         else:
489             print "W: redirecting to BYHAND as automatic processing failed."
490             accept_to_new(directory, upload)
491     elif answer == 'N':
492         accept_to_new(directory, upload)
493     elif answer == 'Q':
494         sys.exit(0)
495     elif answer == 'S':
496         processed = False
497
498     #raise Exception("FAIL")
499     if not Options['No-Action']:
500         upload.commit()
501
502     return processed
503
504 ###############################################################################
505
506 def unlink_if_exists(path):
507     try:
508         os.unlink(path)
509     except OSError as e:
510         if e.errno != errno.ENOENT:
511             raise
512
513 def process_it(directory, changes, keyrings, session):
514     global Logger
515
516     print "\n{0}\n".format(changes.filename)
517     Logger.log(["Processing changes file", changes.filename])
518
519     cnf = Config()
520
521     # Some defaults in case we can't fully process the .changes file
522     #u.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
523     #u.pkg.changes["changedby2047"] = cnf["Dinstall::MyEmailAddress"]
524
525     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
526     bcc = "X-DAK: dak process-upload"
527     #if cnf.has_key("Dinstall::Bcc"):
528     #    u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
529     #else:
530     #    u.Subst["__BCC__"] = bcc
531
532     with daklib.archive.ArchiveUpload(directory, changes, keyrings) as upload:
533         processed = action(directory, upload)
534         if processed and not Options['No-Action']:
535             unlink_if_exists(os.path.join(directory, changes.filename))
536             for fn in changes.files:
537                 unlink_if_exists(os.path.join(directory, fn))
538
539 ###############################################################################
540
541 def process_changes(changes_filenames):
542     session = DBConn().session()
543     keyrings = session.query(Keyring).filter_by(active=True).order_by(Keyring.priority)
544     keyring_files = [ k.keyring_name for k in keyrings ]
545
546     changes = []
547     for fn in changes_filenames:
548         try:
549             directory, filename = os.path.split(fn)
550             c = daklib.upload.Changes(directory, filename, keyring_files)
551             changes.append([directory, c])
552         except Exception as e:
553             Logger.log([filename, "Error while loading changes: {0}".format(e)])
554
555     changes.sort(key=lambda x: x[1])
556
557     for directory, c in changes:
558         process_it(directory, c, keyring_files, session)
559
560     session.rollback()
561
562 ###############################################################################
563
564 def main():
565     global Options, Logger
566
567     cnf = Config()
568     summarystats = SummaryStats()
569
570     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
571                  ('h',"help","Dinstall::Options::Help"),
572                  ('n',"no-action","Dinstall::Options::No-Action"),
573                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
574                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
575                  ('d',"directory", "Dinstall::Options::Directory", "HasArg")]
576
577     for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
578               "version", "directory"]:
579         if not cnf.has_key("Dinstall::Options::%s" % (i)):
580             cnf["Dinstall::Options::%s" % (i)] = ""
581
582     changes_files = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
583     Options = cnf.subtree("Dinstall::Options")
584
585     if Options["Help"]:
586         usage()
587
588     # -n/--dry-run invalidates some other options which would involve things happening
589     if Options["No-Action"]:
590         Options["Automatic"] = ""
591
592     # Check that we aren't going to clash with the daily cron job
593     if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (cnf["Dir::Lock"])) and not Options["No-Lock"]:
594         utils.fubar("Archive maintenance in progress.  Try again later.")
595
596     # Obtain lock if not in no-action mode and initialize the log
597     if not Options["No-Action"]:
598         lock_fd = os.open(os.path.join(cnf["Dir::Lock"], 'dinstall.lock'), os.O_RDWR | os.O_CREAT)
599         try:
600             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
601         except IOError as e:
602             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
603                 utils.fubar("Couldn't obtain lock; assuming another 'dak process-upload' is already running.")
604             else:
605                 raise
606
607         # Initialise UrgencyLog() - it will deal with the case where we don't
608         # want to log urgencies
609         urgencylog = UrgencyLog()
610
611     Logger = daklog.Logger("process-upload", Options["No-Action"])
612
613     # If we have a directory flag, use it to find our files
614     if cnf["Dinstall::Options::Directory"] != "":
615         # Note that we clobber the list of files we were given in this case
616         # so warn if the user has done both
617         if len(changes_files) > 0:
618             utils.warn("Directory provided so ignoring files given on command line")
619
620         changes_files = utils.get_changes_files(cnf["Dinstall::Options::Directory"])
621         Logger.log(["Using changes files from directory", cnf["Dinstall::Options::Directory"], len(changes_files)])
622     elif not len(changes_files) > 0:
623         utils.fubar("No changes files given and no directory specified")
624     else:
625         Logger.log(["Using changes files from command-line", len(changes_files)])
626
627     process_changes(changes_files)
628
629     if summarystats.accept_count:
630         sets = "set"
631         if summarystats.accept_count > 1:
632             sets = "sets"
633         print "Installed %d package %s, %s." % (summarystats.accept_count, sets,
634                                                 utils.size_type(int(summarystats.accept_bytes)))
635         Logger.log(["total", summarystats.accept_count, summarystats.accept_bytes])
636
637     if summarystats.reject_count:
638         sets = "set"
639         if summarystats.reject_count > 1:
640             sets = "sets"
641         print "Rejected %d package %s." % (summarystats.reject_count, sets)
642         Logger.log(["rejected", summarystats.reject_count])
643
644     if not Options["No-Action"]:
645         urgencylog.close()
646
647     Logger.close()
648
649 ###############################################################################
650
651 if __name__ == '__main__':
652     main()