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