added html form to main page
[~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 hash_functions = [
13         ("sha512", "sha512"),
14         ("image_sha512", "image_sha512"),
15         ("gzip_sha512", "gzip_sha512"),
16         ("sha512", "gzip_sha512"),
17         ("gzip_sha512", "sha512")]
18
19 jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader("."))
20
21 def format_size(size):
22     assert isinstance(size, int)
23     size = float(size)
24     fmt = "%d B"
25     if size >= 1024:
26         size /= 1024
27         fmt = "%.1f KB"
28     if size >= 1024:
29         size /= 1024
30         fmt = "%.1f MB"
31     if size >= 1024:
32         size /= 1024
33         fmt = "%.1f GB"
34     return fmt % size
35
36 jinjaenv.filters["format_size"] = format_size
37
38 base_template = jinjaenv.get_template("base.html")
39
40 package_template = jinjaenv.from_string(
41 """{% extends "base.html" %}
42 {% block title %}duplication of {{ package|e }}{% endblock %}
43 {% block header %}<style type="text/css">.dependency { background-color: yellow; } </style>{% endblock %}
44 {% block content %}<h1>{{ package|e }}</h1>
45 <p>Version: {{ version|e }}</p>
46 <p>Architecture: {{ architecture|e }}</p>
47 <p>Number of files: {{ num_files }}</p>
48 <p>Total size: {{ total_size|format_size }}</p>
49 {%- if shared -%}
50     {%- for function, sharing in shared.items() -%}
51         <h3>sharing with respect to {{ function|e }}</h3>
52         <table border='1'><tr><th>package</th><th>files shared</th><th>data shared</th></tr>
53         {%- for entry in sharing|sort(attribute="savable", reverse=true) -%}
54             <tr><td{% if not entry.package or entry.package in dependencies %} class="dependency"{% endif %}>
55                 {%- if entry.package %}<a href="{{ entry.package|e }}">{{ entry.package|e }}</a>{% else %}self{% endif %}
56                 <a href="../compare/{{ package|e }}/{{ entry.package|default(package, true)|e }}">compare</a></td>
57             <td>{{ entry.duplicate }} ({{ (100 * entry.duplicate / num_files)|int }}%)</td>
58             <td>{{ entry.savable|format_size }} ({{ (100 * entry.savable / total_size)|int }}%)</td></tr>
59         {%- endfor -%}
60         </table>
61     {%- endfor -%}
62 {%- endif -%}
63 {% endblock %}""")
64
65 detail_template = jinjaenv.from_string(
66 """{% extends "base.html" %}
67 {% block title %}sharing between {{ details1.package|e }} and {{ details2.package|e }}{% endblock%}
68 {% block content %}
69 <h1><a href="../../binary/{{ details1.package|e }}">{{ details1.package|e }}</a> &lt;-&gt; <a href="../../binary/{{ details2.package|e }}">{{ details2.package|e }}</a></h1>
70 {%- if shared -%}
71 <table border='1'><tr><th colspan="3">{{ details1.package|e }}</th><th colspan="3">{{ details2.package|e }}</th></tr>
72 <tr><th>size</th><th>filename</th><th>hash functions</th><th>size</th><th>filename</th><th>hash functions</th></tr>
73     {%- for entry in shared|sort(attribute="size1", reverse=true) -%}
74         <tr><td>{{ entry.size1|format_size }}</td><td>{{ entry.filename1 }}</td><td>
75             {%- for funccomb, hashvalue in entry.functions.items() %}<a href="../../hash/{{ funccomb[0]|e }}/{{ hashvalue|e }}">{{ funccomb[0]|e }}</a> {% endfor %}</td>
76         <td>{{ entry.size2|format_size }}</td><td>{{ entry.filename2 }}</td><td>
77             {%- for funccomb, hashvalue in entry.functions.items() %}<a href="../../hash/{{ funccomb[1]|e }}/{{ hashvalue|e }}">{{ funccomb[1]|e }}</a> {% endfor %}</td></tr>
78     {%- endfor -%}
79 </table>
80 {%- endif -%}
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 fetchiter(cursor):
144     rows = cursor.fetchmany()
145     while rows:
146         for row in rows:
147             yield row
148         rows = cursor.fetchmany()
149
150 def encode_and_buffer(iterator):
151     buff = b""
152     for elem in iterator:
153         buff += elem.encode("utf8")
154         if len(buff) >= 2048:
155             yield buff
156             buff = b""
157     if buff:
158         yield buff
159
160 def html_response(unicode_iterator, max_age=24 * 60 * 60):
161     resp = Response(encode_and_buffer(unicode_iterator), mimetype="text/html")
162     resp.cache_control.max_age = max_age
163     resp.expires = datetime.datetime.now() + datetime.timedelta(seconds=max_age)
164     return resp
165
166 class Application(object):
167     def __init__(self, db):
168         self.db = db
169         self.routingmap = Map([
170             Rule("/", methods=("GET",), endpoint="index"),
171             Rule("/binary/<package>", methods=("GET",), endpoint="package"),
172             Rule("/compare/<package1>/<package2>", methods=("GET",), endpoint="detail"),
173             Rule("/hash/<function>/<hashvalue>", methods=("GET",), endpoint="hash"),
174         ])
175
176     @Request.application
177     def __call__(self, request):
178         mapadapter = self.routingmap.bind_to_environ(request.environ)
179         try:
180             endpoint, args = mapadapter.match()
181             if endpoint == "package":
182                 return self.show_package(args["package"])
183             elif endpoint == "detail":
184                 return self.show_detail(args["package1"], args["package2"])
185             elif endpoint == "hash":
186                 return self.show_hash(args["function"], args["hashvalue"])
187             elif endpoint == "index":
188                 if not request.environ["PATH_INFO"]:
189                     raise RequestRedirect(request.environ["SCRIPT_NAME"] + "/")
190                 return html_response(index_template.stream())
191             raise NotFound()
192         except HTTPException as e:
193             return e
194
195     def get_details(self, package):
196         cur = self.db.cursor()
197         cur.execute("SELECT version, architecture FROM package WHERE package = ?;",
198                     (package,))
199         row = cur.fetchone()
200         if not row:
201             raise NotFound()
202         version, architecture = row
203         details = dict(package=package,
204                        version=version,
205                        architecture=architecture)
206         cur.execute("SELECT count(filename), sum(size) FROM content WHERE package = ?;",
207                     (package,))
208         num_files, total_size = cur.fetchone()
209         details.update(dict(num_files=num_files, total_size=total_size))
210         return details
211
212     def get_dependencies(self, package):
213         cur = self.db.cursor()
214         cur.execute("SELECT required FROM dependency WHERE package = ?;",
215                     (package,))
216         return set(row[0] for row in fetchiter(cur))
217
218     def show_package(self, package):
219         cur = self.db.cursor()
220         params = self.get_details(package)
221         params["dependencies"] = self.get_dependencies(package)
222
223         sharedstats = {}
224         for func1, func2 in hash_functions:
225             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 != ?);",
226                         (package, func1, func2, package))
227             sharing = dict()
228             for afile, hashval, size, bpkg in fetchiter(cur):
229                 hashdict = sharing.setdefault(bpkg, dict())
230                 fileset = hashdict.setdefault(hashval, (size, set()))[1]
231                 fileset.add(afile)
232             if sharing:
233                 curstats = list()
234                 if func1 == func2:
235                     sharedstats[func1] = curstats
236                 else:
237                     sharedstats["%s -> %s" % (func1, func2)] = curstats
238                 mapping = sharing.pop(package, dict())
239                 if mapping:
240                     duplicate = sum(len(files) for _, files in mapping.values())
241                     savable = sum(size * (len(files) - 1) for size, files in mapping.values())
242                     curstats.append(dict(package=None, duplicate=duplicate, savable=savable))
243                 for pkg, mapping in sharing.items():
244                     duplicate = sum(len(files) for _, files in mapping.values())
245                     savable = sum(size * len(files) for size, files in mapping.values())
246                     curstats.append(dict(package=pkg, duplicate=duplicate, savable=savable))
247
248         params["shared"] = sharedstats
249         return html_response(package_template.render(params))
250
251     def show_detail(self, package1, package2):
252         cur = self.db.cursor()
253         if package1 == package2:
254             details1 = details2 = self.get_details(package1)
255
256             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;",
257                         (package1, package1))
258         else:
259             details1 = self.get_details(package1)
260             details2 = self.get_details(package2)
261
262             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 = ?;",
263                         (package1, package2))
264
265         shared = dict()
266         for filename1, size1, func1, filename2, size2, func2, hashvalue in fetchiter(cur):
267             funccomb = (func1, func2)
268             if funccomb not in hash_functions:
269                 continue
270             funcdict = shared.setdefault((filename1, filename2),
271                                          (size1, size2, dict()))[2]
272             funcdict[(func1, func2)] = hashvalue
273         shared = [dict(filename1=filename1, filename2=filename2, size1=size1,
274                        size2=size2, functions=functions)
275                   for (filename1, filename2), (size1, size2, functions)
276                   in shared.items()]
277         params = dict(
278             details1=details1,
279             details2=details2,
280             shared=shared)
281         return html_response(detail_template.render(params))
282
283     def show_hash(self, function, hashvalue):
284         cur = self.db.cursor()
285         cur.execute("SELECT package, filename, size, function FROM content WHERE hash = ?;",
286                     (hashvalue,))
287         entries = [dict(package=package, filename=filename, size=size,
288                         function=otherfunc)
289                    for package, filename, size, otherfunc in fetchiter(cur)
290                    if (function, otherfunc) in hash_functions]
291         if not entries:
292             raise NotFound()
293         params = dict(function=function, hashvalue=hashvalue, entries=entries)
294         return html_response(hash_template.render(params))
295
296 def main():
297     app = Application(sqlite3.connect("test.sqlite3"))
298     #app = DebuggedApplication(app, evalex=True)
299     make_server("0.0.0.0", 8800, app).serve_forever()
300
301 if __name__ == "__main__":
302     main()