]> git.decadent.org.uk Git - dak.git/blob - dak/generate_releases.py
let generate_releases be able to use multiple keys for a signature
[dak.git] / dak / generate_releases.py
1 #!/usr/bin/env python
2
3 """
4 Create all the Release files
5
6 @contact: Debian FTPMaster <ftpmaster@debian.org>
7 @copyright: 2011  Joerg Jaspert <joerg@debian.org>
8 @copyright: 2011  Mark Hymers <mhy@debian.org>
9 @license: GNU General Public License version 2 or later
10
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 ################################################################################
28
29 # <mhy> I wish they wouldnt leave biscuits out, thats just tempting. Damnit.
30
31 ################################################################################
32
33 import sys
34 import os
35 import os.path
36 import stat
37 import time
38 import gzip
39 import bz2
40 import apt_pkg
41 from tempfile import mkstemp, mkdtemp
42 import commands
43 from sqlalchemy.orm import object_session
44
45 from daklib import utils, daklog
46 from daklib.regexes import re_gensubrelease, re_includeinrelease
47 from daklib.dak_exceptions import *
48 from daklib.dbconn import *
49 from daklib.config import Config
50 from daklib.dakmultiprocessing import DakProcessPool, PROC_STATUS_SUCCESS
51
52 ################################################################################
53 Logger = None                  #: Our logging object
54
55 ################################################################################
56
57 def usage (exit_code=0):
58     """ Usage information"""
59
60     print """Usage: dak generate-releases [OPTIONS]
61 Generate the Release files
62
63   -a, --archive=ARCHIVE      process suites in ARCHIVE
64   -s, --suite=SUITE(s)       process this suite
65                              Default: All suites not marked 'untouchable'
66   -f, --force                Allow processing of untouchable suites
67                              CAREFUL: Only to be used at (point) release time!
68   -h, --help                 show this help and exit
69   -q, --quiet                Don't output progress
70
71 SUITE can be a space seperated list, e.g.
72    --suite=unstable testing
73   """
74     sys.exit(exit_code)
75
76 ########################################################################
77
78 def sign_release_dir(suite, dirname):
79     cnf = Config()
80
81     if cnf.has_key("Dinstall::SigningKeyring"):
82         keyring = "--secret-keyring \"%s\"" % cnf["Dinstall::SigningKeyring"]
83         if cnf.has_key("Dinstall::SigningPubKeyring"):
84             keyring += " --keyring \"%s\"" % cnf["Dinstall::SigningPubKeyring"]
85
86         arguments = "--no-options --batch --no-tty --armour"
87
88         relname = os.path.join(dirname, 'Release')
89
90         dest = os.path.join(dirname, 'Release.gpg')
91         if os.path.exists(dest):
92             os.unlink(dest)
93
94         inlinedest = os.path.join(dirname, 'InRelease')
95         if os.path.exists(inlinedest):
96             os.unlink(inlinedest)
97
98         for keyid in suite.signingkeys or []:
99             defkeyid = "--local-user %s" % keyid
100
101         os.system("gpg %s %s %s --detach-sign <%s >>%s" %
102                   (keyring, defkeyid, arguments, relname, dest))
103         os.system("gpg %s %s %s --clearsign <%s >>%s" %
104                   (keyring, defkeyid, arguments, relname, inlinedest))
105
106 class ReleaseWriter(object):
107     def __init__(self, suite):
108         self.suite = suite
109
110     def generate_release_files(self):
111         """
112         Generate Release files for the given suite
113
114         @type suite: string
115         @param suite: Suite name
116         """
117
118         suite = self.suite
119         session = object_session(suite)
120
121         architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
122
123         # Attribs contains a tuple of field names and the database names to use to
124         # fill them in
125         attribs = ( ('Origin',      'origin'),
126                     ('Label',       'label'),
127                     ('Suite',       'suite_name'),
128                     ('Version',     'version'),
129                     ('Codename',    'codename') )
130
131         # A "Sub" Release file has slightly different fields
132         subattribs = ( ('Archive',  'suite_name'),
133                        ('Origin',   'origin'),
134                        ('Label',    'label'),
135                        ('Version',  'version') )
136
137         # Boolean stuff. If we find it true in database, write out "yes" into the release file
138         boolattrs = ( ('NotAutomatic',         'notautomatic'),
139                       ('ButAutomaticUpgrades', 'butautomaticupgrades') )
140
141         cnf = Config()
142
143         suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
144
145         outfile = os.path.join(suite.archive.path, 'dists', suite.suite_name, suite_suffix, "Release")
146         out = open(outfile + ".new", "w")
147
148         for key, dbfield in attribs:
149             if getattr(suite, dbfield) is not None:
150                 # TEMPORARY HACK HACK HACK until we change the way we store the suite names etc
151                 if key == 'Suite' and getattr(suite, dbfield) == 'squeeze-updates':
152                     out.write("Suite: oldstable-updates\n")
153                 elif key == 'Suite' and getattr(suite, dbfield) == 'wheezy-updates':
154                     out.write("Suite: stable-updates\n")
155                 elif key == 'Suite' and getattr(suite, dbfield) == 'jessie-updates':
156                     out.write("Suite: testing-updates\n")
157                 else:
158                     out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
159
160         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
161
162         if suite.validtime:
163             validtime=float(suite.validtime)
164             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
165
166         for key, dbfield in boolattrs:
167             if getattr(suite, dbfield, False):
168                 out.write("%s: yes\n" % (key))
169
170         out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
171
172         components = [ c.component_name for c in session.query(Component) ]
173
174         out.write("Components: %s\n" % (" ".join(components)))
175
176         # For exact compatibility with old g-r, write out Description here instead
177         # of with the rest of the DB fields above
178         if getattr(suite, 'description') is not None:
179             out.write("Description: %s\n" % suite.description)
180
181         for comp in components:
182             for dirpath, dirnames, filenames in os.walk(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix, comp), topdown=True):
183                 if not re_gensubrelease.match(dirpath):
184                     continue
185
186                 subfile = os.path.join(dirpath, "Release")
187                 subrel = open(subfile + '.new', "w")
188
189                 for key, dbfield in subattribs:
190                     if getattr(suite, dbfield) is not None:
191                         subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
192
193                 for key, dbfield in boolattrs:
194                     if getattr(suite, dbfield, False):
195                         subrel.write("%s: yes\n" % (key))
196
197                 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
198
199                 # Urgh, but until we have all the suite/component/arch stuff in the DB,
200                 # this'll have to do
201                 arch = os.path.split(dirpath)[-1]
202                 if arch.startswith('binary-'):
203                     arch = arch[7:]
204
205                 subrel.write("Architecture: %s\n" % (arch))
206                 subrel.close()
207
208                 os.rename(subfile + '.new', subfile)
209
210         # Now that we have done the groundwork, we want to get off and add the files with
211         # their checksums to the main Release file
212         oldcwd = os.getcwd()
213
214         os.chdir(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix))
215
216         hashfuncs = { 'MD5Sum' : apt_pkg.md5sum,
217                       'SHA1' : apt_pkg.sha1sum,
218                       'SHA256' : apt_pkg.sha256sum }
219
220         fileinfo = {}
221
222         uncompnotseen = {}
223
224         for dirpath, dirnames, filenames in os.walk(".", followlinks=True, topdown=True):
225             for entry in filenames:
226                 # Skip things we don't want to include
227                 if not re_includeinrelease.match(entry):
228                     continue
229
230                 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
231                     continue
232
233                 filename = os.path.join(dirpath.lstrip('./'), entry)
234                 fileinfo[filename] = {}
235                 contents = open(filename, 'r').read()
236
237                 # If we find a file for which we have a compressed version and
238                 # haven't yet seen the uncompressed one, store the possibility
239                 # for future use
240                 if entry.endswith(".gz") and entry[:-3] not in uncompnotseen.keys():
241                     uncompnotseen[filename[:-3]] = (gzip.GzipFile, filename)
242                 elif entry.endswith(".bz2") and entry[:-4] not in uncompnotseen.keys():
243                     uncompnotseen[filename[:-4]] = (bz2.BZ2File, filename)
244
245                 fileinfo[filename]['len'] = len(contents)
246
247                 for hf, func in hashfuncs.items():
248                     fileinfo[filename][hf] = func(contents)
249
250         for filename, comp in uncompnotseen.items():
251             # If we've already seen the uncompressed file, we don't
252             # need to do anything again
253             if filename in fileinfo.keys():
254                 continue
255
256             # Skip uncompressed Contents files as they're huge, take ages to
257             # checksum and we checksum the compressed ones anyways
258             if os.path.basename(filename).startswith("Contents"):
259                 continue
260
261             fileinfo[filename] = {}
262
263             # File handler is comp[0], filename of compressed file is comp[1]
264             contents = comp[0](comp[1], 'r').read()
265
266             fileinfo[filename]['len'] = len(contents)
267
268             for hf, func in hashfuncs.items():
269                 fileinfo[filename][hf] = func(contents)
270
271
272         for h in sorted(hashfuncs.keys()):
273             out.write('%s:\n' % h)
274             for filename in sorted(fileinfo.keys()):
275                 out.write(" %s %8d %s\n" % (fileinfo[filename][h], fileinfo[filename]['len'], filename))
276
277         out.close()
278         os.rename(outfile + '.new', outfile)
279
280         sign_release_dir(suite, os.path.dirname(outfile))
281
282         os.chdir(oldcwd)
283
284         return
285
286
287 def main ():
288     global Logger
289
290     cnf = Config()
291
292     for i in ["Help", "Suite", "Force", "Quiet"]:
293         if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
294             cnf["Generate-Releases::Options::%s" % (i)] = ""
295
296     Arguments = [('h',"help","Generate-Releases::Options::Help"),
297                  ('a','archive','Generate-Releases::Options::Archive','HasArg'),
298                  ('s',"suite","Generate-Releases::Options::Suite"),
299                  ('f',"force","Generate-Releases::Options::Force"),
300                  ('q',"quiet","Generate-Releases::Options::Quiet"),
301                  ('o','option','','ArbItem')]
302
303     suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
304     Options = cnf.subtree("Generate-Releases::Options")
305
306     if Options["Help"]:
307         usage()
308
309     Logger = daklog.Logger('generate-releases')
310     pool = DakProcessPool()
311
312     session = DBConn().session()
313
314     if Options["Suite"]:
315         suites = []
316         for s in suite_names:
317             suite = get_suite(s.lower(), session)
318             if suite:
319                 suites.append(suite)
320             else:
321                 print "cannot find suite %s" % s
322                 Logger.log(['cannot find suite %s' % s])
323     else:
324         query = session.query(Suite).filter(Suite.untouchable == False)
325         if 'Archive' in Options:
326             query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
327         suites = query.all()
328
329     broken=[]
330
331     for s in suites:
332         # Setup a multiprocessing Pool. As many workers as we have CPU cores.
333         if s.untouchable and not Options["Force"]:
334             print "Skipping %s (untouchable)" % s.suite_name
335             continue
336
337         if not Options["Quiet"]:
338             print "Processing %s" % s.suite_name
339         Logger.log(['Processing release file for Suite: %s' % (s.suite_name)])
340         pool.apply_async(generate_helper, (s.suite_id, ))
341
342     # No more work will be added to our pool, close it and then wait for all to finish
343     pool.close()
344     pool.join()
345
346     retcode = pool.overall_status()
347
348     if retcode > 0:
349         # TODO: CENTRAL FUNCTION FOR THIS / IMPROVE LOGGING
350         Logger.log(['Release file generation broken: %s' % (','.join([str(x[1]) for x in pool.results]))])
351
352     Logger.close()
353
354     sys.exit(retcode)
355
356 def generate_helper(suite_id):
357     '''
358     This function is called in a new subprocess.
359     '''
360     session = DBConn().session()
361     suite = Suite.get(suite_id, session)
362
363     # We allow the process handler to catch and deal with any exceptions
364     rw = ReleaseWriter(suite)
365     rw.generate_release_files()
366
367     return (PROC_STATUS_SUCCESS, 'Release file written for %s' % suite.suite_name)
368
369 #######################################################################################
370
371 if __name__ == '__main__':
372     main()