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 sqlalchemy.orm import object_session
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
52 ################################################################################
53 Logger = None #: Our logging object
55 ################################################################################
57 def usage (exit_code=0):
58 """ Usage information"""
60 print """Usage: dak generate-releases [OPTIONS]
61 Generate the Release files
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
69 SUITE can be a space seperated list, e.g.
70 --suite=unstable testing
74 ########################################################################
76 def sign_release_dir(suite, dirname):
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"]
84 arguments = "--no-options --batch --no-tty --armour"
86 relname = os.path.join(dirname, 'Release')
88 dest = os.path.join(dirname, 'Release.gpg')
89 if os.path.exists(dest):
92 inlinedest = os.path.join(dirname, 'InRelease')
93 if os.path.exists(inlinedest):
96 # We can only use one key for inline signing so use the first one in
97 # the array for consistency
100 for keyid in suite.signingkeys:
101 defkeyid = "--default-key %s" % keyid
103 os.system("gpg %s %s %s --detach-sign <%s >>%s" %
104 (keyring, defkeyid, arguments, relname, dest))
107 os.system("gpg %s %s %s --clearsign <%s >>%s" %
108 (keyring, defkeyid, arguments, relname, inlinedest))
111 class ReleaseWriter(object):
112 def __init__(self, suite):
115 def generate_release_files(self):
117 Generate Release files for the given suite
120 @param suite: Suite name
124 session = object_session(suite)
126 architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
128 # Attribs contains a tuple of field names and the database names to use to
130 attribs = ( ('Origin', 'origin'),
132 ('Suite', 'suite_name'),
133 ('Version', 'version'),
134 ('Codename', 'codename') )
136 # A "Sub" Release file has slightly different fields
137 subattribs = ( ('Archive', 'suite_name'),
138 ('Origin', 'origin'),
140 ('Version', 'version') )
142 # Boolean stuff. If we find it true in database, write out "yes" into the release file
143 boolattrs = ( ('NotAutomatic', 'notautomatic'),
144 ('ButAutomaticUpgrades', 'butautomaticupgrades') )
148 suite_suffix = "%s" % (cnf.Find("Dinstall::SuiteSuffix"))
150 outfile = os.path.join(cnf["Dir::Root"], 'dists', "%s/%s" % (suite.suite_name, suite_suffix), "Release")
151 out = open(outfile + ".new", "w")
153 for key, dbfield in attribs:
154 if getattr(suite, dbfield) is not None:
155 out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
157 out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
160 validtime=float(suite.validtime)
161 out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
163 for key, dbfield in boolattrs:
164 if getattr(suite, dbfield, False):
165 out.write("%s: yes\n" % (key))
167 out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
169 ## FIXME: Components need to be adjusted to whatever will be in the db
170 ## Needs putting in the DB
171 components = ['main', 'contrib', 'non-free']
173 out.write("Components: %s\n" % ( " ".join(map(lambda x: "%s%s" % (suite_suffix, x), components ))))
175 # For exact compatibility with old g-r, write out Description here instead
176 # of with the rest of the DB fields above
177 if getattr(suite, 'description') is not None:
178 out.write("Description: %s\n" % suite.description)
180 for comp in components:
181 for dirpath, dirnames, filenames in os.walk("%sdists/%s/%s%s" % (cnf["Dir::Root"], suite.suite_name, suite_suffix, comp), topdown=True):
182 if not re_gensubrelease.match(dirpath):
185 subfile = os.path.join(dirpath, "Release")
186 subrel = open(subfile + '.new', "w")
188 for key, dbfield in subattribs:
189 if getattr(suite, dbfield) is not None:
190 subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
192 for key, dbfield in boolattrs:
193 if getattr(suite, dbfield, False):
194 subrel.write("%s: yes\n" % (key))
196 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
198 # Urgh, but until we have all the suite/component/arch stuff in the DB,
200 arch = os.path.split(dirpath)[-1]
201 if arch.startswith('binary-'):
204 subrel.write("Architecture: %s\n" % (arch))
207 os.rename(subfile + '.new', subfile)
209 # Now that we have done the groundwork, we want to get off and add the files with
210 # their checksums to the main Release file
213 os.chdir("%sdists/%s/%s" % (cnf["Dir::Root"], suite.suite_name, suite_suffix))
215 hashfuncs = { 'MD5Sum' : apt_pkg.md5sum,
216 'SHA1' : apt_pkg.sha1sum,
217 'SHA256' : apt_pkg.sha256sum }
223 for dirpath, dirnames, filenames in os.walk(".", followlinks=True, topdown=True):
224 for entry in filenames:
225 # Skip things we don't want to include
226 if not re_includeinrelease.match(entry):
229 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
232 filename = os.path.join(dirpath.lstrip('./'), entry)
233 fileinfo[filename] = {}
234 contents = open(filename, 'r').read()
236 # If we find a file for which we have a compressed version and
237 # haven't yet seen the uncompressed one, store the possibility
239 if entry.endswith(".gz") and entry[:-3] not in uncompnotseen.keys():
240 uncompnotseen[filename[:-3]] = (gzip.GzipFile, filename)
241 elif entry.endswith(".bz2") and entry[:-4] not in uncompnotseen.keys():
242 uncompnotseen[filename[:-4]] = (bz2.BZ2File, filename)
244 fileinfo[filename]['len'] = len(contents)
246 for hf, func in hashfuncs.items():
247 fileinfo[filename][hf] = func(contents)
249 for filename, comp in uncompnotseen.items():
250 # If we've already seen the uncompressed file, we don't
251 # need to do anything again
252 if filename in fileinfo.keys():
255 # Skip uncompressed Contents files as they're huge, take ages to
256 # checksum and we checksum the compressed ones anyways
257 if os.path.basename(filename).startswith("Contents"):
260 fileinfo[filename] = {}
262 # File handler is comp[0], filename of compressed file is comp[1]
263 contents = comp[0](comp[1], 'r').read()
265 fileinfo[filename]['len'] = len(contents)
267 for hf, func in hashfuncs.items():
268 fileinfo[filename][hf] = func(contents)
271 for h in sorted(hashfuncs.keys()):
272 out.write('%s:\n' % h)
273 for filename in sorted(fileinfo.keys()):
274 out.write(" %s %8d %s\n" % (fileinfo[filename][h], fileinfo[filename]['len'], filename))
277 os.rename(outfile + '.new', outfile)
279 sign_release_dir(suite, os.path.dirname(outfile))
291 for i in ["Help", "Suite", "Force"]:
292 if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
293 cnf["Generate-Releases::Options::%s" % (i)] = ""
295 Arguments = [('h',"help","Generate-Releases::Options::Help"),
296 ('s',"suite","Generate-Releases::Options::Suite"),
297 ('f',"force","Generate-Releases::Options::Force")]
299 suite_names = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
300 Options = cnf.SubTree("Generate-Releases::Options")
305 Logger = daklog.Logger(cnf, 'generate-releases')
307 session = DBConn().session()
311 for s in suite_names:
312 suite = get_suite(s.lower(), session)
316 print "cannot find suite %s" % s
317 Logger.log(['cannot find suite %s' % s])
319 suites = session.query(Suite).filter(Suite.untouchable == False).all()
323 pool = DakProcessPool()
326 # Setup a multiprocessing Pool. As many workers as we have CPU cores.
327 if s.untouchable and not Options["Force"]:
328 print "Skipping %s (untouchable)" % s.suite_name
331 print "Processing %s" % s.suite_name
332 Logger.log(['Processing release file for Suite: %s' % (s.suite_name)])
333 pool.apply_async(generate_helper, (s.suite_id, ))
335 # No more work will be added to our pool, close it and then wait for all to finish
339 retcode = pool.overall_status()
342 # TODO: CENTRAL FUNCTION FOR THIS / IMPROVE LOGGING
343 Logger.log(['Release file generation broken: %s' % (','.join([str(x[1]) for x in pool.results]))])
349 def generate_helper(suite_id):
351 This function is called in a new subprocess.
353 session = DBConn().session()
354 suite = Suite.get(suite_id, session)
356 # We allow the process handler to catch and deal with any exceptions
357 rw = ReleaseWriter(suite)
358 rw.generate_release_files()
360 return (PROC_STATUS_SUCCESS, 'Release file written for %s' % suite.suite_name)
362 #######################################################################################
364 if __name__ == '__main__':