]> git.decadent.org.uk Git - dak.git/blob - dak/show_deferred.py
Merge commit 'ftpmaster/master' into sqlalchemy
[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 tempfile
26 from debian_bundle import deb822
27 from daklib.dbconn import *
28 from daklib import utils
29 from daklib.regexes import re_html_escaping, html_escaping
30
31 ################################################################################
32 ### work around bug #487902 in debian-python 0.1.10
33 deb822.Changes._multivalued_fields = {
34             "files": [ "md5sum", "size", "section", "priority", "name" ],
35             "checksums-sha1": ["sha1", "size", "name"],
36             "checksums-sha256": ["sha256", "size", "name"],
37           }
38
39 ################################################################################
40
41 row_number = 1
42
43 def html_escape(s):
44     return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
45
46 ################################################################################
47
48 def header():
49   return  """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
50         <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
51         <title>Deferred uploads to Debian</title>
52         <link type="text/css" rel="stylesheet" href="style.css">
53         <link rel="shortcut icon" href="http://www.debian.org/favicon.ico">
54         </head>
55         <body>
56         <div align="center">
57         <a href="http://www.debian.org/">
58      <img src="http://www.debian.org/logos/openlogo-nd-50.png" border="0" hspace="0" vspace="0" alt=""></a>
59         <a href="http://www.debian.org/">
60      <img src="http://www.debian.org/Pics/debian.png" border="0" hspace="0" vspace="0" alt="Debian Project"></a>
61         </div>
62         <br />
63         <table class="reddy" width="100%">
64         <tr>
65         <td class="reddy">
66     <img src="http://www.debian.org/Pics/red-upperleft.png" align="left" border="0" hspace="0" vspace="0"
67      alt="" width="15" height="16"></td>
68         <td rowspan="2" class="reddy">Deferred uploads to Debian</td>
69         <td class="reddy">
70     <img src="http://www.debian.org/Pics/red-upperright.png" align="right" border="0" hspace="0" vspace="0"
71      alt="" width="16" height="16"></td>
72         </tr>
73         <tr>
74         <td class="reddy">
75     <img src="http://www.debian.org/Pics/red-lowerleft.png" align="left" border="0" hspace="0" vspace="0"
76      alt="" width="16" height="16"></td>
77         <td class="reddy">
78     <img src="http://www.debian.org/Pics/red-lowerright.png" align="right" border="0" hspace="0" vspace="0"
79      alt="" width="15" height="16"></td>
80         </tr>
81         </table>
82         """
83
84 def footer():
85     res = "<p class=\"validate\">Timestamp: %s (UTC)</p>" % (time.strftime("%d.%m.%Y / %H:%M:%S", time.gmtime()))
86     res += """<a href="http://validator.w3.org/check?uri=referer">
87     <img border="0" src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!" height="31" width="88"></a>
88         <a href="http://jigsaw.w3.org/css-validator/check/referer">
89     <img border="0" src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"
90      height="31" width="88"></a>
91     """
92     res += "</body></html>"
93     return res
94
95 def table_header():
96     return """<h1>Deferred uploads</h1>
97       <center><table border="0">
98         <tr>
99           <th align="center">Change</th>
100           <th align="center">Time remaining</th>
101           <th align="center">Uploader</th>
102           <th align="center">Closes</th>
103         </tr>
104         """
105     return res
106
107 def table_footer():
108     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'
109
110 def table_row(changesname, delay, changed_by, closes):
111     global row_number
112
113     res = '<tr class="%s">'%((row_number%2) and 'odd' or 'even')
114     res += (3*'<td valign="top">%s</td>')%tuple(map(html_escape,(changesname,delay,changed_by)))
115     res += ('<td valign="top">%s</td>' %
116              ''.join(map(lambda close:  '<a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=%s">#%s</a><br>' % (close, close),closes)))
117     res += '</tr>\n'
118     row_number+=1
119     return res
120
121 def get_upload_data(changesfn):
122     achanges = deb822.Changes(file(changesfn))
123     changesname = os.path.basename(changesfn)
124     delay = os.path.basename(os.path.dirname(changesfn))
125     m = re.match(r'([0-9]+)-day', delay)
126     if m:
127         delaydays = int(m.group(1))
128         remainingtime = (delaydays>0)*max(0,24*60*60+os.stat(changesfn).st_mtime-time.time())
129         delay = "%d days %02d:%02d" %(max(delaydays-1,0), int(remainingtime/3600),int(remainingtime/60)%60)
130     else:
131         remainingtime = 0
132
133     uploader = achanges.get('changed-by')
134     uploader = re.sub(r'^\s*(\S.*)\s+<.*>',r'\1',uploader)
135     if Cnf.has_key("Show-Deferred::LinkPath"):
136         isnew = 0
137         suites = get_suites_source_in(achanges['source'])
138         if 'unstable' not in suites and 'experimental' not in suites:
139             isnew = 1
140
141         for b in achanges['binary'].split():
142             suites = get_suites_binary_in(b)
143             if 'unstable' not in suites and 'experimental' not in suites:
144                 isnew = 1
145
146         if not isnew:
147             # we don't link .changes because we don't want other people to
148             # upload it with the existing signature.
149             for afn in map(lambda x: x['name'],achanges['files']):
150                 lfn = os.path.join(Cnf["Show-Deferred::LinkPath"],afn)
151                 qfn = os.path.join(os.path.dirname(changesfn),afn)
152                 if os.path.islink(lfn):
153                     os.unlink(lfn)
154                 if os.path.exists(qfn):
155                     os.symlink(qfn,lfn)
156                     os.chmod(qfn, 0644)
157     return (max(delaydays-1,0)*24*60*60+remainingtime, changesname, delay, uploader, achanges.get('closes','').split(),achanges)
158
159 def list_uploads(filelist):
160     uploads = map(get_upload_data, filelist)
161     uploads.sort()
162     # print the summary page
163     print header()
164     if uploads:
165         print table_header()
166         print ''.join(map(lambda x: table_row(*x[1:5]), uploads))
167         print table_footer()
168     else:
169         print '<h1>Currently no deferred uploads to Debian</h1>'
170     print footer()
171     # machine readable summary
172     if Cnf.has_key("Show-Deferred::LinkPath"):
173         fn = os.path.join(Cnf["Show-Deferred::LinkPath"],'.status.tmp')
174         f = open(fn,"w")
175         try:
176             for u in uploads:
177                 print >> f, "Changes: %s"%u[1]
178                 fields = """Location: DEFERRED
179 Delayed-Until: %s
180 Delay-Remaining: %s"""%(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()+u[0])),u[2])
181                 print >> f, fields
182                 print >> f, str(u[5]).rstrip()
183                 open(os.path.join(Cnf["Show-Deferred::LinkPath"],u[1]),"w").write(str(u[5])+fields+'\n')
184                 print >> f
185             f.close()
186             os.rename(os.path.join(Cnf["Show-Deferred::LinkPath"],'.status.tmp'),
187                       os.path.join(Cnf["Show-Deferred::LinkPath"],'status'))
188         except:
189             os.unlink(fn)
190             raise
191
192 def usage (exit_code=0):
193     if exit_code:
194         f = sys.stderr
195     else:
196         f = sys.stdout
197     print >> f, """Usage: dak show-deferred
198   -h, --help                    show this help and exit.
199   -p, --link-path [path]        override output directory.
200   -d, --deferred-queue [path]   path to the deferred queue
201   """
202     sys.exit(exit_code)
203
204 def init():
205     global Cnf, Options
206     Cnf = utils.get_conf()
207     Arguments = [('h',"help","Show-Deferred::Options::Help"),
208                  ("p","link-path","Show-Deferred::LinkPath","HasArg"),
209                  ("d","deferred-queue","Show-Deferred::DeferredQueue","HasArg")]
210     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
211     for i in ["help"]:
212         if not Cnf.has_key("Show-Deferred::Options::%s" % (i)):
213             Cnf["Show-Deferred::Options::%s" % (i)] = ""
214     for i,j in [("DeferredQueue","--deferred-queue")]:
215         if not Cnf.has_key("Show-Deferred::%s" % (i)):
216             print >> sys.stderr, """Show-Deferred::%s is mandatory.
217   set via config file or command-line option %s"""%(i,j)
218
219     Options = Cnf.SubTree("Show-Deferred::Options")
220     if Options["help"]:
221         usage()
222
223     # Initialise database connection
224     DBConn()
225
226     return args
227
228 def main():
229     args = init()
230     if len(args)!=0:
231         usage(1)
232
233     filelist = []
234     for r,d,f  in os.walk(Cnf["Show-Deferred::DeferredQueue"]):
235         filelist += map (lambda x: os.path.join(r,x),
236                          filter(lambda x: x.endswith('.changes'), f))
237     list_uploads(filelist)
238
239     available_changes = set(map(os.path.basename,filelist))
240     if Cnf.has_key("Show-Deferred::LinkPath"):
241         # remove dead links
242         for r,d,f in os.walk(Cnf["Show-Deferred::LinkPath"]):
243             for af in f:
244                 afp = os.path.join(r,af)
245                 if (not os.path.exists(afp) or
246                     (af.endswith('.changes') and af not in available_changes)):
247                     os.unlink(afp)