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