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