]> git.decadent.org.uk Git - dak.git/blob - dak/generate_releases.py
21eaac9ebed0ad9d21f71ee03a5fa9c5b1c0ece7
[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         # We can only use one key for inline signing so use the first one in
99         # the array for consistency
100         firstkey = True
101
102         for keyid in suite.signingkeys or []:
103             defkeyid = "--default-key %s" % keyid
104
105             os.system("gpg %s %s %s --detach-sign <%s >>%s" %
106                     (keyring, defkeyid, arguments, relname, dest))
107
108             if firstkey:
109                 os.system("gpg %s %s %s --clearsign <%s >>%s" %
110                         (keyring, defkeyid, arguments, relname, inlinedest))
111                 firstkey = False
112
113 class ReleaseWriter(object):
114     def __init__(self, suite):
115         self.suite = suite
116
117     def generate_release_files(self):
118         """
119         Generate Release files for the given suite
120
121         @type suite: string
122         @param suite: Suite name
123         """
124
125         suite = self.suite
126         session = object_session(suite)
127
128         architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
129
130         # Attribs contains a tuple of field names and the database names to use to
131         # fill them in
132         attribs = ( ('Origin',      'origin'),
133                     ('Label',       'label'),
134                     ('Suite',       'suite_name'),
135                     ('Version',     'version'),
136                     ('Codename',    'codename') )
137
138         # A "Sub" Release file has slightly different fields
139         subattribs = ( ('Archive',  'suite_name'),
140                        ('Origin',   'origin'),
141                        ('Label',    'label'),
142                        ('Version',  'version') )
143
144         # Boolean stuff. If we find it true in database, write out "yes" into the release file
145         boolattrs = ( ('NotAutomatic',         'notautomatic'),
146                       ('ButAutomaticUpgrades', 'butautomaticupgrades') )
147
148         cnf = Config()
149
150         suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
151
152         outfile = os.path.join(suite.archive.path, 'dists', suite.suite_name, suite_suffix, "Release")
153         out = open(outfile + ".new", "w")
154
155         for key, dbfield in attribs:
156             if getattr(suite, dbfield) is not None:
157                 # TEMPORARY HACK HACK HACK until we change the way we store the suite names etc
158                 if key == 'Suite' and getattr(suite, dbfield) == 'squeeze-updates':
159                     out.write("Suite: stable-updates\n")
160                 elif key == 'Suite' and getattr(suite, dbfield) == 'wheezy-updates':
161                     out.write("Suite: testing-updates\n")
162                 else:
163                     out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
164
165         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
166
167         if suite.validtime:
168             validtime=float(suite.validtime)
169             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
170
171         for key, dbfield in boolattrs:
172             if getattr(suite, dbfield, False):
173                 out.write("%s: yes\n" % (key))
174
175         out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
176
177         components = [ c.component_name for c in session.query(Component) ]
178
179         out.write("Components: %s\n" % ( " ".join(map(lambda x: "%s%s" % (suite_suffix, x), components ))))
180
181         # For exact compatibility with old g-r, write out Description here instead
182         # of with the rest of the DB fields above
183         if getattr(suite, 'description') is not None:
184             out.write("Description: %s\n" % suite.description)
185
186         for comp in components:
187             for dirpath, dirnames, filenames in os.walk(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix, comp), topdown=True):
188                 if not re_gensubrelease.match(dirpath):
189                     continue
190
191                 subfile = os.path.join(dirpath, "Release")
192                 subrel = open(subfile + '.new', "w")
193
194                 for key, dbfield in subattribs:
195                     if getattr(suite, dbfield) is not None:
196                         subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
197
198                 for key, dbfield in boolattrs:
199                     if getattr(suite, dbfield, False):
200                         subrel.write("%s: yes\n" % (key))
201
202                 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
203
204                 # Urgh, but until we have all the suite/component/arch stuff in the DB,
205                 # this'll have to do
206                 arch = os.path.split(dirpath)[-1]
207                 if arch.startswith('binary-'):
208                     arch = arch[7:]
209
210                 subrel.write("Architecture: %s\n" % (arch))
211                 subrel.close()
212
213                 os.rename(subfile + '.new', subfile)
214
215         # Now that we have done the groundwork, we want to get off and add the files with
216         # their checksums to the main Release file
217         oldcwd = os.getcwd()
218
219         os.chdir(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix))
220
221         hashfuncs = { 'MD5Sum' : apt_pkg.md5sum,
222                       'SHA1' : apt_pkg.sha1sum,
223                       'SHA256' : apt_pkg.sha256sum }
224
225         fileinfo = {}
226
227         uncompnotseen = {}
228
229         for dirpath, dirnames, filenames in os.walk(".", followlinks=True, topdown=True):
230             for entry in filenames:
231                 # Skip things we don't want to include
232                 if not re_includeinrelease.match(entry):
233                     continue
234
235                 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
236                     continue
237
238                 filename = os.path.join(dirpath.lstrip('./'), entry)
239                 fileinfo[filename] = {}
240                 contents = open(filename, 'r').read()
241
242                 # If we find a file for which we have a compressed version and
243                 # haven't yet seen the uncompressed one, store the possibility
244                 # for future use
245                 if entry.endswith(".gz") and entry[:-3] not in uncompnotseen.keys():
246                     uncompnotseen[filename[:-3]] = (gzip.GzipFile, filename)
247                 elif entry.endswith(".bz2") and entry[:-4] not in uncompnotseen.keys():
248                     uncompnotseen[filename[:-4]] = (bz2.BZ2File, filename)
249
250                 fileinfo[filename]['len'] = len(contents)
251
252                 for hf, func in hashfuncs.items():
253                     fileinfo[filename][hf] = func(contents)
254
255         for filename, comp in uncompnotseen.items():
256             # If we've already seen the uncompressed file, we don't
257             # need to do anything again
258             if filename in fileinfo.keys():
259                 continue
260
261             # Skip uncompressed Contents files as they're huge, take ages to
262             # checksum and we checksum the compressed ones anyways
263             if os.path.basename(filename).startswith("Contents"):
264                 continue
265
266             fileinfo[filename] = {}
267
268             # File handler is comp[0], filename of compressed file is comp[1]
269             contents = comp[0](comp[1], 'r').read()
270
271             fileinfo[filename]['len'] = len(contents)
272
273             for hf, func in hashfuncs.items():
274                 fileinfo[filename][hf] = func(contents)
275
276
277         for h in sorted(hashfuncs.keys()):
278             out.write('%s:\n' % h)
279             for filename in sorted(fileinfo.keys()):
280                 out.write(" %s %8d %s\n" % (fileinfo[filename][h], fileinfo[filename]['len'], filename))
281
282         out.close()
283         os.rename(outfile + '.new', outfile)
284
285         sign_release_dir(suite, os.path.dirname(outfile))
286
287         os.chdir(oldcwd)
288
289         return
290
291
292 def main ():
293     global Logger
294
295     cnf = Config()
296
297     for i in ["Help", "Suite", "Force", "Quiet"]:
298         if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
299             cnf["Generate-Releases::Options::%s" % (i)] = ""
300
301     Arguments = [('h',"help","Generate-Releases::Options::Help"),
302                  ('a','archive','Generate-Releases::Options::Archive','HasArg'),
303                  ('s',"suite","Generate-Releases::Options::Suite"),
304                  ('f',"force","Generate-Releases::Options::Force"),
305                  ('q',"quiet","Generate-Releases::Options::Quiet"),
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     pool = DakProcessPool()
316
317     session = DBConn().session()
318
319     if Options["Suite"]:
320         suites = []
321         for s in suite_names:
322             suite = get_suite(s.lower(), session)
323             if suite:
324                 suites.append(suite)
325             else:
326                 print "cannot find suite %s" % s
327                 Logger.log(['cannot find suite %s' % s])
328     else:
329         query = session.query(Suite).filter(Suite.untouchable == False)
330         if 'Archive' in Options:
331             query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
332         suites = query.all()
333
334     broken=[]
335
336     for s in suites:
337         # Setup a multiprocessing Pool. As many workers as we have CPU cores.
338         if s.untouchable and not Options["Force"]:
339             print "Skipping %s (untouchable)" % s.suite_name
340             continue
341
342         if not Options["Quiet"]:
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()