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 ################################################################################
42 from tempfile import mkstemp, mkdtemp
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
51 from daklib.dakmultiprocessing import DakProcessPool, PROC_STATUS_SUCCESS
52 import daklib.daksubprocess
54 ################################################################################
55 Logger = None #: Our logging object
57 ################################################################################
59 def usage (exit_code=0):
60 """ Usage information"""
62 print """Usage: dak generate-releases [OPTIONS]
63 Generate the Release files
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
73 SUITE can be a space separated list, e.g.
74 --suite=unstable testing
78 ########################################################################
80 def sign_release_dir(suite, dirname):
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"]
88 arguments = "--no-options --batch --no-tty --armour --personal-digest-preferences=SHA256"
90 relname = os.path.join(dirname, 'Release')
92 dest = os.path.join(dirname, 'Release.gpg')
93 if os.path.exists(dest):
96 inlinedest = os.path.join(dirname, 'InRelease')
97 if os.path.exists(inlinedest):
101 for keyid in suite.signingkeys or []:
102 defkeyid += "--local-user %s " % keyid
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))
109 class XzFile(object):
110 def __init__(self, filename, mode='r'):
111 self.filename = filename
114 with open(self.filename, 'r') as stdin:
115 process = daklib.daksubprocess.Popen(cmd, stdin=stdin, stdout=subprocess.PIPE)
116 (stdout, stderr) = process.communicate()
119 class ReleaseWriter(object):
120 def __init__(self, suite):
123 def generate_release_files(self):
125 Generate Release files for the given suite
128 @param suite: Suite name
132 session = object_session(suite)
134 architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
136 # Attribs contains a tuple of field names and the database names to use to
138 attribs = ( ('Origin', 'origin'),
140 ('Suite', 'release_suite_output'),
141 ('Version', 'version'),
142 ('Codename', 'codename'),
143 ('Changelogs', 'changelog_url'),
146 # A "Sub" Release file has slightly different fields
147 subattribs = ( ('Archive', 'suite_name'),
148 ('Origin', 'origin'),
150 ('Version', 'version') )
152 # Boolean stuff. If we find it true in database, write out "yes" into the release file
153 boolattrs = ( ('NotAutomatic', 'notautomatic'),
154 ('ButAutomaticUpgrades', 'butautomaticupgrades') )
158 suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
160 outfile = os.path.join(suite.archive.path, 'dists', suite.suite_name, suite_suffix, "Release")
161 out = open(outfile + ".new", "w")
163 for key, dbfield in attribs:
164 # Hack to skip NULL Version fields as we used to do this
165 # We should probably just always ignore anything which is None
166 if key in ("Version", "Changelogs") and getattr(suite, dbfield) is None:
169 out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
171 out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
174 validtime=float(suite.validtime)
175 out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
177 for key, dbfield in boolattrs:
178 if getattr(suite, dbfield, False):
179 out.write("%s: yes\n" % (key))
181 out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
183 components = [ c.component_name for c in suite.components ]
185 out.write("Components: %s\n" % (" ".join(components)))
187 # For exact compatibility with old g-r, write out Description here instead
188 # of with the rest of the DB fields above
189 if getattr(suite, 'description') is not None:
190 out.write("Description: %s\n" % suite.description)
192 for comp in components:
193 for dirpath, dirnames, filenames in os.walk(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix, comp), topdown=True):
194 if not re_gensubrelease.match(dirpath):
197 subfile = os.path.join(dirpath, "Release")
198 subrel = open(subfile + '.new', "w")
200 for key, dbfield in subattribs:
201 if getattr(suite, dbfield) is not None:
202 subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
204 for key, dbfield in boolattrs:
205 if getattr(suite, dbfield, False):
206 subrel.write("%s: yes\n" % (key))
208 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
210 # Urgh, but until we have all the suite/component/arch stuff in the DB,
212 arch = os.path.split(dirpath)[-1]
213 if arch.startswith('binary-'):
216 subrel.write("Architecture: %s\n" % (arch))
219 os.rename(subfile + '.new', subfile)
221 # Now that we have done the groundwork, we want to get off and add the files with
222 # their checksums to the main Release file
225 os.chdir(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix))
227 hashfuncs = { 'MD5Sum' : apt_pkg.md5sum,
228 'SHA1' : apt_pkg.sha1sum,
229 'SHA256' : apt_pkg.sha256sum }
235 for dirpath, dirnames, filenames in os.walk(".", followlinks=True, topdown=True):
236 for entry in filenames:
237 # Skip things we don't want to include
238 if not re_includeinrelease.match(entry):
241 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
244 filename = os.path.join(dirpath.lstrip('./'), entry)
245 fileinfo[filename] = {}
246 contents = open(filename, 'r').read()
248 # If we find a file for which we have a compressed version and
249 # haven't yet seen the uncompressed one, store the possibility
251 if entry.endswith(".gz") and filename[:-3] not in uncompnotseen:
252 uncompnotseen[filename[:-3]] = (gzip.GzipFile, filename)
253 elif entry.endswith(".bz2") and filename[:-4] not in uncompnotseen:
254 uncompnotseen[filename[:-4]] = (bz2.BZ2File, filename)
255 elif entry.endswith(".xz") and filename[:-3] not in uncompnotseen:
256 uncompnotseen[filename[:-3]] = (XzFile, filename)
258 fileinfo[filename]['len'] = len(contents)
260 for hf, func in hashfuncs.items():
261 fileinfo[filename][hf] = func(contents)
263 for filename, comp in uncompnotseen.items():
264 # If we've already seen the uncompressed file, we don't
265 # need to do anything again
266 if filename in fileinfo:
269 fileinfo[filename] = {}
271 # File handler is comp[0], filename of compressed file is comp[1]
272 contents = comp[0](comp[1], 'r').read()
274 fileinfo[filename]['len'] = len(contents)
276 for hf, func in hashfuncs.items():
277 fileinfo[filename][hf] = func(contents)
280 for h in sorted(hashfuncs.keys()):
281 out.write('%s:\n' % h)
282 for filename in sorted(fileinfo.keys()):
283 out.write(" %s %8d %s\n" % (fileinfo[filename][h], fileinfo[filename]['len'], filename))
286 os.rename(outfile + '.new', outfile)
288 sign_release_dir(suite, os.path.dirname(outfile))
300 for i in ["Help", "Suite", "Force", "Quiet"]:
301 if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
302 cnf["Generate-Releases::Options::%s" % (i)] = ""
304 Arguments = [('h',"help","Generate-Releases::Options::Help"),
305 ('a','archive','Generate-Releases::Options::Archive','HasArg'),
306 ('s',"suite","Generate-Releases::Options::Suite"),
307 ('f',"force","Generate-Releases::Options::Force"),
308 ('q',"quiet","Generate-Releases::Options::Quiet"),
309 ('o','option','','ArbItem')]
311 suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
312 Options = cnf.subtree("Generate-Releases::Options")
317 Logger = daklog.Logger('generate-releases')
318 pool = DakProcessPool()
320 session = DBConn().session()
324 for s in suite_names:
325 suite = get_suite(s.lower(), session)
329 print "cannot find suite %s" % s
330 Logger.log(['cannot find suite %s' % s])
332 query = session.query(Suite).filter(Suite.untouchable == False)
333 if 'Archive' in Options:
334 query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
340 # Setup a multiprocessing Pool. As many workers as we have CPU cores.
341 if s.untouchable and not Options["Force"]:
342 print "Skipping %s (untouchable)" % s.suite_name
345 if not Options["Quiet"]:
346 print "Processing %s" % s.suite_name
347 Logger.log(['Processing release file for Suite: %s' % (s.suite_name)])
348 pool.apply_async(generate_helper, (s.suite_id, ))
350 # No more work will be added to our pool, close it and then wait for all to finish
354 retcode = pool.overall_status()
357 # TODO: CENTRAL FUNCTION FOR THIS / IMPROVE LOGGING
358 Logger.log(['Release file generation broken: %s' % (','.join([str(x[1]) for x in pool.results]))])
364 def generate_helper(suite_id):
366 This function is called in a new subprocess.
368 session = DBConn().session()
369 suite = Suite.get(suite_id, session)
371 # We allow the process handler to catch and deal with any exceptions
372 rw = ReleaseWriter(suite)
373 rw.generate_release_files()
375 return (PROC_STATUS_SUCCESS, 'Release file written for %s' % suite.suite_name)
377 #######################################################################################
379 if __name__ == '__main__':