4 Create all the Release files
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
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.
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.
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
27 ################################################################################
29 # <mhy> I wish they wouldnt leave biscuits out, thats just tempting. Damnit.
31 ################################################################################
41 from tempfile import mkstemp, mkdtemp
43 from multiprocessing import Pool, TimeoutError
44 from sqlalchemy.orm import object_session
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
52 ################################################################################
53 Logger = None #: Our logging object
54 results = [] #: Results of the subprocesses
56 ################################################################################
58 def usage (exit_code=0):
59 """ Usage information"""
61 print """Usage: dak generate-releases [OPTIONS]
62 Generate the Release files
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
70 SUITE can be a space seperated list, e.g.
71 --suite=unstable testing
75 ########################################################################
82 def sign_release_dir(suite, dirname):
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"]
90 arguments = "--no-options --batch --no-tty --armour"
92 relname = os.path.join(dirname, 'Release')
94 dest = os.path.join(dirname, 'Release.gpg')
95 if os.path.exists(dest):
98 inlinedest = os.path.join(dirname, 'InRelease')
99 if os.path.exists(inlinedest):
100 os.unlink(inlinedest)
102 # We can only use one key for inline signing so use the first one in
103 # the array for consistency
106 for keyid in suite.signingkeys:
107 defkeyid = "--default-key %s" % keyid
109 os.system("gpg %s %s %s --detach-sign <%s >>%s" %
110 (keyring, defkeyid, arguments, relname, dest))
113 os.system("gpg %s %s %s --clearsign <%s >>%s" %
114 (keyring, defkeyid, arguments, relname, inlinedest))
117 class ReleaseWriter(object):
118 def __init__(self, suite):
121 def generate_release_files(self):
123 Generate Release files for the given suite
126 @param suite: Suite name
130 session = object_session(suite)
132 architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
134 # Attribs contains a tuple of field names and the database names to use to
136 attribs = ( ('Origin', 'origin'),
138 ('Suite', 'suite_name'),
139 ('Version', 'version'),
140 ('Codename', 'codename') )
142 # A "Sub" Release file has slightly different fields
143 subattribs = ( ('Archive', 'suite_name'),
144 ('Origin', 'origin'),
146 ('Version', 'version') )
148 # Boolean stuff. If we find it true in database, write out "yes" into the release file
149 boolattrs = ( ('NotAutomatic', 'notautomatic'),
150 ('ButAutomaticUpgrades', 'butautomaticupgrades') )
154 suite_suffix = "%s" % (cnf.Find("Dinstall::SuiteSuffix"))
156 outfile = os.path.join(cnf["Dir::Root"], 'dists', "%s/%s" % (suite.suite_name, suite_suffix), "Release")
157 out = open(outfile + ".new", "w")
159 for key, dbfield in attribs:
160 if getattr(suite, dbfield) is not None:
161 out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
163 out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
166 validtime=float(suite.validtime)
167 out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
169 for key, dbfield in boolattrs:
170 if getattr(suite, dbfield, False):
171 out.write("%s: yes\n" % (key))
173 out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
175 ## FIXME: Components need to be adjusted to whatever will be in the db
176 ## Needs putting in the DB
177 components = ['main', 'contrib', 'non-free']
179 out.write("Components: %s\n" % ( " ".join(map(lambda x: "%s%s" % (suite_suffix, x), components ))))
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)
186 for comp in components:
187 for dirpath, dirnames, filenames in os.walk("%sdists/%s/%s%s" % (cnf["Dir::Root"], suite.suite_name, suite_suffix, comp), topdown=True):
188 if not re_gensubrelease.match(dirpath):
191 subfile = os.path.join(dirpath, "Release")
192 subrel = open(subfile + '.new', "w")
194 for key, dbfield in subattribs:
195 if getattr(suite, dbfield) is not None:
196 subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
198 for key, dbfield in boolattrs:
199 if getattr(suite, dbfield, False):
200 subrel.write("%s: yes\n" % (key))
202 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
204 # Urgh, but until we have all the suite/component/arch stuff in the DB,
206 arch = os.path.split(dirpath)[-1]
207 if arch.startswith('binary-'):
210 subrel.write("Architecture: %s\n" % (arch))
213 os.rename(subfile + '.new', subfile)
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
219 os.chdir("%sdists/%s/%s" % (cnf["Dir::Root"], suite.suite_name, suite_suffix))
221 hashfuncs = { 'MD5Sum' : apt_pkg.md5sum,
222 'SHA1' : apt_pkg.sha1sum,
223 'SHA256' : apt_pkg.sha256sum }
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):
235 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
238 filename = os.path.join(dirpath.lstrip('./'), entry)
239 fileinfo[filename] = {}
240 contents = open(filename, 'r').read()
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
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)
250 fileinfo[filename]['len'] = len(contents)
252 for hf, func in hashfuncs.items():
253 fileinfo[filename][hf] = func(contents)
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():
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"):
266 fileinfo[filename] = {}
268 # File handler is comp[0], filename of compressed file is comp[1]
269 contents = comp[0](comp[1], 'r').read()
271 fileinfo[filename]['len'] = len(contents)
273 for hf, func in hashfuncs.items():
274 fileinfo[filename][hf] = func(contents)
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))
283 os.rename(outfile + '.new', outfile)
285 sign_release_dir(suite, os.path.dirname(outfile))
293 global Logger, results
297 for i in ["Help", "Suite", "Force"]:
298 if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
299 cnf["Generate-Releases::Options::%s" % (i)] = ""
301 Arguments = [('h',"help","Generate-Releases::Options::Help"),
302 ('s',"suite","Generate-Releases::Options::Suite"),
303 ('f',"force","Generate-Releases::Options::Force")]
305 suite_names = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
306 Options = cnf.SubTree("Generate-Releases::Options")
311 Logger = daklog.Logger(cnf, 'generate-releases')
313 session = DBConn().session()
317 for s in suite_names:
318 suite = get_suite(s.lower(), session)
322 print "cannot find suite %s" % s
323 Logger.log(['cannot find suite %s' % s])
325 suites = session.query(Suite).filter(Suite.untouchable == False).all()
328 # For each given suite, run one process
334 # Setup a multiprocessing Pool. As many workers as we have CPU cores.
335 if s.untouchable and not Options["Force"]:
336 print "Skipping %s (untouchable)" % s.suite_name
339 print "Processing %s" % s.suite_name
340 Logger.log(['Processing release file for Suite: %s' % (s.suite_name)])
341 pool.apply_async(generate_helper, (s.suite_id, ), callback=get_result)
343 # No more work will be added to our pool, close it and then wait for all to finish
350 Logger.log(['Release file generation broken: %s' % (results)])
351 print "Release file generation broken:\n", '\n'.join(results)
358 def generate_helper(suite_id):
360 This function is called in a new subprocess.
362 session = DBConn().session()
363 suite = Suite.get(suite_id, session)
365 rw = ReleaseWriter(suite)
366 rw.generate_release_files()
372 #######################################################################################
374 if __name__ == '__main__':