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 -a, --archive=ARCHIVE process suites in ARCHIVE
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 -q, --quiet Don't output progress
71 SUITE can be a space seperated list, e.g.
72 --suite=unstable testing
76 ########################################################################
78 def sign_release_dir(suite, dirname):
81 if cnf.has_key("Dinstall::SigningKeyring"):
82 keyring = "--secret-keyring \"%s\"" % cnf["Dinstall::SigningKeyring"]
83 if cnf.has_key("Dinstall::SigningPubKeyring"):
84 keyring += " --keyring \"%s\"" % cnf["Dinstall::SigningPubKeyring"]
86 arguments = "--no-options --batch --no-tty --armour --personal-digest-preferences=SHA256"
88 relname = os.path.join(dirname, 'Release')
90 dest = os.path.join(dirname, 'Release.gpg')
91 if os.path.exists(dest):
94 inlinedest = os.path.join(dirname, 'InRelease')
95 if os.path.exists(inlinedest):
99 for keyid in suite.signingkeys or []:
100 defkeyid += "--local-user %s " % keyid
102 os.system("gpg %s %s %s --detach-sign <%s >>%s" %
103 (keyring, defkeyid, arguments, relname, dest))
104 os.system("gpg %s %s %s --clearsign <%s >>%s" %
105 (keyring, defkeyid, arguments, relname, inlinedest))
107 class ReleaseWriter(object):
108 def __init__(self, suite):
111 def generate_release_files(self):
113 Generate Release files for the given suite
116 @param suite: Suite name
120 session = object_session(suite)
122 architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
124 # Attribs contains a tuple of field names and the database names to use to
126 attribs = ( ('Origin', 'origin'),
128 ('Suite', 'suite_name'),
129 ('Version', 'version'),
130 ('Codename', 'codename') )
132 # A "Sub" Release file has slightly different fields
133 subattribs = ( ('Archive', 'suite_name'),
134 ('Origin', 'origin'),
136 ('Version', 'version') )
138 # Boolean stuff. If we find it true in database, write out "yes" into the release file
139 boolattrs = ( ('NotAutomatic', 'notautomatic'),
140 ('ButAutomaticUpgrades', 'butautomaticupgrades') )
144 suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
146 outfile = os.path.join(suite.archive.path, 'dists', suite.suite_name, suite_suffix, "Release")
147 out = open(outfile + ".new", "w")
149 for key, dbfield in attribs:
150 if getattr(suite, dbfield) is not None:
151 # TEMPORARY HACK HACK HACK until we change the way we store the suite names etc
152 if key == 'Suite' and getattr(suite, dbfield) == 'squeeze-updates':
153 out.write("Suite: oldstable-updates\n")
154 elif key == 'Suite' and getattr(suite, dbfield) == 'wheezy-updates':
155 out.write("Suite: stable-updates\n")
156 elif key == 'Suite' and getattr(suite, dbfield) == 'jessie-updates':
157 out.write("Suite: testing-updates\n")
159 out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
161 out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
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))))
167 for key, dbfield in boolattrs:
168 if getattr(suite, dbfield, False):
169 out.write("%s: yes\n" % (key))
171 out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
173 components = [ c.component_name for c in suite.components ]
175 out.write("Components: %s\n" % (" ".join(components)))
177 # For exact compatibility with old g-r, write out Description here instead
178 # of with the rest of the DB fields above
179 if getattr(suite, 'description') is not None:
180 out.write("Description: %s\n" % suite.description)
182 for comp in components:
183 for dirpath, dirnames, filenames in os.walk(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix, comp), topdown=True):
184 if not re_gensubrelease.match(dirpath):
187 subfile = os.path.join(dirpath, "Release")
188 subrel = open(subfile + '.new', "w")
190 for key, dbfield in subattribs:
191 if getattr(suite, dbfield) is not None:
192 subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
194 for key, dbfield in boolattrs:
195 if getattr(suite, dbfield, False):
196 subrel.write("%s: yes\n" % (key))
198 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
200 # Urgh, but until we have all the suite/component/arch stuff in the DB,
202 arch = os.path.split(dirpath)[-1]
203 if arch.startswith('binary-'):
206 subrel.write("Architecture: %s\n" % (arch))
209 os.rename(subfile + '.new', subfile)
211 # Now that we have done the groundwork, we want to get off and add the files with
212 # their checksums to the main Release file
215 os.chdir(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix))
217 hashfuncs = { 'MD5Sum' : apt_pkg.md5sum,
218 'SHA1' : apt_pkg.sha1sum,
219 'SHA256' : apt_pkg.sha256sum }
225 for dirpath, dirnames, filenames in os.walk(".", followlinks=True, topdown=True):
226 for entry in filenames:
227 # Skip things we don't want to include
228 if not re_includeinrelease.match(entry):
231 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
234 filename = os.path.join(dirpath.lstrip('./'), entry)
235 fileinfo[filename] = {}
236 contents = open(filename, 'r').read()
238 # If we find a file for which we have a compressed version and
239 # haven't yet seen the uncompressed one, store the possibility
241 if entry.endswith(".gz") and entry[:-3] not in uncompnotseen.keys():
242 uncompnotseen[filename[:-3]] = (gzip.GzipFile, filename)
243 elif entry.endswith(".bz2") and entry[:-4] not in uncompnotseen.keys():
244 uncompnotseen[filename[:-4]] = (bz2.BZ2File, filename)
246 fileinfo[filename]['len'] = len(contents)
248 for hf, func in hashfuncs.items():
249 fileinfo[filename][hf] = func(contents)
251 for filename, comp in uncompnotseen.items():
252 # If we've already seen the uncompressed file, we don't
253 # need to do anything again
254 if filename in fileinfo.keys():
257 # Skip uncompressed Contents files as they're huge, take ages to
258 # checksum and we checksum the compressed ones anyways
259 if os.path.basename(filename).startswith("Contents"):
262 fileinfo[filename] = {}
264 # File handler is comp[0], filename of compressed file is comp[1]
265 contents = comp[0](comp[1], 'r').read()
267 fileinfo[filename]['len'] = len(contents)
269 for hf, func in hashfuncs.items():
270 fileinfo[filename][hf] = func(contents)
273 for h in sorted(hashfuncs.keys()):
274 out.write('%s:\n' % h)
275 for filename in sorted(fileinfo.keys()):
276 out.write(" %s %8d %s\n" % (fileinfo[filename][h], fileinfo[filename]['len'], filename))
279 os.rename(outfile + '.new', outfile)
281 sign_release_dir(suite, os.path.dirname(outfile))
293 for i in ["Help", "Suite", "Force", "Quiet"]:
294 if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
295 cnf["Generate-Releases::Options::%s" % (i)] = ""
297 Arguments = [('h',"help","Generate-Releases::Options::Help"),
298 ('a','archive','Generate-Releases::Options::Archive','HasArg'),
299 ('s',"suite","Generate-Releases::Options::Suite"),
300 ('f',"force","Generate-Releases::Options::Force"),
301 ('q',"quiet","Generate-Releases::Options::Quiet"),
302 ('o','option','','ArbItem')]
304 suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
305 Options = cnf.subtree("Generate-Releases::Options")
310 Logger = daklog.Logger('generate-releases')
311 pool = DakProcessPool()
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 query = session.query(Suite).filter(Suite.untouchable == False)
326 if 'Archive' in Options:
327 query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
333 # Setup a multiprocessing Pool. As many workers as we have CPU cores.
334 if s.untouchable and not Options["Force"]:
335 print "Skipping %s (untouchable)" % s.suite_name
338 if not Options["Quiet"]:
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, ))
343 # No more work will be added to our pool, close it and then wait for all to finish
347 retcode = pool.overall_status()
350 # TODO: CENTRAL FUNCTION FOR THIS / IMPROVE LOGGING
351 Logger.log(['Release file generation broken: %s' % (','.join([str(x[1]) for x in pool.results]))])
357 def generate_helper(suite_id):
359 This function is called in a new subprocess.
361 session = DBConn().session()
362 suite = Suite.get(suite_id, session)
364 # We allow the process handler to catch and deal with any exceptions
365 rw = ReleaseWriter(suite)
366 rw.generate_release_files()
368 return (PROC_STATUS_SUCCESS, 'Release file written for %s' % suite.suite_name)
370 #######################################################################################
372 if __name__ == '__main__':