5 Import known_changes files
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
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.
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.
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
26 ################################################################################
29 ################################################################################
35 from daklib.dbconn import DBConn,get_knownchange
36 from daklib.config import Config
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
43 # where in dak.conf all of our configuration will be stowed
44 options_prefix = "KnownChanges"
45 options_prefix = "%s::Options" % options_prefix
47 log = logging.getLogger()
49 ################################################################################
52 def usage (exit_code=0):
53 print """Usage: dak import-known-changes [options]
57 run with n threads concurrently
60 show verbose information messages
63 supress all output but errors
68 def check_signature (sig_filename, data_filename=""):
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"
80 keyringargs = " ".join(["--keyring %s" % x for x in keyrings ])
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)
86 # Invoke gpgv on the file
87 (output, status, exit_status) = gpgv_get_status_output(cmd, status_read, status_write)
89 # Process the status-fd output
90 (keywords, internal_error) = process_gpgv_output(status)
92 # If we failed to parse the status-fd output, let's just whine and bail now
94 warn("Couldn't parse signature")
97 # usually one would check for bad things here. We, however, do not care.
99 # Next check gpgv exited with a zero return code
101 warn("Couldn't parse signature")
104 # Sanity check the good stuff we expect
105 if not keywords.has_key("VALIDSIG"):
106 warn("Couldn't parse signature")
108 args = keywords["VALIDSIG"]
110 warn("Couldn't parse signature")
112 fingerprint = args[0]
117 class EndOfChanges(object):
118 """something enqueued to signify the last change"""
122 class OneAtATime(object):
124 a one space queue which sits between multiple possible producers
125 and multiple possible consumers
128 self.next_in_line = None
129 self.next_lock = threading.Condition()
131 def enqueue(self, next):
132 self.next_lock.acquire()
133 while self.next_in_line:
134 self.next_lock.wait()
136 assert( not self.next_in_line )
137 self.next_in_line = next
138 self.next_lock.notify()
139 self.next_lock.release()
142 self.next_lock.acquire()
143 while not self.next_in_line:
144 self.next_lock.wait()
145 result = self.next_in_line
147 if isinstance(result, EndOfChanges):
150 self.next_in_line = None
151 self.next_lock.notify()
152 self.next_lock.release()
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
163 return "#%d: %s in %s" % (self.count, self.changesfile, self.dirpath)
165 class ChangesGenerator(threading.Thread):
166 """enqueues changes files to be imported"""
167 def __init__(self, queue):
168 threading.Thread.__init__(self)
170 self.session = DBConn().session()
179 for directory in [ "Accepted", "Byhand", "Done", "New", "ProposedUpdates", "OldProposedUpdates" ]:
180 checkdir = cnf["Dir::Queue::%s" % (directory) ]
181 if os.path.exists(checkdir):
182 print "Looking into %s" % (checkdir)
184 for dirpath, dirnames, filenames in os.walk(checkdir, topdown=False):
186 # Empty directory (or only subdirectories), next
191 for changesfile in filenames:
192 if not changesfile.endswith(".changes"):
193 # Only interested in changes files.
197 if not get_knownchange(changesfile, self.session):
198 to_import = ChangesToImport(dirpath, changesfile, count)
199 self.queue.enqueue(to_import)
201 self.queue.enqueue(EndOfChanges())
203 class ImportThread(threading.Thread):
204 def __init__(self, queue):
205 threading.Thread.__init__(self)
207 self.session = DBConn().session()
218 to_import = self.queue.dequeue()
222 print( "Directory %s, file %7d, (%s)" % (to_import.dirpath[-10:], to_import.count, to_import.changesfile) )
225 changes.changes_file = to_import.changesfile
226 changesfile = os.path.join(to_import.dirpath, to_import.changesfile)
227 changes.changes = parse_changes(changesfile, signing_rules=-1)
228 changes.changes["fingerprint"] = check_signature(changesfile)
229 changes.add_known_changes(to_import.dirpath, self.session)
230 self.session.commit()
232 except InvalidDscError, line:
233 warn("syntax error in .dsc file '%s', line %s." % (f, line))
236 except ChangesUnicodeError:
237 warn("found invalid changes file, not properly utf-8 encoded")
240 print "Directory %s, file %7d, failures %3d. (%s)" % (dirpath[-10:], count, failure, changesfile)
244 traceback.print_exc()
249 arguments = [('h',"help", "%s::%s" % (options_prefix,"Help")),
250 ('j',"concurrency", "%s::%s" % (options_prefix,"Concurrency"),"HasArg"),
251 ('q',"quiet", "%s::%s" % (options_prefix,"Quiet")),
252 ('v',"verbose", "%s::%s" % (options_prefix,"Verbose")),
255 args = apt_pkg.ParseCommandLine(cnf.Cnf, arguments,sys.argv)
262 if cnf.has_key("%s::%s" % (options_prefix,"Help")):
266 if cnf.has_key("%s::%s" % (options_prefix,"Quiet")):
269 elif cnf.has_key("%s::%s" % (options_prefix,"Verbose")):
273 logging.basicConfig( level=level,
274 format='%(asctime)s %(levelname)s %(message)s',
275 stream = sys.stderr )
277 if Config().has_key( "%s::%s" %(options_prefix,"Concurrency")):
278 num_threads = int(Config()[ "%s::%s" %(options_prefix,"Concurrency")])
282 threads = [ ChangesGenerator(queue) ]
284 for i in range(num_threads):
285 threads.append( ImportThread(queue) )
288 for thread in threads:
291 for thread in thrads:
294 except KeyboardInterrupt:
295 utils.warn("Caught C-c; terminating.")
296 for thread in threads:
299 for thread in threads:
303 if __name__ == '__main__':