]> git.decadent.org.uk Git - dak.git/blob - dak/process_upload.py
hack to see if it helps cleanup
[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 from errno import EACCES, EAGAIN
163 import fcntl
164 import os
165 import sys
166 import traceback
167 import apt_pkg
168 from sqlalchemy.orm.exc import NoResultFound
169
170 from daklib import daklog
171 from daklib.queue import *
172 from daklib.queue_install import *
173 from daklib import utils
174 from daklib.dbconn import *
175 from daklib.urgencylog import UrgencyLog
176 from daklib.summarystats import SummaryStats
177 from daklib.holding import Holding
178 from daklib.config import Config
179
180 ###############################################################################
181
182 Options = None
183 Logger = None
184
185 ###############################################################################
186
187 def usage (exit_code=0):
188     print """Usage: dak process-upload [OPTION]... [CHANGES]...
189   -a, --automatic           automatic run
190   -h, --help                show this help and exit.
191   -n, --no-action           don't do anything
192   -p, --no-lock             don't check lockfile !! for cron.daily only !!
193   -s, --no-mail             don't send any mail
194   -V, --version             display the version number and exit"""
195     sys.exit(exit_code)
196
197 ###############################################################################
198
199 def byebye():
200     if not Options["No-Action"]:
201         # Clean out the queue files
202         session = DBConn().session()
203         session.execute("DELETE FROM changes_pending_files WHERE id NOT IN (SELECT file_id FROM changes_pending_files_map )")
204         session.commit()
205
206
207
208 def action(u, session):
209     cnf = Config()
210     holding = Holding()
211
212     # changes["distribution"] may not exist in corner cases
213     # (e.g. unreadable changes files)
214     if not u.pkg.changes.has_key("distribution") or not isinstance(u.pkg.changes["distribution"], dict):
215         u.pkg.changes["distribution"] = {}
216
217     (summary, short_summary) = u.build_summaries()
218
219     (prompt, answer) = ("", "XXX")
220     if Options["No-Action"] or Options["Automatic"]:
221         answer = 'S'
222
223     queuekey = ''
224
225     pi = u.package_info()
226
227     try:
228         chg = session.query(DBChange).filter_by(changesname=os.path.basename(u.pkg.changes_file)).one()
229     except NoResultFound, e:
230         chg = None
231
232     if len(u.rejects) > 0:
233         if u.upload_too_new():
234             print "SKIP (too new)\n" + pi,
235             prompt = "[S]kip, Quit ?"
236         else:
237             print "REJECT\n" + pi
238             prompt = "[R]eject, Skip, Quit ?"
239             if Options["Automatic"]:
240                 answer = 'R'
241     else:
242         # Are we headed for NEW / BYHAND / AUTOBYHAND?
243         # Note that policy queues are no longer handled here
244         qu = determine_target(u)
245         if qu:
246             print "%s for %s\n%s%s" % ( qu.upper(), ", ".join(u.pkg.changes["distribution"].keys()), pi, summary)
247             queuekey = qu[0].upper()
248             if queuekey in "RQSA":
249                 queuekey = "D"
250                 prompt = "[D]ivert, Skip, Quit ?"
251             else:
252                 prompt = "[%s]%s, Skip, Quit ?" % (queuekey, qu[1:].lower())
253             if Options["Automatic"]:
254                 answer = queuekey
255         else:
256             # Does suite have a policy_queue configured
257             divert = False
258             for s in u.pkg.changes["distribution"].keys():
259                 suite = get_suite(s, session)
260                 if suite.policy_queue:
261                     if not chg or chg.approved_for_id != su.policy_queue.policy_queue_id:
262                         # This routine will check whether the upload is a binary
263                         # upload when the source is already in the target suite.  If
264                         # so, we skip the policy queue, otherwise we go there.
265                         divert = package_to_suite(u, suite.suite_name, session=session)
266                         if divert:
267                             print "%s for %s\n%s%s" % ( suite.policy_queue.queue_name.upper(),
268                                                         ", ".join(u.pkg.changes["distribution"].keys()),
269                                                         pi, summary)
270                             queuekey = "P"
271                             prompt = "[P]olicy, Skip, Quit ?"
272                             policyqueue = suite.policy_queue
273                             if Options["Automatic"]:
274                                 answer = 'P'
275                             break
276
277             if not divert:
278                 print "ACCEPT\n" + pi + summary,
279                 prompt = "[A]ccept, Skip, Quit ?"
280                 if Options["Automatic"]:
281                     answer = 'A'
282
283     while prompt.find(answer) == -1:
284         answer = utils.our_raw_input(prompt)
285         m = re_default_answer.match(prompt)
286         if answer == "":
287             answer = m.group(1)
288         answer = answer[:1].upper()
289
290     if answer == 'R':
291         os.chdir(u.pkg.directory)
292         u.do_reject(0, pi)
293     elif answer == 'A':
294         if not chg:
295             chg = u.pkg.add_known_changes(holding.holding_dir, session=session)
296         session.commit()
297         u.accept(summary, short_summary, session)
298         u.check_override()
299         chg.clean_from_queue()
300         session.commit()
301         u.remove()
302     elif answer == 'P':
303         if not chg:
304             chg = u.pkg.add_known_changes(holding.holding_dir, session=session)
305         package_to_queue(u, summary, short_summary, policyqueue, chg, session)
306         session.commit()
307         u.remove()
308     elif answer == queuekey:
309         if not chg:
310             chg = u.pkg.add_known_changes(holding.holding_dir, session=session)
311         QueueInfo[qu]["process"](u, summary, short_summary, chg, session)
312         session.commit()
313         u.remove()
314     elif answer == 'Q':
315         byebye()
316         sys.exit(0)
317
318     session.commit()
319
320 ###############################################################################
321
322 def cleanup():
323     h = Holding()
324     if not Options["No-Action"]:
325         h.clean()
326
327 def process_it(changes_file, session):
328     global Logger
329
330     Logger.log(["Processing changes file", changes_file])
331
332     cnf = Config()
333
334     holding = Holding()
335
336     # TODO: Actually implement using pending* tables so that we don't lose track
337     #       of what is where
338
339     u = Upload()
340     u.pkg.changes_file = changes_file
341     u.pkg.directory = os.getcwd()
342     u.logger = Logger
343     origchanges = os.path.abspath(u.pkg.changes_file)
344
345     # Some defaults in case we can't fully process the .changes file
346     u.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
347     u.pkg.changes["changedby2047"] = cnf["Dinstall::MyEmailAddress"]
348
349     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
350     bcc = "X-DAK: dak process-upload"
351     if cnf.has_key("Dinstall::Bcc"):
352         u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
353     else:
354         u.Subst["__BCC__"] = bcc
355
356     # Remember where we are so we can come back after cd-ing into the
357     # holding directory.  TODO: Fix this stupid hack
358     u.prevdir = os.getcwd()
359
360     try:
361         # If this is the Real Thing(tm), copy things into a private
362         # holding directory first to avoid replacable file races.
363         if not Options["No-Action"]:
364             os.chdir(cnf["Dir::Queue::Holding"])
365
366             # Absolutize the filename to avoid the requirement of being in the
367             # same directory as the .changes file.
368             holding.copy_to_holding(origchanges)
369
370             # Relativize the filename so we use the copy in holding
371             # rather than the original...
372             changespath = os.path.basename(u.pkg.changes_file)
373         else:
374             changespath = origchanges
375
376         (u.pkg.changes["fingerprint"], rejects) = utils.check_signature(changespath)
377
378         if u.pkg.changes["fingerprint"]:
379             valid_changes_p = u.load_changes(changespath)
380         else:
381             valid_changes_p = False
382             u.rejects.extend(rejects)
383
384         if valid_changes_p:
385             u.check_distributions()
386             u.check_files(not Options["No-Action"])
387             valid_dsc_p = u.check_dsc(not Options["No-Action"])
388             if valid_dsc_p and not Options["No-Action"]:
389                 u.check_source()
390                 u.check_lintian()
391             u.check_hashes()
392             u.check_urgency()
393             u.check_timestamps()
394             u.check_signed_by_key()
395
396         action(u, session)
397
398     except (SystemExit, KeyboardInterrupt):
399         cleanup()
400         raise
401
402     except:
403         print "ERROR"
404         traceback.print_exc(file=sys.stderr)
405
406     cleanup()
407     # Restore previous WD
408     os.chdir(u.prevdir)
409
410 ###############################################################################
411
412 def main():
413     global Options, Logger
414
415     cnf = Config()
416     summarystats = SummaryStats()
417     log_urgency = False
418
419     DBConn()
420
421     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
422                  ('h',"help","Dinstall::Options::Help"),
423                  ('n',"no-action","Dinstall::Options::No-Action"),
424                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
425                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
426                  ('d',"directory", "Dinstall::Options::Directory", "HasArg")]
427
428     for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
429               "version", "directory"]:
430         if not cnf.has_key("Dinstall::Options::%s" % (i)):
431             cnf["Dinstall::Options::%s" % (i)] = ""
432
433     changes_files = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
434     Options = cnf.SubTree("Dinstall::Options")
435
436     if Options["Help"]:
437         usage()
438
439     # -n/--dry-run invalidates some other options which would involve things happening
440     if Options["No-Action"]:
441         Options["Automatic"] = ""
442
443     # Check that we aren't going to clash with the daily cron job
444     if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (cnf["Dir::Lock"])) and not Options["No-Lock"]:
445         utils.fubar("Archive maintenance in progress.  Try again later.")
446
447     # Obtain lock if not in no-action mode and initialize the log
448     if not Options["No-Action"]:
449         lock_fd = os.open(cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
450         try:
451             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
452         except IOError, e:
453             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
454                 utils.fubar("Couldn't obtain lock; assuming another 'dak process-upload' is already running.")
455             else:
456                 raise
457         if cnf.get("Dir::UrgencyLog"):
458             # Initialise UrgencyLog()
459             log_urgency = True
460             UrgencyLog()
461
462     Logger = daklog.Logger(cnf, "process-upload", Options["No-Action"])
463
464     # If we have a directory flag, use it to find our files
465     if cnf["Dinstall::Options::Directory"] != "":
466         # Note that we clobber the list of files we were given in this case
467         # so warn if the user has done both
468         if len(changes_files) > 0:
469             utils.warn("Directory provided so ignoring files given on command line")
470
471         changes_files = utils.get_changes_files(cnf["Dinstall::Options::Directory"])
472         Logger.log(["Using changes files from directory", cnf["Dinstall::Options::Directory"], len(changes_files)])
473     elif not len(changes_files) > 0:
474         utils.fubar("No changes files given and no directory specified")
475     else:
476         Logger.log(["Using changes files from command-line", len(changes_files)])
477
478     # Sort the .changes files so that we process sourceful ones first
479     changes_files.sort(utils.changes_compare)
480
481     # Process the changes files
482     for changes_file in changes_files:
483         print "\n" + changes_file
484         session = DBConn().session()
485         process_it(changes_file, session)
486         session.close()
487
488     if summarystats.accept_count:
489         sets = "set"
490         if summarystats.accept_count > 1:
491             sets = "sets"
492         print "Installed %d package %s, %s." % (summarystats.accept_count, sets,
493                                                 utils.size_type(int(summarystats.accept_bytes)))
494         Logger.log(["total", summarystats.accept_count, summarystats.accept_bytes])
495
496     byebye()
497
498     if not Options["No-Action"]:
499         if log_urgency:
500             UrgencyLog().close()
501
502     Logger.close()
503
504 ###############################################################################
505
506 if __name__ == '__main__':
507     main()