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