]> git.decadent.org.uk Git - dak.git/blob - dak/show_deferred.py
Fix typo
[dak.git] / dak / show_deferred.py
1 #!/usr/bin/env python
2
3 """ Overview of the DEFERRED queue, based on queue-report """
4 #    Copyright (C) 2001, 2002, 2003, 2005, 2006  James Troup <james@nocrew.org>
5 # Copyright (C) 2008 Thomas Viehmann <tv@beamnet.de>
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 ################################################################################
22
23 import sys, os, re, time
24 import apt_pkg
25 import rrdtool
26
27 try:
28     # starting with squeeze
29     from debian import deb822
30 except:
31     # up to lenny
32     from debian_bundle import deb822
33
34 from daklib.dbconn import *
35 from daklib import utils
36 from daklib.regexes import re_html_escaping, html_escaping
37
38 ################################################################################
39 ### work around bug #487902 in debian-python 0.1.10
40 deb822.Changes._multivalued_fields = {
41             "files": [ "md5sum", "size", "section", "priority", "name" ],
42             "checksums-sha1": ["sha1", "size", "name"],
43             "checksums-sha256": ["sha256", "size", "name"],
44           }
45
46 ################################################################################
47
48 row_number = 1
49
50 def html_escape(s):
51     return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
52
53 ################################################################################
54
55 def header():
56   return  """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
57         <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
58         <title>Deferred uploads to Debian</title>
59         <link type="text/css" rel="stylesheet" href="style.css">
60         <link rel="shortcut icon" href="http://www.debian.org/favicon.ico">
61         </head>
62         <body>
63         <div align="center">
64         <a href="http://www.debian.org/">
65      <img src="http://www.debian.org/logos/openlogo-nd-50.png" border="0" hspace="0" vspace="0" alt=""></a>
66         <a href="http://www.debian.org/">
67      <img src="http://www.debian.org/Pics/debian.png" border="0" hspace="0" vspace="0" alt="Debian Project"></a>
68         </div>
69         <br />
70         <table class="reddy" width="100%">
71         <tr>
72         <td class="reddy">
73     <img src="http://www.debian.org/Pics/red-upperleft.png" align="left" border="0" hspace="0" vspace="0"
74      alt="" width="15" height="16"></td>
75         <td rowspan="2" class="reddy">Deferred uploads to Debian</td>
76         <td class="reddy">
77     <img src="http://www.debian.org/Pics/red-upperright.png" align="right" border="0" hspace="0" vspace="0"
78      alt="" width="16" height="16"></td>
79         </tr>
80         <tr>
81         <td class="reddy">
82     <img src="http://www.debian.org/Pics/red-lowerleft.png" align="left" border="0" hspace="0" vspace="0"
83      alt="" width="16" height="16"></td>
84         <td class="reddy">
85     <img src="http://www.debian.org/Pics/red-lowerright.png" align="right" border="0" hspace="0" vspace="0"
86      alt="" width="15" height="16"></td>
87         </tr>
88         </table>
89         """
90
91 def footer():
92     res = "<p class=\"validate\">Timestamp: %s (UTC)</p>" % (time.strftime("%d.%m.%Y / %H:%M:%S", time.gmtime()))
93     res += "<p class=\"timestamp\">There are <a href=\"/stat.html\">graphs about the queues</a> available.</p>"
94     res += """<a href="http://validator.w3.org/check?uri=referer">
95     <img border="0" src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" height="31" width="88"></a>
96         <a href="http://jigsaw.w3.org/css-validator/check/referer">
97     <img border="0" src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"
98      height="31" width="88"></a>
99     """
100     res += "</body></html>"
101     return res
102
103 def table_header():
104     return """<h1>Deferred uploads</h1>
105       <center><table border="0">
106         <tr>
107           <th align="center">Change</th>
108           <th align="center">Time remaining</th>
109           <th align="center">Uploader</th>
110           <th align="center">Closes</th>
111         </tr>
112         """
113
114 def table_footer():
115     return '</table><br/><p>non-NEW uploads are <a href="/deferred/">available</a>, see the <a href="ftp://ftp-master.debian.org/pub/UploadQueue/README">UploadQueue-README</a> for more information.</p></center><br/>\n'
116
117 def table_row(changesname, delay, changed_by, closes):
118     global row_number
119
120     res = '<tr class="%s">'%((row_number%2) and 'odd' or 'even')
121     res += (3*'<td valign="top">%s</td>')%tuple(map(html_escape,(changesname,delay,changed_by)))
122     res += ('<td valign="top">%s</td>' %
123              ''.join(map(lambda close:  '<a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s">#%s</a><br>' % (close, close),closes)))
124     res += '</tr>\n'
125     row_number+=1
126     return res
127
128 def update_graph_database(rrd_dir, *counts):
129     if not rrd_dir:
130         return
131
132     rrd_file = os.path.join(rrd_dir, 'deferred.rrd')
133     counts = [str(count) for count in counts]
134     update = [rrd_file, "N:"+":".join(counts)]
135
136     try:
137         rrdtool.update(*update)
138     except rrdtool.error:
139         create = [rrd_file]+"""
140 --step
141 300
142 --start
143 0
144 DS:day0:GAUGE:7200:0:1000
145 DS:day1:GAUGE:7200:0:1000
146 DS:day2:GAUGE:7200:0:1000
147 DS:day3:GAUGE:7200:0:1000
148 DS:day4:GAUGE:7200:0:1000
149 DS:day5:GAUGE:7200:0:1000
150 DS:day6:GAUGE:7200:0:1000
151 DS:day7:GAUGE:7200:0:1000
152 DS:day8:GAUGE:7200:0:1000
153 DS:day9:GAUGE:7200:0:1000
154 DS:day10:GAUGE:7200:0:1000
155 DS:day11:GAUGE:7200:0:1000
156 DS:day12:GAUGE:7200:0:1000
157 DS:day13:GAUGE:7200:0:1000
158 DS:day14:GAUGE:7200:0:1000
159 DS:day15:GAUGE:7200:0:1000
160 RRA:AVERAGE:0.5:1:599
161 RRA:AVERAGE:0.5:6:700
162 RRA:AVERAGE:0.5:24:775
163 RRA:AVERAGE:0.5:288:795
164 RRA:MIN:0.5:1:600
165 RRA:MIN:0.5:6:700
166 RRA:MIN:0.5:24:775
167 RRA:MIN:0.5:288:795
168 RRA:MAX:0.5:1:600
169 RRA:MAX:0.5:6:700
170 RRA:MAX:0.5:24:775
171 RRA:MAX:0.5:288:795
172 """.strip().split("\n")
173         try:
174             rc = rrdtool.create(*create)
175             ru = rrdtool.update(*update)
176         except rrdtool.error, e:
177             print('warning: queue_report: rrdtool error, skipping %s.rrd: %s' % (type, e))
178     except NameError:
179         pass
180
181 def get_upload_data(changesfn):
182     achanges = deb822.Changes(file(changesfn))
183     changesname = os.path.basename(changesfn)
184     delay = os.path.basename(os.path.dirname(changesfn))
185     m = re.match(r'([0-9]+)-day', delay)
186     if m:
187         delaydays = int(m.group(1))
188         remainingtime = (delaydays>0)*max(0,24*60*60+os.stat(changesfn).st_mtime-time.time())
189         delay = "%d days %02d:%02d" %(max(delaydays-1,0), int(remainingtime/3600),int(remainingtime/60)%60)
190     else:
191         delaydays = 0
192         remainingtime = 0
193
194     uploader = achanges.get('changed-by')
195     uploader = re.sub(r'^\s*(\S.*)\s+<.*>',r'\1',uploader)
196     if Cnf.has_key("Show-Deferred::LinkPath"):
197         isnew = 0
198         suites = get_suites_source_in(achanges['source'])
199         if 'unstable' not in suites and 'experimental' not in suites:
200             isnew = 1
201
202         for b in achanges['binary'].split():
203             suites = get_suites_binary_in(b)
204             if 'unstable' not in suites and 'experimental' not in suites:
205                 isnew = 1
206
207         if not isnew:
208             # we don't link .changes because we don't want other people to
209             # upload it with the existing signature.
210             for afn in map(lambda x: x['name'],achanges['files']):
211                 lfn = os.path.join(Cnf["Show-Deferred::LinkPath"],afn)
212                 qfn = os.path.join(os.path.dirname(changesfn),afn)
213                 if os.path.islink(lfn):
214                     os.unlink(lfn)
215                 if os.path.exists(qfn):
216                     os.symlink(qfn,lfn)
217                     os.chmod(qfn, 0644)
218     return (max(delaydays-1,0)*24*60*60+remainingtime, changesname, delay, uploader, achanges.get('closes','').split(),achanges, delaydays)
219
220 def list_uploads(filelist, rrd_dir):
221     uploads = map(get_upload_data, filelist)
222     uploads.sort()
223     # print the summary page
224     print header()
225     if uploads:
226         print table_header()
227         print ''.join(map(lambda x: table_row(*x[1:5]), uploads))
228         print table_footer()
229     else:
230         print '<h1>Currently no deferred uploads to Debian</h1>'
231     print footer()
232     # machine readable summary
233     if Cnf.has_key("Show-Deferred::LinkPath"):
234         fn = os.path.join(Cnf["Show-Deferred::LinkPath"],'.status.tmp')
235         f = open(fn,"w")
236         try:
237             counts = [0]*16
238             for u in uploads:
239                 counts[u[6]] += 1
240                 print >> f, "Changes-file: %s"%u[1]
241                 fields = """Location: DEFERRED
242 Delayed-Until: %s
243 Delay-Remaining: %s"""%(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()+u[0])),u[2])
244                 print >> f, fields
245                 print >> f, str(u[5]).rstrip()
246                 open(os.path.join(Cnf["Show-Deferred::LinkPath"],u[1]),"w").write(str(u[5])+fields+'\n')
247                 print >> f
248             f.close()
249             os.rename(os.path.join(Cnf["Show-Deferred::LinkPath"],'.status.tmp'),
250                       os.path.join(Cnf["Show-Deferred::LinkPath"],'status'))
251             update_graph_database(rrd_dir, *counts)
252         except:
253             os.unlink(fn)
254             raise
255
256 def usage (exit_code=0):
257     if exit_code:
258         f = sys.stderr
259     else:
260         f = sys.stdout
261     print >> f, """Usage: dak show-deferred
262   -h, --help                    show this help and exit.
263   -p, --link-path [path]        override output directory.
264   -d, --deferred-queue [path]   path to the deferred queue
265   -r, --rrd=key                 Directory where rrd files to be updated are stored
266   """
267     sys.exit(exit_code)
268
269 def init():
270     global Cnf, Options
271     Cnf = utils.get_conf()
272     Arguments = [('h',"help","Show-Deferred::Options::Help"),
273                  ("p","link-path","Show-Deferred::LinkPath","HasArg"),
274                  ("d","deferred-queue","Show-Deferred::DeferredQueue","HasArg"),
275                  ('r',"rrd","Show-Deferred::Options::Rrd", "HasArg")]
276     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
277     for i in ["help"]:
278         if not Cnf.has_key("Show-Deferred::Options::%s" % (i)):
279             Cnf["Show-Deferred::Options::%s" % (i)] = ""
280     for i,j in [("DeferredQueue","--deferred-queue")]:
281         if not Cnf.has_key("Show-Deferred::%s" % (i)):
282             print >> sys.stderr, """Show-Deferred::%s is mandatory.
283   set via config file or command-line option %s"""%(i,j)
284
285     Options = Cnf.SubTree("Show-Deferred::Options")
286     if Options["help"]:
287         usage()
288
289     # Initialise database connection
290     DBConn()
291
292     return args
293
294 def main():
295     args = init()
296     if len(args)!=0:
297         usage(1)
298
299     if Cnf.has_key("Show-Deferred::Options::Rrd"):
300         rrd_dir = Cnf["Show-Deferred::Options::Rrd"]
301     elif Cnf.has_key("Dir::Rrd"):
302         rrd_dir = Cnf["Dir::Rrd"]
303     else:
304         rrd_dir = None
305
306     filelist = []
307     for r,d,f  in os.walk(Cnf["Show-Deferred::DeferredQueue"]):
308         filelist += map (lambda x: os.path.join(r,x),
309                          filter(lambda x: x.endswith('.changes'), f))
310     list_uploads(filelist, rrd_dir)
311
312     available_changes = set(map(os.path.basename,filelist))
313     if Cnf.has_key("Show-Deferred::LinkPath"):
314         # remove dead links
315         for r,d,f in os.walk(Cnf["Show-Deferred::LinkPath"]):
316             for af in f:
317                 afp = os.path.join(r,af)
318                 if (not os.path.exists(afp) or
319                     (af.endswith('.changes') and af not in available_changes)):
320                     os.unlink(afp)
321
322 if __name__ == '__main__':
323     main()