]> git.decadent.org.uk Git - dak.git/blob - dak/process_upload.py
dak/process_upload.py: update for multi-archive changes
[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 from errno import EACCES, EAGAIN
164 import fcntl
165 import os
166 import sys
167 import traceback
168 import apt_pkg
169 import time
170 from sqlalchemy.orm.exc import NoResultFound
171
172 from daklib import daklog
173 from daklib.dbconn import *
174 from daklib.urgencylog import UrgencyLog
175 from daklib.summarystats import SummaryStats
176 from daklib.config import Config
177 import daklib.utils as utils
178 from daklib.textutils import fix_maintainer
179 from daklib.regexes import *
180
181 import daklib.archive
182 import daklib.upload
183
184 ###############################################################################
185
186 Options = None
187 Logger = None
188
189 ###############################################################################
190
191 def usage (exit_code=0):
192     print """Usage: dak process-upload [OPTION]... [CHANGES]...
193   -a, --automatic           automatic run
194   -d, --directory <DIR>     process uploads in <DIR>
195   -h, --help                show this help and exit.
196   -n, --no-action           don't do anything
197   -p, --no-lock             don't check lockfile !! for cron.daily only !!
198   -s, --no-mail             don't send any mail
199   -V, --version             display the version number and exit"""
200     sys.exit(exit_code)
201
202 ###############################################################################
203
204 def try_or_reject(function):
205     """Try to call function or reject the upload if that fails
206     """
207     def wrapper(directory, upload, *args, **kwargs):
208         try:
209             return function(directory, upload, *args, **kwargs)
210         except Exception as e:
211             try:
212                 reason = "There was an uncaught exception when processing your upload:\n{0}\nAny original reject reason follows below.".format(traceback.format_exc())
213                 upload.rollback()
214                 return real_reject(directory, upload, reason=reason)
215             except Exception as e:
216                 reason = "In addition there was an exception when rejecting the package:\n{0}\nPrevious reasons:\n{1}".format(traceback.format_exc(), reason)
217                 upload.rollback()
218                 return real_reject(directory, upload, reason=reason, notify=False)
219
220     return wrapper
221
222 def subst_for_upload(upload):
223     cnf = Config()
224
225     changes = upload.changes
226     control = upload.changes.changes
227
228     if upload.final_suites is None or len(upload.final_suites) == 0:
229         suite_name = '(unknown)'
230     else:
231         suite_names = []
232         for suite in upload.final_suites:
233             if suite.policy_queue:
234                 suite_names.append("{0}->{1}".format(suite.suite_name, suite.policy_queue.queue_name))
235             else:
236                 suite_names.append(suite.suite_name)
237         suite_name = ','.join(suite_names)
238
239     maintainer_field = control.get('Changed-By', control.get('Maintainer', cnf['Dinstall::MyEmailAddress']))
240     maintainer = fix_maintainer(maintainer_field)
241     addresses = utils.mail_addresses_for_upload(control.get('Maintainer', cnf['Dinstall::MyEmailAddress']), maintainer_field, changes.primary_fingerprint)
242
243     bcc = 'X-DAK: dak process-upload'
244     if 'Dinstall::Bcc' in cnf:
245         bcc = '{0}\nBcc: {1}'.format(bcc, cnf['Dinstall::Bcc'])
246
247     subst = {
248         '__DISTRO__': cnf['Dinstall::MyDistribution'],
249         '__ADMIN_ADDRESS__': cnf['Dinstall::MyAdminAddress'],
250
251         '__CHANGES_FILENAME__': upload.changes.filename,
252
253         '__SOURCE__': control.get('Source', '(unknown)'),
254         '__ARCHITECTURE__': control.get('Architecture', '(unknown)'),
255         '__VERSION__': control.get('Version', '(unknown)'),
256
257         '__SUITE__': suite_name,
258
259         '__DAK_ADDRESS__': cnf['Dinstall::MyEmailAddress'],
260         '__MAINTAINER_FROM__': maintainer[1],
261         '__MAINTAINER_TO__': ", ".join(addresses),
262         '__MAINTAINER__': maintainer_field,
263         '__BCC__': bcc,
264
265         '__BUG_SERVER__': cnf.get('Dinstall::BugServer'),
266
267         # TODO: don't use private member
268         '__FILE_CONTENTS__': upload.changes._signed_file.contents,
269
270         # __REJECT_MESSAGE__
271         }
272
273     override_maintainer = cnf.get('Dinstall::OverrideMaintainer')
274     if override_maintainer:
275         subst['__MAINTAINER_TO__'] = subst['__MAINTAINER_FROM__'] = override_maintainer
276
277     return subst
278
279 @try_or_reject
280 def accept(directory, upload):
281     cnf = Config()
282
283     Logger.log(['ACCEPT', upload.changes.filename])
284
285     upload.install()
286
287     accepted_to_real_suite = False
288     for suite in upload.final_suites:
289         accepted_to_real_suite = accepted_to_real_suite or suite.policy_queue is None
290
291     control = upload.changes.changes
292     if 'source' in upload.changes.architectures and not Options['No-Action']:
293         urgency = control.get('Urgency')
294         if urgency not in cnf.value_list('Urgency::Valid'):
295             urgency = cnf['Urgency::Default']
296         UrgencyLog().log(control['Source'], control['Version'], urgency)
297
298     # send mail to maintainer
299     subst = subst_for_upload(upload)
300     message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.accepted'))
301     utils.send_mail(message)
302
303     # send mail to announce lists and tracking server
304     subst = subst_for_upload(upload)
305     announce = set()
306     for suite in upload.final_suites:
307         if suite.policy_queue is None:
308             continue
309         announce.update(suite.announce or [])
310     announce_address = ", ".join(announce)
311     tracking = cnf.get('Dinstall::TrackingServer')
312     if tracking and 'source' in upload.changes.architectures:
313         announce_address = '{0}\nBcc: {1}@{2}'.format(announce_address, control['Source'], tracking)
314     message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.announce'))
315     utils.send_mail(message)
316
317     # Only close bugs for uploads that were not redirected to a policy queue.
318     # process-policy will close bugs for those once they are accepted.
319     subst = subst_for_upload(upload)
320     if accepted_to_real_suite and cnf.find_b('Dinstall::CloseBugs') and upload.changes.source is not None:
321         for bugnum in upload.changes.closed_bugs:
322             subst['__BUG_NUMBER__'] = str(bugnum)
323
324             message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.bug-close'))
325             utils.send_mail(message)
326
327             del subst['__BUG_NUMBER__']
328
329     # Move .changes to done, but only for uploads that were accepted to a
330     # real suite.  process-policy will handle this for uploads to queues.
331     if accepted_to_real_suite:
332         src = os.path.join(upload.directory, upload.changes.filename)
333
334         now = datetime.datetime.now()
335         donedir = os.path.join(cnf['Dir::Done'], now.strftime('%Y/%m/%d'))
336         dst = os.path.join(donedir, upload.changes.filename)
337         dst = utils.find_next_free(dst)
338
339         upload.transaction.fs.copy(src, dst, mode=0o644)
340
341     SummaryStats().accept_count += 1
342     SummaryStats().accept_bytes += upload.changes.bytes
343
344 @try_or_reject
345 def accept_to_new(directory, upload):
346     cnf = Config()
347
348     Logger.log(['ACCEPT-TO-NEW', upload.changes.filename])
349
350     upload.install_to_new()
351     # TODO: tag bugs pending, send announcement
352
353     subst = subst_for_upload(upload)
354     message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'process-unchecked.new'))
355     utils.send_mail(message)
356
357     SummaryStats().accept_count += 1
358     SummaryStats().accept_bytes += upload.changes.bytes
359
360 @try_or_reject
361 def reject(directory, upload, reason=None, notify=True):
362     real_reject(directory, upload, reason, notify)
363
364 def real_reject(directory, upload, reason=None, notify=True):
365     # XXX: rejection itself should go to daklib.archive.ArchiveUpload
366     cnf = Config()
367
368     Logger.log(['REJECT', upload.changes.filename])
369
370     fs = upload.transaction.fs
371     rejectdir = cnf['Dir::Reject']
372
373     files = [ f.filename for f in upload.changes.files.itervalues() ]
374     files.append(upload.changes.filename)
375
376     for fn in files:
377         src = os.path.join(upload.directory, fn)
378         dst = utils.find_next_free(os.path.join(rejectdir, fn))
379         fs.copy(src, dst)
380
381     if upload.reject_reasons is not None:
382         if reason is None:
383             reason = ''
384         reason = reason + '\n' + '\n'.join(upload.reject_reasons)
385
386     if reason is None:
387         reason = '(Unknown reason. Please check logs.)'
388
389     dst = utils.find_next_free(os.path.join(rejectdir, '{0}.reason'.format(upload.changes.filename)))
390     fh = fs.create(dst)
391     fh.write(reason)
392     fh.close()
393
394     # TODO: fix
395     if notify:
396         subst = subst_for_upload(upload)
397         subst['__REJECTOR_ADDRESS__'] = cnf['Dinstall::MyEmailAddress']
398         subst['__MANUAL_REJECT_MESSAGE__'] = ''
399         subst['__REJECT_MESSAGE__'] = reason
400         subst['__CC__'] = 'X-DAK-Rejection: automatic (moo)'
401
402         message = utils.TemplateSubst(subst, os.path.join(cnf['Dir::Templates'], 'queue.rejected'))
403         utils.send_mail(message)
404
405     SummaryStats().reject_count += 1
406
407 ###############################################################################
408
409 def action(directory, upload):
410     changes = upload.changes
411     processed = True
412
413     global Logger
414
415     cnf = Config()
416
417     okay = upload.check()
418
419     summary = changes.changes.get('Changes', '')
420
421     package_info = []
422     if okay:
423         if changes.source is not None:
424             package_info.append("source:{0}".format(changes.source.dsc['Source']))
425         for binary in changes.binaries:
426             package_info.append("binary:{0}".format(binary.control['Package']))
427
428     (prompt, answer) = ("", "XXX")
429     if Options["No-Action"] or Options["Automatic"]:
430         answer = 'S'
431
432     queuekey = ''
433
434     print summary
435     print
436     print "\n".join(package_info)
437     print
438
439     if len(upload.reject_reasons) > 0:
440         print "Reason:"
441         print "\n".join(upload.reject_reasons)
442         print
443
444         path = os.path.join(directory, changes.filename)
445         created = os.stat(path).st_mtime
446         now = time.time()
447         too_new = (now - created < int(cnf['Dinstall::SkipTime']))
448
449         if too_new:
450             print "SKIP (too new)"
451             prompt = "[S]kip, Quit ?"
452         else:
453             prompt = "[R]eject, Skip, Quit ?"
454             if Options["Automatic"]:
455                 answer = 'R'
456     elif upload.new:
457         prompt = "[N]ew, Skip, Quit ?"
458         if Options['Automatic']:
459             answer = 'N'
460     else:
461         prompt = "[A]ccept, Skip, Quit ?"
462         if Options['Automatic']:
463             answer = 'A'
464
465     while prompt.find(answer) == -1:
466         answer = utils.our_raw_input(prompt)
467         m = re_default_answer.match(prompt)
468         if answer == "":
469             answer = m.group(1)
470         answer = answer[:1].upper()
471
472     if answer == 'R':
473         reject(directory, upload)
474     elif answer == 'A':
475         # upload.try_autobyhand must not be run with No-Action.
476         if Options['No-Action']:
477             accept(directory, upload)
478         elif upload.try_autobyhand():
479             accept(directory, upload)
480         else:
481             print "W: redirecting to BYHAND as automatic processing failed."
482             accept_to_new(directory, upload)
483     elif answer == 'N':
484         accept_to_new(directory, upload)
485     elif answer == 'Q':
486         sys.exit(0)
487     elif answer == 'S':
488         processed = False
489
490     #raise Exception("FAIL")
491     if not Options['No-Action']:
492         upload.commit()
493
494     return processed
495
496 ###############################################################################
497
498 def unlink_if_exists(path):
499     try:
500         os.unlink(path)
501     except OSError as e:
502         if e.errno != errno.ENOENT:
503             raise
504
505 def process_it(directory, changes, keyrings, session):
506     global Logger
507
508     print "\n{0}\n".format(changes.filename)
509     Logger.log(["Processing changes file", changes.filename])
510
511     cnf = Config()
512
513     # Some defaults in case we can't fully process the .changes file
514     #u.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
515     #u.pkg.changes["changedby2047"] = cnf["Dinstall::MyEmailAddress"]
516
517     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
518     bcc = "X-DAK: dak process-upload"
519     #if cnf.has_key("Dinstall::Bcc"):
520     #    u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
521     #else:
522     #    u.Subst["__BCC__"] = bcc
523
524     with daklib.archive.ArchiveUpload(directory, changes, keyrings) as upload:
525         processed = action(directory, upload)
526         if processed and not Options['No-Action']:
527             unlink_if_exists(os.path.join(directory, changes.filename))
528             for fn in changes.files:
529                 unlink_if_exists(os.path.join(directory, fn))
530
531 ###############################################################################
532
533 def process_changes(changes_filenames):
534     session = DBConn().session()
535     keyrings = session.query(Keyring).filter_by(active=True).order_by(Keyring.priority)
536     keyring_files = [ k.keyring_name for k in keyrings ]
537
538     changes = []
539     for fn in changes_filenames:
540         try:
541             directory, filename = os.path.split(fn)
542             c = daklib.upload.Changes(directory, filename, keyring_files)
543             changes.append([directory, c])
544         except Exception as e:
545             Logger.log([filename, "Error while loading changes: {0}".format(e)])
546
547     changes.sort(key=lambda x: x[1])
548
549     for directory, c in changes:
550         process_it(directory, c, keyring_files, session)
551
552     session.rollback()
553
554 ###############################################################################
555
556 def main():
557     global Options, Logger
558
559     cnf = Config()
560     summarystats = SummaryStats()
561
562     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
563                  ('h',"help","Dinstall::Options::Help"),
564                  ('n',"no-action","Dinstall::Options::No-Action"),
565                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
566                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
567                  ('d',"directory", "Dinstall::Options::Directory", "HasArg")]
568
569     for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
570               "version", "directory"]:
571         if not cnf.has_key("Dinstall::Options::%s" % (i)):
572             cnf["Dinstall::Options::%s" % (i)] = ""
573
574     changes_files = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
575     Options = cnf.subtree("Dinstall::Options")
576
577     if Options["Help"]:
578         usage()
579
580     # -n/--dry-run invalidates some other options which would involve things happening
581     if Options["No-Action"]:
582         Options["Automatic"] = ""
583
584     # Check that we aren't going to clash with the daily cron job
585     if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (cnf["Dir::Lock"])) and not Options["No-Lock"]:
586         utils.fubar("Archive maintenance in progress.  Try again later.")
587
588     # Obtain lock if not in no-action mode and initialize the log
589     if not Options["No-Action"]:
590         lock_fd = os.open(os.path.join(cnf["Dir::Lock"], 'dinstall.lock'), os.O_RDWR | os.O_CREAT)
591         try:
592             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
593         except IOError as e:
594             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
595                 utils.fubar("Couldn't obtain lock; assuming another 'dak process-upload' is already running.")
596             else:
597                 raise
598
599         # Initialise UrgencyLog() - it will deal with the case where we don't
600         # want to log urgencies
601         urgencylog = UrgencyLog()
602
603     Logger = daklog.Logger("process-upload", Options["No-Action"])
604
605     # If we have a directory flag, use it to find our files
606     if cnf["Dinstall::Options::Directory"] != "":
607         # Note that we clobber the list of files we were given in this case
608         # so warn if the user has done both
609         if len(changes_files) > 0:
610             utils.warn("Directory provided so ignoring files given on command line")
611
612         changes_files = utils.get_changes_files(cnf["Dinstall::Options::Directory"])
613         Logger.log(["Using changes files from directory", cnf["Dinstall::Options::Directory"], len(changes_files)])
614     elif not len(changes_files) > 0:
615         utils.fubar("No changes files given and no directory specified")
616     else:
617         Logger.log(["Using changes files from command-line", len(changes_files)])
618
619     process_changes(changes_files)
620
621     if summarystats.accept_count:
622         sets = "set"
623         if summarystats.accept_count > 1:
624             sets = "sets"
625         print "Installed %d package %s, %s." % (summarystats.accept_count, sets,
626                                                 utils.size_type(int(summarystats.accept_bytes)))
627         Logger.log(["total", summarystats.accept_count, summarystats.accept_bytes])
628
629     if summarystats.reject_count:
630         sets = "set"
631         if summarystats.reject_count > 1:
632             sets = "sets"
633         print "Rejected %d package %s." % (summarystats.reject_count, sets)
634         Logger.log(["rejected", summarystats.reject_count])
635
636     if not Options["No-Action"]:
637         urgencylog.close()
638
639     Logger.close()
640
641 ###############################################################################
642
643 if __name__ == '__main__':
644     main()