]> git.decadent.org.uk Git - dak.git/blob - dak/generate_releases.py
Add by-hash support
[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 generate_release_files(self):
125         """
126         Generate Release files for the given suite
127
128         @type suite: string
129         @param suite: Suite name
130         """
131
132         suite = self.suite
133         session = object_session(suite)
134
135         architectures = get_suite_architectures(suite.suite_name, skipall=True, skipsrc=True, session=session)
136
137         # Attribs contains a tuple of field names and the database names to use to
138         # fill them in
139         attribs = ( ('Origin',      'origin'),
140                     ('Label',       'label'),
141                     ('Suite',       'release_suite_output'),
142                     ('Version',     'version'),
143                     ('Codename',    'codename'),
144                     ('Changelogs',  'changelog_url'),
145                   )
146
147         # A "Sub" Release file has slightly different fields
148         subattribs = ( ('Archive',  'suite_name'),
149                        ('Origin',   'origin'),
150                        ('Label',    'label'),
151                        ('Version',  'version') )
152
153         # Boolean stuff. If we find it true in database, write out "yes" into the release file
154         boolattrs = ( ('NotAutomatic',         'notautomatic'),
155                       ('ButAutomaticUpgrades', 'butautomaticupgrades'),
156                       ('Acquire-By-Hash',      'byhash'),
157                     )
158
159         cnf = Config()
160
161         suite_suffix = cnf.find("Dinstall::SuiteSuffix", "")
162
163         outfile = os.path.join(suite.archive.path, 'dists', suite.suite_name, suite_suffix, "Release")
164         out = open(outfile + ".new", "w")
165
166         for key, dbfield in attribs:
167             # Hack to skip NULL Version fields as we used to do this
168             # We should probably just always ignore anything which is None
169             if key in ("Version", "Changelogs") and getattr(suite, dbfield) is None:
170                 continue
171
172             out.write("%s: %s\n" % (key, getattr(suite, dbfield)))
173
174         out.write("Date: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()))))
175
176         if suite.validtime:
177             validtime=float(suite.validtime)
178             out.write("Valid-Until: %s\n" % (time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+validtime))))
179
180         for key, dbfield in boolattrs:
181             if getattr(suite, dbfield, False):
182                 out.write("%s: yes\n" % (key))
183
184         out.write("Architectures: %s\n" % (" ".join([a.arch_string for a in architectures])))
185
186         components = [ c.component_name for c in suite.components ]
187
188         out.write("Components: %s\n" % (" ".join(components)))
189
190         # For exact compatibility with old g-r, write out Description here instead
191         # of with the rest of the DB fields above
192         if getattr(suite, 'description') is not None:
193             out.write("Description: %s\n" % suite.description)
194
195         for comp in components:
196             for dirpath, dirnames, filenames in os.walk(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix, comp), topdown=True):
197                 if not re_gensubrelease.match(dirpath):
198                     continue
199
200                 subfile = os.path.join(dirpath, "Release")
201                 subrel = open(subfile + '.new', "w")
202
203                 for key, dbfield in subattribs:
204                     if getattr(suite, dbfield) is not None:
205                         subrel.write("%s: %s\n" % (key, getattr(suite, dbfield)))
206
207                 for key, dbfield in boolattrs:
208                     if getattr(suite, dbfield, False):
209                         subrel.write("%s: yes\n" % (key))
210
211                 subrel.write("Component: %s%s\n" % (suite_suffix, comp))
212
213                 # Urgh, but until we have all the suite/component/arch stuff in the DB,
214                 # this'll have to do
215                 arch = os.path.split(dirpath)[-1]
216                 if arch.startswith('binary-'):
217                     arch = arch[7:]
218
219                 subrel.write("Architecture: %s\n" % (arch))
220                 subrel.close()
221
222                 os.rename(subfile + '.new', subfile)
223
224         # Now that we have done the groundwork, we want to get off and add the files with
225         # their checksums to the main Release file
226         oldcwd = os.getcwd()
227
228         os.chdir(os.path.join(suite.archive.path, "dists", suite.suite_name, suite_suffix))
229
230         hashfuncs = dict(zip([x.upper().replace('UM', 'um') for x in suite.checksums],
231                              [getattr(apt_pkg, "%s" % (x)) for x in [x.replace("sum", "") + "sum" for x in suite.checksums]]))
232
233         fileinfo = {}
234
235         uncompnotseen = {}
236
237         for dirpath, dirnames, filenames in os.walk(".", followlinks=True, topdown=True):
238             for entry in filenames:
239                 # Skip things we don't want to include
240                 if not re_includeinrelease.match(entry):
241                     continue
242
243                 if dirpath == '.' and entry in ["Release", "Release.gpg", "InRelease"]:
244                     continue
245
246                 filename = os.path.join(dirpath.lstrip('./'), entry)
247                 fileinfo[filename] = {}
248                 contents = open(filename, 'r').read()
249
250                 # If we find a file for which we have a compressed version and
251                 # haven't yet seen the uncompressed one, store the possibility
252                 # for future use
253                 if entry.endswith(".gz") and filename[:-3] not in uncompnotseen:
254                     uncompnotseen[filename[:-3]] = (gzip.GzipFile, filename)
255                 elif entry.endswith(".bz2") and filename[:-4] not in uncompnotseen:
256                     uncompnotseen[filename[:-4]] = (bz2.BZ2File, filename)
257                 elif entry.endswith(".xz") and filename[:-3] not in uncompnotseen:
258                     uncompnotseen[filename[:-3]] = (XzFile, filename)
259
260                 fileinfo[filename]['len'] = len(contents)
261
262                 for hf, func in hashfuncs.items():
263                     fileinfo[filename][hf] = func(contents)
264
265         for filename, comp in uncompnotseen.items():
266             # If we've already seen the uncompressed file, we don't
267             # need to do anything again
268             if filename in fileinfo:
269                 continue
270
271             fileinfo[filename] = {}
272
273             # File handler is comp[0], filename of compressed file is comp[1]
274             contents = comp[0](comp[1], 'r').read()
275
276             fileinfo[filename]['len'] = len(contents)
277
278             for hf, func in hashfuncs.items():
279                 fileinfo[filename][hf] = func(contents)
280
281
282         for h in sorted(hashfuncs.keys()):
283             out.write('%s:\n' % h)
284             for filename in sorted(fileinfo.keys()):
285                 out.write(" %s %8d %s\n" % (fileinfo[filename][h], fileinfo[filename]['len'], filename))
286
287         out.close()
288         os.rename(outfile + '.new', outfile)
289
290         if suite.byhash:
291             query = """
292                 UPDATE hashfile SET unreferenced = CURRENT_TIMESTAMP
293                 WHERE suite_id = :id AND unreferenced IS NULL"""
294             session.execute(query, {'id': suite.suite_id})
295
296             for filename in fileinfo:
297                 if not os.path.exists(filename):
298                     # probably an uncompressed index we didn't generate
299                     continue
300
301                 for h in hashfuncs:
302                     hashfile = os.path.join(os.path.dirname(filename), 'by-hash', h, fileinfo[filename][h])
303                     query = "SELECT 1 FROM hashfile WHERE path = :p AND suite_id = :id"
304                     q = session.execute(
305                             query,
306                             {'p': hashfile, 'id': suite.suite_id})
307                     if q.rowcount:
308                         session.execute('''
309                             UPDATE hashfile SET unreferenced = NULL
310                             WHERE path = :p and suite_id = :id''',
311                             {'p': hashfile, 'id': suite.suite_id})
312                     else:
313                         session.execute('''
314                             INSERT INTO hashfile (path, suite_id)
315                             VALUES (:p, :id)''',
316                             {'p': hashfile, 'id': suite.suite_id})
317
318                     try:
319                         os.makedirs(os.path.dirname(hashfile))
320                     except OSError as exc:
321                         if exc.errno != errno.EEXIST:
322                             raise
323                     try:
324                         os.link(filename, hashfile)
325                     except OSError as exc:
326                         if exc.errno != errno.EEXIST:
327                             raise
328
329                 session.commit()
330
331         sign_release_dir(suite, os.path.dirname(outfile))
332
333         os.chdir(oldcwd)
334
335         return
336
337
338 def main ():
339     global Logger
340
341     cnf = Config()
342
343     for i in ["Help", "Suite", "Force", "Quiet"]:
344         if not cnf.has_key("Generate-Releases::Options::%s" % (i)):
345             cnf["Generate-Releases::Options::%s" % (i)] = ""
346
347     Arguments = [('h',"help","Generate-Releases::Options::Help"),
348                  ('a','archive','Generate-Releases::Options::Archive','HasArg'),
349                  ('s',"suite","Generate-Releases::Options::Suite"),
350                  ('f',"force","Generate-Releases::Options::Force"),
351                  ('q',"quiet","Generate-Releases::Options::Quiet"),
352                  ('o','option','','ArbItem')]
353
354     suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
355     Options = cnf.subtree("Generate-Releases::Options")
356
357     if Options["Help"]:
358         usage()
359
360     Logger = daklog.Logger('generate-releases')
361     pool = DakProcessPool()
362
363     session = DBConn().session()
364
365     if Options["Suite"]:
366         suites = []
367         for s in suite_names:
368             suite = get_suite(s.lower(), session)
369             if suite:
370                 suites.append(suite)
371             else:
372                 print "cannot find suite %s" % s
373                 Logger.log(['cannot find suite %s' % s])
374     else:
375         query = session.query(Suite).filter(Suite.untouchable == False)
376         if 'Archive' in Options:
377             query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
378         suites = query.all()
379
380     broken=[]
381
382     for s in suites:
383         # Setup a multiprocessing Pool. As many workers as we have CPU cores.
384         if s.untouchable and not Options["Force"]:
385             print "Skipping %s (untouchable)" % s.suite_name
386             continue
387
388         if not Options["Quiet"]:
389             print "Processing %s" % s.suite_name
390         Logger.log(['Processing release file for Suite: %s' % (s.suite_name)])
391         pool.apply_async(generate_helper, (s.suite_id, ))
392
393     # No more work will be added to our pool, close it and then wait for all to finish
394     pool.close()
395     pool.join()
396
397     retcode = pool.overall_status()
398
399     if retcode > 0:
400         # TODO: CENTRAL FUNCTION FOR THIS / IMPROVE LOGGING
401         Logger.log(['Release file generation broken: %s' % (','.join([str(x[1]) for x in pool.results]))])
402
403     Logger.close()
404
405     sys.exit(retcode)
406
407 def generate_helper(suite_id):
408     '''
409     This function is called in a new subprocess.
410     '''
411     session = DBConn().session()
412     suite = Suite.get(suite_id, session)
413
414     # We allow the process handler to catch and deal with any exceptions
415     rw = ReleaseWriter(suite)
416     rw.generate_release_files()
417
418     return (PROC_STATUS_SUCCESS, 'Release file written for %s' % suite.suite_name)
419
420 #######################################################################################
421
422 if __name__ == '__main__':
423     main()