]> git.decadent.org.uk Git - dak.git/blob - dak/import_known_changes.py
now actuall working
[dak.git] / dak / import_known_changes.py
1 #!/usr/bin/env python
2 # coding=utf8
3
4 """
5 Import known_changes files
6
7 @contact: Debian FTP Master <ftpmaster@debian.org>
8 @copyright: 2009  Mike O'Connor <stew@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 ################################################################################
27
28
29 ################################################################################
30
31 import sys
32 import os
33 import logging
34 import threading
35 from daklib.dbconn import DBConn,get_knownchange
36 from daklib.config import Config
37 import apt_pkg
38 from daklib.dak_exceptions import DBUpdateError, InvalidDscError, ChangesUnicodeError
39 from daklib.changes import Changes
40 from daklib.utils import parse_changes, warn, gpgv_get_status_output, process_gpgv_output
41 import traceback
42
43 # where in dak.conf all of our configuration will be stowed
44 options_prefix = "KnownChanges"
45 options_prefix = "%s::Options" % options_prefix
46
47 log = logging.getLogger()
48
49 ################################################################################
50
51
52 def usage (exit_code=0):
53     print """Usage: dak import-known-changes [options]
54
55 OPTIONS
56      -j n
57         run with n threads concurrently
58
59      -v, --verbose
60         show verbose information messages
61
62      -q, --quiet
63         supress all output but errors
64
65 """
66     sys.exit(exit_code)
67
68 def check_signature (sig_filename, data_filename=""):
69     keyrings = [
70         "/home/joerg/keyring/keyrings/debian-keyring.gpg",
71         "/home/joerg/keyring/keyrings/debian-keyring.pgp",
72         "/home/joerg/keyring/keyrings/debian-maintainers.gpg",
73         "/home/joerg/keyring/keyrings/debian-role-keys.gpg",
74         "/home/joerg/keyring/keyrings/emeritus-keyring.pgp",
75         "/home/joerg/keyring/keyrings/emeritus-keyring.gpg",
76         "/home/joerg/keyring/keyrings/removed-keys.gpg",
77         "/home/joerg/keyring/keyrings/removed-keys.pgp"
78         ]
79
80     keyringargs = " ".join(["--keyring %s" % x for x in keyrings ])
81
82     # Build the command line
83     status_read, status_write = os.pipe()
84     cmd = "gpgv --status-fd %s %s %s" % (status_write, keyringargs, sig_filename)
85
86     # Invoke gpgv on the file
87     (output, status, exit_status) = gpgv_get_status_output(cmd, status_read, status_write)
88
89     # Process the status-fd output
90     (keywords, internal_error) = process_gpgv_output(status)
91
92     # If we failed to parse the status-fd output, let's just whine and bail now
93     if internal_error:
94         warn("Couldn't parse signature")
95         return None
96
97     # usually one would check for bad things here. We, however, do not care.
98
99     # Next check gpgv exited with a zero return code
100     if exit_status:
101         warn("Couldn't parse signature")
102         return None
103
104     # Sanity check the good stuff we expect
105     if not keywords.has_key("VALIDSIG"):
106         warn("Couldn't parse signature")
107     else:
108         args = keywords["VALIDSIG"]
109         if len(args) < 1:
110             warn("Couldn't parse signature")
111         else:
112             fingerprint = args[0]
113
114     return fingerprint
115
116
117 class EndOfChanges(object):
118     """something enqueued to signify the last change"""
119     pass
120
121
122 class OneAtATime(object):
123     """
124     a one space queue which sits between multiple possible producers
125     and multiple possible consumers
126     """
127     def __init__(self):
128         self.next_in_line = None
129         self.next_lock = threading.Condition()
130
131     def enqueue(self, next):
132         self.next_lock.acquire()
133         while self.next_in_line:
134             self.next_lock.wait()
135
136         assert( not self.next_in_line )
137         self.next_in_line = next
138         self.next_lock.notify()
139         self.next_lock.release()
140
141     def dequeue(self):
142         self.next_lock.acquire()
143         while not self.next_in_line:
144             self.next_lock.wait()
145         result = self.next_in_line
146
147         if isinstance(result, EndOfChanges):
148             return None
149
150         self.next_in_line = None
151         self.next_lock.notify()
152         self.next_lock.release()
153         return result
154
155 class ChangesToImport(object):
156     """A changes file to be enqueued to be processed"""
157     def __init__(self, checkdir, changesfile, count):
158         self.dirpath = checkdir
159         self.changesfile = changesfile
160         self.count = count
161
162     def __str__(self):
163         return "#%d: %s in %s" % (self.count, self.changesfile, self.dirpath)
164
165 class ChangesGenerator(threading.Thread):
166     """enqueues changes files to be imported"""
167     def __init__(self, queue):
168         threading.Thread.__init__(self)
169         self.queue = queue
170         self.session = DBConn().session()
171
172     def run(self):
173         cnf = Config()
174         count = 1
175         for directory in [ "Accepted", "Byhand", "Done", "New", "ProposedUpdates", "OldProposedUpdates" ]:
176             checkdir = cnf["Dir::Queue::%s" % (directory) ]
177             if os.path.exists(checkdir):
178                 print "Looking into %s" % (checkdir)
179
180                 for dirpath, dirnames, filenames in os.walk(checkdir, topdown=False):
181                     if not filenames:
182                         # Empty directory (or only subdirectories), next
183                         continue
184                     for changesfile in filenames:
185                         if not changesfile.endswith(".changes"):
186                             # Only interested in changes files.
187                             continue
188                         count += 1
189
190                         if not get_knownchange(changesfile, self.session):
191                             to_import = ChangesToImport(dirpath, changesfile, count)
192                             print("enqueue: %s" % to_import)
193                             self.queue.enqueue(to_import)
194
195         self.queue.enqueue(EndOfChanges())
196
197 class ImportThread(threading.Thread):
198     def __init__(self, queue):
199         threading.Thread.__init__(self)
200         self.queue = queue
201         self.session = DBConn().session()
202
203     def run(self):
204         while True:
205             try:
206                 to_import = self.queue.dequeue()
207                 if not to_import:
208                     return
209
210                 print( "Directory %s, file %7d, (%s)" % (to_import.dirpath[-10:], to_import.count, to_import.changesfile) )
211
212                 changes = Changes()
213                 changes.changes_file = to_import.changesfile
214                 changesfile = os.path.join(to_import.dirpath, to_import.changesfile)
215                 print( "STU: %s / %s" % (to_import.dirpath, to_import.changesfile))
216                 changes.changes = parse_changes(changesfile, signing_rules=-1)
217                 changes.changes["fingerprint"] = check_signature(changesfile)
218                 changes.add_known_changes(to_import.dirpath, self.session)
219                 self.session.commit()
220
221             except InvalidDscError, line:
222                 warn("syntax error in .dsc file '%s', line %s." % (f, line))
223 #                failure += 1
224
225             except ChangesUnicodeError:
226                 warn("found invalid changes file, not properly utf-8 encoded")
227 #                failure += 1
228
229                 print "Directory %s, file %7d, failures %3d. (%s)" % (dirpath[-10:], count, failure, changesfile)
230
231
232             except:
233                 traceback.print_exc()
234
235 def main():
236     cnf = Config()
237
238     arguments = [('h',"help", "%s::%s" % (options_prefix,"Help")),
239                  ('j',"concurrency", "%s::%s" % (options_prefix,"Concurrency"),"HasArg"),
240                  ('q',"quiet", "%s::%s" % (options_prefix,"Quiet")),
241                  ('v',"verbose", "%s::%s" % (options_prefix,"Verbose")),
242                 ]
243
244     args = apt_pkg.ParseCommandLine(cnf.Cnf, arguments,sys.argv)
245
246     num_threads = 1
247
248     if len(args) > 0:
249         usage()
250
251     if cnf.has_key("%s::%s" % (options_prefix,"Help")):
252         usage()
253
254     level=logging.INFO
255     if cnf.has_key("%s::%s" % (options_prefix,"Quiet")):
256         level=logging.ERROR
257
258     elif cnf.has_key("%s::%s" % (options_prefix,"Verbose")):
259         level=logging.DEBUG
260
261
262     logging.basicConfig( level=level,
263                          format='%(asctime)s %(levelname)s %(message)s',
264                          stream = sys.stderr )
265
266     if Config().has_key( "%s::%s" %(options_prefix,"Concurrency")):
267         num_threads = int(Config()[ "%s::%s" %(options_prefix,"Concurrency")])
268
269
270     queue = OneAtATime()
271     ChangesGenerator(queue).start()
272
273     for i in range(num_threads):
274         ImportThread(queue).start()
275
276
277 if __name__ == '__main__':
278     main()