webapp: generate /comparison pages in constant-space
[~helmut/debian-dedup.git] / webapp.py
1 #!/usr/bin/python
2
3 import datetime
4 import sqlite3
5 from wsgiref.simple_server import make_server
6
7 import jinja2
8 from werkzeug.exceptions import HTTPException, NotFound
9 from werkzeug.routing import Map, Rule, RequestRedirect
10 from werkzeug.wrappers import Request, Response
11
12 from dedup.utils import fetchiter
13
14 hash_functions = [
15         ("sha512", "sha512"),
16         ("image_sha512", "image_sha512"),
17         ("gzip_sha512", "gzip_sha512"),
18         ("sha512", "gzip_sha512"),
19         ("gzip_sha512", "sha512")]
20
21 jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader("."))
22
23 def format_size(size):
24     assert isinstance(size, int)
25     size = float(size)
26     fmt = "%d B"
27     if size >= 1024:
28         size /= 1024
29         fmt = "%.1f KB"
30     if size >= 1024:
31         size /= 1024
32         fmt = "%.1f MB"
33     if size >= 1024:
34         size /= 1024
35         fmt = "%.1f GB"
36     return fmt % size
37
38 jinjaenv.filters["format_size"] = format_size
39
40 base_template = jinjaenv.get_template("base.html")
41
42 package_template = jinjaenv.from_string(
43 """{% extends "base.html" %}
44 {% block title %}duplication of {{ package|e }}{% endblock %}
45 {% block header %}<style type="text/css">.dependency { background-color: yellow; } </style>{% endblock %}
46 {% block content %}<h1>{{ package|e }}</h1>
47 <p>Version: {{ version|e }}</p>
48 <p>Architecture: {{ architecture|e }}</p>
49 <p>Number of files: {{ num_files }}</p>
50 <p>Total size: {{ total_size|format_size }}</p>
51 {%- if shared -%}
52     {%- for function, sharing in shared.items() -%}
53         <h3>sharing with respect to {{ function|e }}</h3>
54         <table border='1'><tr><th>package</th><th>files shared</th><th>data shared</th></tr>
55         {%- for entry in sharing|sort(attribute="savable", reverse=true) -%}
56             <tr><td{% if not entry.package or entry.package in dependencies %} class="dependency"{% endif %}>
57                 {%- if entry.package %}<a href="{{ entry.package|e }}">{{ entry.package|e }}</a>{% else %}self{% endif %}
58                 <a href="../compare/{{ package|e }}/{{ entry.package|default(package, true)|e }}">compare</a></td>
59             <td>{{ entry.duplicate }} ({{ (100 * entry.duplicate / num_files)|int }}%)</td>
60             <td>{{ entry.savable|format_size }} ({{ (100 * entry.savable / total_size)|int }}%)</td></tr>
61         {%- endfor -%}
62         </table>
63     {%- endfor -%}
64 {%- endif -%}
65 {% endblock %}""")
66
67 detail_template = jinjaenv.from_string(
68 """{% extends "base.html" %}
69 {% block title %}sharing between {{ details1.package|e }} and {{ details2.package|e }}{% endblock%}
70 {% block content %}
71 <h1><a href="../../binary/{{ details1.package|e }}">{{ details1.package|e }}</a> &lt;-&gt; <a href="../../binary/{{ details2.package|e }}">{{ details2.package|e }}</a></h1>
72 <table border='1'><tr><th colspan="3">{{ details1.package|e }}</th><th colspan="3">{{ details2.package|e }}</th></tr>
73 <tr><th>size</th><th>filename</th><th>hash functions</th><th>size</th><th>filename</th><th>hash functions</th></tr>
74     {%- for entry in shared -%}
75         <tr><td>{{ entry.size1|format_size }}</td><td>{{ entry.filename1 }}</td><td>
76             {%- for funccomb, hashvalue in entry.functions.items() %}<a href="../../hash/{{ funccomb[0]|e }}/{{ hashvalue|e }}">{{ funccomb[0]|e }}</a> {% endfor %}</td>
77         <td>{{ entry.size2|format_size }}</td><td>{{ entry.filename2 }}</td><td>
78             {%- for funccomb, hashvalue in entry.functions.items() %}<a href="../../hash/{{ funccomb[1]|e }}/{{ hashvalue|e }}">{{ funccomb[1]|e }}</a> {% endfor %}</td></tr>
79     {%- endfor -%}
80 </table>
81 {% endblock %}""")
82
83 hash_template = jinjaenv.from_string(
84 """{% extends "base.html" %}
85 {% block title %}information on {{ function|e }} hash {{ hashvalue|e }}{% endblock %}
86 {% block content %}
87 <h1>{{ function|e }} {{ hashvalue|e }}</h1>
88 <table border='1'><tr><th>package</th><th>filename</th><th>size</th><th>different function</th></tr>
89 {%- for entry in entries -%}
90     <tr><td><a href="../../binary/{{ entry.package|e }}">{{ entry.package|e }}</a></td>
91     <td>{{ entry.filename|e }}</td><td>{{ entry.size|format_size }}</td>
92     <td>{% if function != entry.function %}{{ entry.function|e }}{% endif %}</td></tr>
93 {%- endfor -%}
94 </table>
95 {% endblock %}""")
96
97 index_template = jinjaenv.from_string(
98 """{% extends "base.html" %}
99 {% block title %}Debian duplication detector{% endblock %}
100 {% block header %}
101     <script type="text/javascript">
102         function getLinkTarget() {
103             var pkg = document.getElementById("pkg_name").value;
104             if(pkg) {
105                 return "/binary/"+pkg;
106             }
107             return '#';
108         }
109         function processData() {
110             var link = document.getElementById("perma_link");
111             link.href = getLinkTarget();
112             link.text = location.href + getLinkTarget();
113         }
114         window.onload = function() {
115             document.getElementById('pkg_name').onkeyup = processData;
116             document.getElementById("pkg_form").onsubmit = function () {
117                 location.href = getLinkTarget();
118                 return false;
119             }
120             processData();
121             document.getElementById("form_div").style.display = '';
122         }
123     </script>
124 {% endblock %}
125 {% block content %}
126 <h1>Debian duplication detector</h1>
127 <ul>
128 <li>To inspect a particlar binary package, go to <pre>binary/&lt;packagename&gt;</pre> Example: <a href="binary/git">binary/git</a>
129     <div style="display:none" id="form_div"><fieldset>
130             <legend>Inspect package</legend>
131             <noscript><b>This form is disfunctional when javascript is not enabled</b></noscript>
132             Enter binary package to inspect - Note: Non-existing packages will result in <b>404</b>-Errors
133             <form id="pkg_form">
134                 <label for="pkg_name">Name: <input type="text" size="30" name="pkg_name" id="pkg_name">
135                 <input type="submit" value="Go"> Permanent Link: <a id="perma_link" href="#" />
136             </form>
137     </fieldset></div></li>
138 <li>To inspect a combination of binary packages go to <pre>compare/&lt;firstpackage&gt;/&lt;secondpackage&gt;</pre> Example: <a href="compare/git/git">compare/git/git</a></li>
139 <li>To discover package shipping a particular file go to <pre>hash/sha512/&lt;hashvalue&gt;</pre> Example: <a href="hash/sha512/ed94df7781793f06f9426a600c1bde86397afc7b35cb3aa11b60214bd31e35ad893b53a04a2cf4676154982d7c204c4aa165d6ccdaac0170031364a05dbab3bc">hash/sha512/ed94df7781793f06f9426a600c1bde86397afc7b35cb3aa11b60214bd31e35ad893b53a04a2cf4676154982d7c204c4aa165d6ccdaac0170031364a05dbab3bc</a></li>
140 </ul>
141 {% endblock %}""")
142
143 def encode_and_buffer(iterator):
144     buff = b""
145     for elem in iterator:
146         buff += elem.encode("utf8")
147         if len(buff) >= 2048:
148             yield buff
149             buff = b""
150     if buff:
151         yield buff
152
153 def html_response(unicode_iterator, max_age=24 * 60 * 60):
154     resp = Response(encode_and_buffer(unicode_iterator), mimetype="text/html")
155     resp.cache_control.max_age = max_age
156     resp.expires = datetime.datetime.now() + datetime.timedelta(seconds=max_age)
157     return resp
158
159 def generate_shared(rows):
160     """internal helper from show_detail"""
161     entry = None
162     for filename1, size1, func1, filename2, size2, func2, hashvalue in rows:
163         funccomb = (func1, func2)
164         if funccomb not in hash_functions:
165             continue
166         if entry and (entry["filename1"] != filename1 or
167                       entry["filename2"] != filename2):
168             yield entry
169             entry = None
170         if entry:
171             funcdict = entry["functions"]
172         else:
173             funcdict = dict()
174             entry = dict(filename1=filename1, filename2=filename2, size1=size1,
175                          size2=size2, functions=funcdict)
176         funcdict[funccomb] = hashvalue
177     if entry:
178         yield entry
179
180 class Application(object):
181     def __init__(self, db):
182         self.db = db
183         self.routingmap = Map([
184             Rule("/", methods=("GET",), endpoint="index"),
185             Rule("/binary/<package>", methods=("GET",), endpoint="package"),
186             Rule("/compare/<package1>/<package2>", methods=("GET",), endpoint="detail"),
187             Rule("/hash/<function>/<hashvalue>", methods=("GET",), endpoint="hash"),
188         ])
189
190     @Request.application
191     def __call__(self, request):
192         mapadapter = self.routingmap.bind_to_environ(request.environ)
193         try:
194             endpoint, args = mapadapter.match()
195             if endpoint == "package":
196                 return self.show_package(args["package"])
197             elif endpoint == "detail":
198                 return self.show_detail(args["package1"], args["package2"])
199             elif endpoint == "hash":
200                 return self.show_hash(args["function"], args["hashvalue"])
201             elif endpoint == "index":
202                 if not request.environ["PATH_INFO"]:
203                     raise RequestRedirect(request.environ["SCRIPT_NAME"] + "/")
204                 return html_response(index_template.stream())
205             raise NotFound()
206         except HTTPException as e:
207             return e
208
209     def get_details(self, package):
210         cur = self.db.cursor()
211         cur.execute("SELECT version, architecture FROM package WHERE package = ?;",
212                     (package,))
213         row = cur.fetchone()
214         if not row:
215             raise NotFound()
216         version, architecture = row
217         details = dict(package=package,
218                        version=version,
219                        architecture=architecture)
220         cur.execute("SELECT count(filename), sum(size) FROM content WHERE package = ?;",
221                     (package,))
222         num_files, total_size = cur.fetchone()
223         details.update(dict(num_files=num_files, total_size=total_size))
224         return details
225
226     def get_dependencies(self, package):
227         cur = self.db.cursor()
228         cur.execute("SELECT required FROM dependency WHERE package = ?;",
229                     (package,))
230         return set(row[0] for row in fetchiter(cur))
231
232     def show_package(self, package):
233         cur = self.db.cursor()
234         params = self.get_details(package)
235         params["dependencies"] = self.get_dependencies(package)
236
237         sharedstats = {}
238         for func1, func2 in hash_functions:
239             cur.execute("SELECT a.filename, a.hash, a.size, b.package FROM content AS a JOIN content AS b ON a.hash = b.hash WHERE a.package = ? AND a.function = ? AND b.function = ? AND (a.filename != b.filename OR b.package != ?);",
240                         (package, func1, func2, package))
241             sharing = dict()
242             for afile, hashval, size, bpkg in fetchiter(cur):
243                 hashdict = sharing.setdefault(bpkg, dict())
244                 fileset = hashdict.setdefault(hashval, (size, set()))[1]
245                 fileset.add(afile)
246             if sharing:
247                 curstats = list()
248                 if func1 == func2:
249                     sharedstats[func1] = curstats
250                 else:
251                     sharedstats["%s -> %s" % (func1, func2)] = curstats
252                 mapping = sharing.pop(package, dict())
253                 if mapping:
254                     duplicate = sum(len(files) for _, files in mapping.values())
255                     savable = sum(size * (len(files) - 1) for size, files in mapping.values())
256                     curstats.append(dict(package=None, duplicate=duplicate, savable=savable))
257                 for pkg, mapping in sharing.items():
258                     duplicate = sum(len(files) for _, files in mapping.values())
259                     savable = sum(size * len(files) for size, files in mapping.values())
260                     curstats.append(dict(package=pkg, duplicate=duplicate, savable=savable))
261
262         params["shared"] = sharedstats
263         return html_response(package_template.render(params))
264
265     def show_detail(self, package1, package2):
266         cur = self.db.cursor()
267         if package1 == package2:
268             details1 = details2 = self.get_details(package1)
269
270             cur.execute("SELECT a.filename, a.size, a.function, b.filename, b.size, b.function, a.hash FROM content AS a JOIN content AS b ON a.hash = b.hash WHERE a.package = ? AND b.package = ? AND a.filename != b.filename ORDER BY a.size DESC, a.filename, b.filename;",
271                         (package1, package1))
272         else:
273             details1 = self.get_details(package1)
274             details2 = self.get_details(package2)
275
276             cur.execute("SELECT a.filename, a.size, a.function, b.filename, b.size, b.function, a.hash FROM content AS a JOIN content AS b ON a.hash = b.hash WHERE a.package = ? AND b.package = ? ORDER BY a.size DESC, a.filename, b.filename;",
277                         (package1, package2))
278         shared = generate_shared(fetchiter(cur))
279         # The cursor will be in use until the template is fully rendered.
280         params = dict(
281             details1=details1,
282             details2=details2,
283             shared=shared)
284         return html_response(detail_template.stream(params))
285
286     def show_hash(self, function, hashvalue):
287         cur = self.db.cursor()
288         cur.execute("SELECT package, filename, size, function FROM content WHERE hash = ?;",
289                     (hashvalue,))
290         entries = [dict(package=package, filename=filename, size=size,
291                         function=otherfunc)
292                    for package, filename, size, otherfunc in fetchiter(cur)
293                    if (function, otherfunc) in hash_functions]
294         if not entries:
295             raise NotFound()
296         params = dict(function=function, hashvalue=hashvalue, entries=entries)
297         return html_response(hash_template.render(params))
298
299 def main():
300     app = Application(sqlite3.connect("test.sqlite3"))
301     #app = DebuggedApplication(app, evalex=True)
302     make_server("0.0.0.0", 8800, app).serve_forever()
303
304 if __name__ == "__main__":
305     main()