]> git.decadent.org.uk Git - dak.git/blob - dak/generate_releases.py
Move Release files to zzz-dists
[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 errno
41 import apt_pkg
42 import subprocess
43 from tempfile import mkstemp, mkdtemp
44 import commands
45 from sqlalchemy.orm import object_session
46
47 from daklib import utils, daklog
48 from daklib.regexes import re_gensubrelease, re_includeinrelease
49 from daklib.dak_exceptions import *
50 from daklib.dbconn import *
51 from daklib.config import Config
52 from daklib.dakmultiprocessing import DakProcessPool, PROC_STATUS_SUCCESS
53 import daklib.daksubprocess
54
55 ################################################################################
56 Logger = None                  #: Our logging object
57
58 ################################################################################
59
60 def usage (exit_code=0):
61     """ Usage information"""
62
63     print """Usage: dak generate-releases [OPTIONS]
64 Generate the Release files
65
66   -a, --archive=ARCHIVE      process suites in ARCHIVE
67   -s, --suite=SUITE(s)       process this suite
68                              Default: All suites not marked 'untouchable'
69   -f, --force                Allow processing of untouchable suites
70                              CAREFUL: Only to be used at (point) release time!
71   -h, --help                 show this help and exit
72   -q, --quiet                Don't output progress
73
74 SUITE can be a space separated list, e.g.
75    --suite=unstable testing
76   """
77     sys.exit(exit_code)
78
79 ########################################################################
80
81 def sign_release_dir(suite, dirname):
82     cnf = Config()
83
84     if cnf.has_key("Dinstall::SigningKeyring"):
85         keyring = "--secret-keyring \"%s\"" % cnf["Dinstall::SigningKeyring"]
86         if cnf.has_key("Dinstall::SigningPubKeyring"):
87             keyring += " --keyring \"%s\"" % cnf["Dinstall::SigningPubKeyring"]
88
89         arguments = "--no-options --batch --no-tty --armour --personal-digest-preferences=SHA256"
90
91         relname = os.path.join(dirname, 'Release')
92
93         dest = os.path.join(dirname, 'Release.gpg')
94         if os.path.exists(dest):
95             os.unlink(dest)
96
97         inlinedest = os.path.join(dirname, 'InRelease')
98         if os.path.exists(inlinedest):
99             os.unlink(inlinedest)
100
101         defkeyid=""
102         for keyid in suite.signingkeys or []:
103             defkeyid += "--local-user %s " % keyid
104
105         os.system("gpg %s %s %s --detach-sign <%s >>%s" %
106                   (keyring, defkeyid, arguments, relname, dest))
107         os.system("gpg %s %s %s --clearsign <%s >>%s" %
108                   (keyring, defkeyid, arguments, relname, inlinedest))
109
110 class XzFile(object):
111     def __init__(self, filename, mode='r'):
112         self.filename = filename
113     def read(self):
114         cmd = ("xz", "-d")
115         with open(self.filename, 'r') as stdin:
116             process = daklib.daksubprocess.Popen(cmd, stdin=stdin, stdout=subprocess.PIPE)
117             (stdout, stderr) = process.communicate()
118             return stdout
119
120 class ReleaseWriter(object):
121     def __init__(self, suite):
122         self.suite = suite
123
124     def suite_path(self):
125         """
126         Absolute path to the suite-specific files.
127         """
128         cnf = Config()
129         suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
130
131         return os.path.join(self.suite.archive.path, 'dists',
132                             self.suite.suite_name, suite_suffix)
133
134     def suite_release_path(self):
135         """
136         Absolute path where Release files are physically stored.
137         This should be a path that sorts after the dists/ directory.
138         """
139         # TODO: Eventually always create Release in `zzz-dists` to avoid
140         # special cases. However we don't want to move existing Release files
141         # for released suites.
142         # See `create_release_symlinks` below.
143         if not self.suite.byhash:
144             return self.suite_path()
145
146         cnf = Config()
147         suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
148
149         return os.path.join(self.suite.archive.path, 'zzz-dists',
150                             self.suite.suite_name, suite_suffix)
151
152     def create_release_symlinks(self):
153         """
154         Create symlinks for Release files.
155         This creates the symlinks for Release files in the `suite_path`
156         to the actual files in `suite_release_path`.
157         """
158         # TODO: Eventually always create the links.
159         # See `suite_release_path` above.
160         if not self.suite.byhash:
161             return
162
163         relpath = os.path.relpath(self.suite_release_path(), self.suite_path())
164         for f in ("Release", "Release.gpg", "InRelease"):
165             source = os.path.join(relpath, f)
166             dest = os.path.join(self.suite_path(), f)
167             if not os.path.islink(dest):
168                 os.unlink(dest)
169             elif os.readlink(dest) == source:
170                 continue
171             else:
172                 os.unlink(dest)
173             os.symlink(source, dest)
174
175     def create_output_directories(self):
176         for path in (self.suite_path(), self.suite_release_path()):
177             try:
178                 os.makedirs(path)
179             except OSError as e:
180                 if e.errno != errno.EEXIST:
181                     raise
182
183     def generate_release_files(self):
184         """
185         Generate Release files for the given suite
186
187         @type suite: string
188         @param suite: Suite name
189         """
190
191         suite = self.suite
192         session = object_session(suite)
193
194         architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
195
196         # Attribs contains a tuple of field names and the database names to use to
197         # fill them in
198         attribs = ( ('Origin',      'origin'),
199                     ('Label',       'label'),
200                     ('Suite',       'release_suite_output'),
201                     ('Version',     'version'),
202                     ('Codename',    'codename'),
203                     ('Changelogs',  'changelog_url'),
204                   )
205
206         # A "Sub" Release file has slightly different fields
207         subattribs = ( ('Archive',  'suite_name'),
208                        ('Origin',   'origin'),
209                        ('Label',    'label'),
210                        ('Version',  'version') )
211
212         # Boolean stuff. If we find it true in database, write out "yes" into the release file
213         boolattrs = ( ('NotAutomatic',         'notautomatic'),
214                       ('ButAutomaticUpgrades', 'butautomaticupgrades'),
215                       ('Acquire-By-Hash',      'byhash'),
216                     )
217
218         cnf = Config()
219
220         suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
221
222         self.create_output_directories()
223         self.create_release_symlinks()
224
225         outfile = os.path.join(self.suite_release_path(), "Release")
226         out = open(outfile + ".new", "w")
227
228         for key, dbfield in attribs:
229             # Hack to skip NULL Version fields as we used to do this
230             # We should probably just always ignore anything which is None
231             if key in ("Version", "Changelogs") and getattr(suite, dbfield) is None:
232                 continue
233
234             out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
235
236         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
237
238         if suite.validtime:
239             validtime=float(suite.validtime)
240             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
241
242         for key, dbfield in boolattrs:
243             if getattr(suite, dbfield, False):
244                 out.write("%s: yes\n" % (key))
245
246         out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
247
248         components = [ c.component_name for c in suite.components ]
249
250         out.write("Components: %s\n" % (" ".join(components)))
251
252         # For exact compatibility with old g-r, write out Description here instead
253         # of with the rest of the DB fields above
254         if getattr(suite, 'description') is not None:
255             out.write("Description: %s\n" % suite.description)
256
257         for comp in components:
258             for dirpath, dirnames, filenames in os.walk(os.path.join(self.suite_path(), comp), topdown=True):
259                 if not re_gensubrelease.match(dirpath):
260                     continue
261
262                 subfile = os.path.join(dirpath, "Release")
263                 subrel = open(subfile + '.new', "w")
264
265                 for key, dbfield in subattribs:
266                     if getattr(suite, dbfield) is not None:
267                         subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
268
269                 for key, dbfield in boolattrs:
270                     if getattr(suite, dbfield, False):
271                         subrel.write("%s: yes\n" % (key))
272
273                 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
274
275                 # Urgh, but until we have all the suite/component/arch stuff in the DB,
276                 # this'll have to do
277                 arch = os.path.split(dirpath)[-1]
278                 if arch.startswith('binary-'):
279                     arch = arch[7:]
280
281                 subrel.write("Architecture: %s\n" % (arch))
282                 subrel.close()
283
284                 os.rename(subfile + '.new', subfile)
285
286         # Now that we have done the groundwork, we want to get off and add the files with
287         # their checksums to the main Release file
288         oldcwd = os.getcwd()
289
290         os.chdir(self.suite_path())
291
292         hashfuncs = dict(zip([x.upper().replace('UM', 'um') for x in suite.checksums],
293                              [getattr(apt_pkg, "%s" % (x)) for x in [x.replace("sum", "") + "sum" for x in suite.checksums]]))
294
295         fileinfo = {}
296
297         uncompnotseen = {}
298
299         for dirpath, dirnames, filenames in os.walk(".", followlinks=True, topdown=True):
300             for entry in filenames:
301                 # Skip things we don't want to include
302                 if not re_includeinrelease.match(entry):
303                     continue
304
305                 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
306                     continue
307
308                 filename = os.path.join(dirpath.lstrip('./'), entry)
309                 fileinfo[filename] = {}
310                 contents = open(filename, 'r').read()
311
312                 # If we find a file for which we have a compressed version and
313                 # haven't yet seen the uncompressed one, store the possibility
314                 # for future use
315                 if entry.endswith(".gz") and filename[:-3] not in uncompnotseen:
316                     uncompnotseen[filename[:-3]] = (gzip.GzipFile, filename)
317                 elif entry.endswith(".bz2") and filename[:-4] not in uncompnotseen:
318                     uncompnotseen[filename[:-4]] = (bz2.BZ2File, filename)
319                 elif entry.endswith(".xz") and filename[:-3] not in uncompnotseen:
320                     uncompnotseen[filename[:-3]] = (XzFile, filename)
321
322                 fileinfo[filename]['len'] = len(contents)
323
324                 for hf, func in hashfuncs.items():
325                     fileinfo[filename][hf] = func(contents)
326
327         for filename, comp in uncompnotseen.items():
328             # If we've already seen the uncompressed file, we don't
329             # need to do anything again
330             if filename in fileinfo:
331                 continue
332
333             fileinfo[filename] = {}
334
335             # File handler is comp[0], filename of compressed file is comp[1]
336             contents = comp[0](comp[1], 'r').read()
337
338             fileinfo[filename]['len'] = len(contents)
339
340             for hf, func in hashfuncs.items():
341                 fileinfo[filename][hf] = func(contents)
342
343
344         for h in sorted(hashfuncs.keys()):
345             out.write('%s:\n' % h)
346             for filename in sorted(fileinfo.keys()):
347                 out.write(" %s %8d %s\n" % (fileinfo[filename][h], fileinfo[filename]['len'], filename))
348
349         out.close()
350         os.rename(outfile + '.new', outfile)
351
352         if suite.byhash:
353             query = """
354                 UPDATE hashfile SET unreferenced = CURRENT_TIMESTAMP
355                 WHERE suite_id = :id AND unreferenced IS NULL"""
356             session.execute(query, {'id': suite.suite_id})
357
358             for filename in fileinfo:
359                 if not os.path.exists(filename):
360                     # probably an uncompressed index we didn't generate
361                     continue
362
363                 for h in hashfuncs:
364                     hashfile = os.path.join(os.path.dirname(filename), 'by-hash', h, fileinfo[filename][h])
365                     query = "SELECT 1 FROM hashfile WHERE path = :p AND suite_id = :id"
366                     q = session.execute(
367                             query,
368                             {'p': hashfile, 'id': suite.suite_id})
369                     if q.rowcount:
370                         session.execute('''
371                             UPDATE hashfile SET unreferenced = NULL
372                             WHERE path = :p and suite_id = :id''',
373                             {'p': hashfile, 'id': suite.suite_id})
374                     else:
375                         session.execute('''
376                             INSERT INTO hashfile (path, suite_id)
377                             VALUES (:p, :id)''',
378                             {'p': hashfile, 'id': suite.suite_id})
379
380                     try:
381                         os.makedirs(os.path.dirname(hashfile))
382                     except OSError as exc:
383                         if exc.errno != errno.EEXIST:
384                             raise
385                     try:
386                         os.link(filename, hashfile)
387                     except OSError as exc:
388                         if exc.errno != errno.EEXIST:
389                             raise
390
391                 session.commit()
392
393         sign_release_dir(suite, os.path.dirname(outfile))
394
395         os.chdir(oldcwd)
396
397         return
398
399
400 def main ():
401     global Logger
402
403     cnf = Config()
404
405     for i in ["Help", "Suite", "Force", "Quiet"]:
406         if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
407             cnf["Generate-Releases::Options::%s" % (i)] = ""
408
409     Arguments = [('h',"help","Generate-Releases::Options::Help"),
410                  ('a','archive','Generate-Releases::Options::Archive','HasArg'),
411                  ('s',"suite","Generate-Releases::Options::Suite"),
412                  ('f',"force","Generate-Releases::Options::Force"),
413                  ('q',"quiet","Generate-Releases::Options::Quiet"),
414                  ('o','option','','ArbItem')]
415
416     suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
417     Options = cnf.subtree("Generate-Releases::Options")
418
419     if Options["Help"]:
420         usage()
421
422     Logger = daklog.Logger('generate-releases')
423     pool = DakProcessPool()
424
425     session = DBConn().session()
426
427     if Options["Suite"]:
428         suites = []
429         for s in suite_names:
430             suite = get_suite(s.lower(), session)
431             if suite:
432                 suites.append(suite)
433             else:
434                 print "cannot find suite %s" % s
435                 Logger.log(['cannot find suite %s' % s])
436     else:
437         query = session.query(Suite).filter(Suite.untouchable == False)
438         if 'Archive' in Options:
439             query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
440         suites = query.all()
441
442     broken=[]
443
444     for s in suites:
445         # Setup a multiprocessing Pool. As many workers as we have CPU cores.
446         if s.untouchable and not Options["Force"]:
447             print "Skipping %s (untouchable)" % s.suite_name
448             continue
449
450         if not Options["Quiet"]:
451             print "Processing %s" % s.suite_name
452         Logger.log(['Processing release file for Suite: %s' % (s.suite_name)])
453         pool.apply_async(generate_helper, (s.suite_id, ))
454
455     # No more work will be added to our pool, close it and then wait for all to finish
456     pool.close()
457     pool.join()
458
459     retcode = pool.overall_status()
460
461     if retcode > 0:
462         # TODO: CENTRAL FUNCTION FOR THIS / IMPROVE LOGGING
463         Logger.log(['Release file generation broken: %s' % (','.join([str(x[1]) for x in pool.results]))])
464
465     Logger.close()
466
467     sys.exit(retcode)
468
469 def generate_helper(suite_id):
470     '''
471     This function is called in a new subprocess.
472     '''
473     session = DBConn().session()
474     suite = Suite.get(suite_id, session)
475
476     # We allow the process handler to catch and deal with any exceptions
477     rw = ReleaseWriter(suite)
478     rw.generate_release_files()
479
480     return (PROC_STATUS_SUCCESS, 'Release file written for %s' % suite.suite_name)
481
482 #######################################################################################
483
484 if __name__ == '__main__':
485     main()