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