]> git.decadent.org.uk Git - dak.git/blob - dak/process_upload.py
Merge commit 'ftpmaster/master'
[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 import errno
129 import fcntl
130 import os
131 import sys
132 #from datetime import datetime
133 import traceback
134 import apt_pkg
135
136 from daklib import daklog
137 from daklib.queue import *
138 from daklib.queue_install import *
139 from daklib import utils
140 from daklib.dbconn import *
141 #from daklib.dak_exceptions import *
142 #from daklib.regexes import re_default_answer, re_issource, re_fdnic
143 from daklib.urgencylog import UrgencyLog
144 from daklib.summarystats import SummaryStats
145 from daklib.holding import Holding
146 from daklib.config import Config
147
148 ###############################################################################
149
150 Options = None
151 Logger = None
152
153 ###############################################################################
154
155 def usage (exit_code=0):
156     print """Usage: dak process-upload [OPTION]... [CHANGES]...
157   -a, --automatic           automatic run
158   -h, --help                show this help and exit.
159   -n, --no-action           don't do anything
160   -p, --no-lock             don't check lockfile !! for cron.daily only !!
161   -s, --no-mail             don't send any mail
162   -V, --version             display the version number and exit"""
163     sys.exit(exit_code)
164
165 ###############################################################################
166
167 def action(u):
168     cnf = Config()
169     holding = Holding()
170
171     # changes["distribution"] may not exist in corner cases
172     # (e.g. unreadable changes files)
173     if not u.pkg.changes.has_key("distribution") or not isinstance(u.pkg.changes["distribution"], DictType):
174         u.pkg.changes["distribution"] = {}
175
176     (summary, short_summary) = u.build_summaries()
177
178     (prompt, answer) = ("", "XXX")
179     if Options["No-Action"] or Options["Automatic"]:
180         answer = 'S'
181
182     queuekey = ''
183
184     pi = u.package_info()
185
186     if len(u.rejects) > 0:
187         if u.upload_too_new():
188             print "SKIP (too new)\n" + pi,
189             prompt = "[S]kip, Quit ?"
190         else:
191             print "REJECT\n" + pi
192             prompt = "[R]eject, Skip, Quit ?"
193             if Options["Automatic"]:
194                 answer = 'R'
195     else:
196         qu = determine_target(u)
197         if qu:
198             print "%s for %s\n%s%s" % ( qu.upper(), ", ".join(u.pkg.changes["distribution"].keys()), pi, summary)
199             queuekey = qu[0].upper()
200             if queuekey in "RQSA":
201                 queuekey = "D"
202                 prompt = "[D]ivert, Skip, Quit ?"
203             else:
204                 prompt = "[%s]%s, Skip, Quit ?" % (queuekey, qu[1:].lower())
205             if Options["Automatic"]:
206                 answer = queuekey
207         else:
208             print "ACCEPT\n" + pi + summary,
209             prompt = "[A]ccept, Skip, Quit ?"
210             if Options["Automatic"]:
211                 answer = 'A'
212
213     while prompt.find(answer) == -1:
214         answer = utils.our_raw_input(prompt)
215         m = re_default_answer.match(prompt)
216         if answer == "":
217             answer = m.group(1)
218         answer = answer[:1].upper()
219
220     session = DBConn().session()
221
222     if answer == 'R':
223         os.chdir(u.pkg.directory)
224         u.do_reject(0, pi)
225     elif answer == 'A':
226         u.pkg.add_known_changes(holding.holding_dir, session)
227         u.accept(summary, short_summary, session)
228         u.check_override()
229         u.remove()
230     elif answer == queuekey:
231         u.pkg.add_known_changes(holding.holding_dir, session)
232         QueueInfo[qu]["process"](u, summary, short_summary, session)
233         u.remove()
234     elif answer == 'Q':
235         sys.exit(0)
236
237     session.commit()
238
239 ###############################################################################
240
241 def cleanup():
242     h = Holding()
243     if not Options["No-Action"]:
244         h.clean()
245
246 def process_it(changes_file):
247     global Logger
248
249     Logger.log(["Processing changes file", changes_file])
250
251     cnf = Config()
252
253     holding = Holding()
254
255     u = Upload()
256     u.pkg.changes_file = changes_file
257     u.pkg.directory = os.getcwd()
258     u.logger = Logger
259     origchanges = os.path.abspath(u.pkg.changes_file)
260
261     # Some defaults in case we can't fully process the .changes file
262     u.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
263     u.pkg.changes["changedby2047"] = cnf["Dinstall::MyEmailAddress"]
264
265     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
266     bcc = "X-DAK: dak process-upload"
267     if cnf.has_key("Dinstall::Bcc"):
268         u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
269     else:
270         u.Subst["__BCC__"] = bcc
271
272     # Remember where we are so we can come back after cd-ing into the
273     # holding directory.  TODO: Fix this stupid hack
274     u.prevdir = os.getcwd()
275
276     try:
277         # If this is the Real Thing(tm), copy things into a private
278         # holding directory first to avoid replacable file races.
279         if not Options["No-Action"]:
280             os.chdir(cnf["Dir::Queue::Holding"])
281
282             # Absolutize the filename to avoid the requirement of being in the
283             # same directory as the .changes file.
284             holding.copy_to_holding(origchanges)
285
286             # Relativize the filename so we use the copy in holding
287             # rather than the original...
288             changespath = os.path.basename(u.pkg.changes_file)
289         else:
290             changespath = origchanges
291
292         (u.pkg.changes["fingerprint"], rejects) = utils.check_signature(changespath)
293
294         if u.pkg.changes["fingerprint"]:
295             valid_changes_p = u.load_changes(changespath)
296         else:
297             valid_changes_p = False
298             u.rejects.extend(rejects)
299
300         if valid_changes_p:
301             u.check_distributions()
302             u.check_files(not Options["No-Action"])
303             valid_dsc_p = u.check_dsc(not Options["No-Action"])
304             if valid_dsc_p and not Options["No-Action"]:
305                 u.check_source()
306                 u.check_lintian()
307             u.check_hashes()
308             u.check_urgency()
309             u.check_timestamps()
310             u.check_signed_by_key()
311
312         action(u)
313
314     except (SystemExit, KeyboardInterrupt):
315         cleanup()
316         raise
317
318     except:
319         print "ERROR"
320         traceback.print_exc(file=sys.stderr)
321
322     cleanup()
323     # Restore previous WD
324     os.chdir(u.prevdir)
325
326 ###############################################################################
327
328 def main():
329     global Options, Logger
330
331     cnf = Config()
332     summarystats = SummaryStats()
333     log_urgency = False
334
335     DBConn()
336
337     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
338                  ('h',"help","Dinstall::Options::Help"),
339                  ('n',"no-action","Dinstall::Options::No-Action"),
340                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
341                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
342                  ('d',"directory", "Dinstall::Options::Directory", "HasArg")]
343
344     for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
345               "version", "directory"]:
346         if not cnf.has_key("Dinstall::Options::%s" % (i)):
347             cnf["Dinstall::Options::%s" % (i)] = ""
348
349     changes_files = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
350     Options = cnf.SubTree("Dinstall::Options")
351
352     if Options["Help"]:
353         usage()
354
355     # -n/--dry-run invalidates some other options which would involve things happening
356     if Options["No-Action"]:
357         Options["Automatic"] = ""
358
359     # Check that we aren't going to clash with the daily cron job
360     if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (cnf["Dir::Lock"])) and not Options["No-Lock"]:
361         utils.fubar("Archive maintenance in progress.  Try again later.")
362
363     # Obtain lock if not in no-action mode and initialize the log
364     if not Options["No-Action"]:
365         lock_fd = os.open(cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
366         try:
367             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
368         except IOError, e:
369             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
370                 utils.fubar("Couldn't obtain lock; assuming another 'dak process-upload' is already running.")
371             else:
372                 raise
373         if cnf.get("Dir::UrgencyLog"):
374             # Initialise UrgencyLog()
375             log_urgency = True
376             UrgencyLog()
377
378     Logger = daklog.Logger(cnf, "process-upload", Options["No-Action"])
379
380     # If we have a directory flag, use it to find our files
381     if cnf["Dinstall::Options::Directory"] != "":
382         # Note that we clobber the list of files we were given in this case
383         # so warn if the user has done both
384         if len(changes_files) > 0:
385             utils.warn("Directory provided so ignoring files given on command line")
386
387         changes_files = utils.get_changes_files(cnf["Dinstall::Options::Directory"])
388         Logger.log(["Using changes files from directory", cnf["Dinstall::Options::Directory"], len(changes_files)])
389     elif not len(changes_files) > 0:
390         utils.fubar("No changes files given and no directory specified")
391     else:
392         Logger.log(["Using changes files from command-line", len(changes_files)])
393
394     # Sort the .changes files so that we process sourceful ones first
395     changes_files.sort(utils.changes_compare)
396
397     # Process the changes files
398     for changes_file in changes_files:
399         print "\n" + changes_file
400         session = DBConn().session()
401         process_it(changes_file)
402         session.close()
403
404     if summarystats.accept_count:
405         sets = "set"
406         if summarystats.accept_count > 1:
407             sets = "sets"
408         sys.stderr.write("Installed %d package %s, %s.\n" % (summarystats.accept_count, sets,
409                                                              utils.size_type(int(summarystats.accept_bytes))))
410         Logger.log(["total", summarystats.accept_count, summarystats.accept_bytes])
411
412     if not Options["No-Action"]:
413         if log_urgency:
414             UrgencyLog().close()
415     Logger.close()
416
417 ###############################################################################
418
419 if __name__ == '__main__':
420     main()