webapp: pass database to Application class
[~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 content %}
101 <h1>Debian duplication detector</h1>
102 <ul>
103 <li>To inspect a particlar binary package, go to <pre>binary/&lt;packagename&gt;</pre> Example: <a href="binary/git">binary/git</a></li>
104 <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>
105 <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>
106 </ul>
107 {% endblock %}""")
108
109 def fetchiter(cursor):
110     rows = cursor.fetchmany()
111     while rows:
112         for row in rows:
113             yield row
114         rows = cursor.fetchmany()
115
116 def encode_and_buffer(iterator):
117     buff = b""
118     for elem in iterator:
119         buff += elem.encode("utf8")
120         if len(buff) >= 2048:
121             yield buff
122             buff = b""
123     if buff:
124         yield buff
125
126 def html_response(unicode_iterator, max_age=24 * 60 * 60):
127     resp = Response(encode_and_buffer(unicode_iterator), mimetype="text/html")
128     resp.cache_control.max_age = max_age
129     resp.expires = datetime.datetime.now() + datetime.timedelta(seconds=max_age)
130     return resp
131
132 class Application(object):
133     def __init__(self, db):
134         self.db = db
135         self.cur = self.db.cursor()
136         self.routingmap = Map([
137             Rule("/", methods=("GET",), endpoint="index"),
138             Rule("/binary/<package>", methods=("GET",), endpoint="package"),
139             Rule("/compare/<package1>/<package2>", methods=("GET",), endpoint="detail"),
140             Rule("/hash/<function>/<hashvalue>", methods=("GET",), endpoint="hash"),
141         ])
142
143     @Request.application
144     def __call__(self, request):
145         mapadapter = self.routingmap.bind_to_environ(request.environ)
146         try:
147             endpoint, args = mapadapter.match()
148             if endpoint == "package":
149                 return self.show_package(args["package"])
150             elif endpoint == "detail":
151                 return self.show_detail(args["package1"], args["package2"])
152             elif endpoint == "hash":
153                 return self.show_hash(args["function"], args["hashvalue"])
154             elif endpoint == "index":
155                 if not request.environ["PATH_INFO"]:
156                     raise RequestRedirect(request.environ["SCRIPT_NAME"] + "/")
157                 return html_response(index_template.stream())
158             raise NotFound()
159         except HTTPException as e:
160             return e
161
162     def get_details(self, package):
163         self.cur.execute("SELECT version, architecture FROM package WHERE package = ?;",
164                          (package,))
165         row = self.cur.fetchone()
166         if not row:
167             raise NotFound()
168         version, architecture = row
169         details = dict(package=package,
170                        version=version,
171                        architecture=architecture)
172         self.cur.execute("SELECT count(filename), sum(size) FROM content WHERE package = ?;",
173                          (package,))
174         num_files, total_size = self.cur.fetchone()
175         details.update(dict(num_files=num_files, total_size=total_size))
176         return details
177
178     def get_dependencies(self, package):
179         self.cur.execute("SELECT required FROM dependency WHERE package = ?;",
180                          (package,))
181         return set(row[0] for row in fetchiter(self.cur))
182
183     def show_package(self, package):
184         params = self.get_details(package)
185         params["dependencies"] = self.get_dependencies(package)
186
187         sharedstats = {}
188         for func1, func2 in hash_functions:
189             self.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 != ?);",
190                              (package, func1, func2, package))
191             sharing = dict()
192             for afile, hashval, size, bpkg in fetchiter(self.cur):
193                 hashdict = sharing.setdefault(bpkg, dict())
194                 fileset = hashdict.setdefault(hashval, (size, set()))[1]
195                 fileset.add(afile)
196             if sharing:
197                 curstats = list()
198                 if func1 == func2:
199                     sharedstats[func1] = curstats
200                 else:
201                     sharedstats["%s -> %s" % (func1, func2)] = curstats
202                 mapping = sharing.pop(package, dict())
203                 if mapping:
204                     duplicate = sum(len(files) for _, files in mapping.values())
205                     savable = sum(size * (len(files) - 1) for size, files in mapping.values())
206                     curstats.append(dict(package=None, duplicate=duplicate, savable=savable))
207                 for pkg, mapping in sharing.items():
208                     duplicate = sum(len(files) for _, files in mapping.values())
209                     savable = sum(size * len(files) for size, files in mapping.values())
210                     curstats.append(dict(package=pkg, duplicate=duplicate, savable=savable))
211
212         params["shared"] = sharedstats
213         return html_response(package_template.render(params))
214
215     def show_detail(self, package1, package2):
216         if package1 == package2:
217             details1 = details2 = self.get_details(package1)
218
219             self.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;",
220                              (package1, package1))
221         else:
222             details1 = self.get_details(package1)
223             details2 = self.get_details(package2)
224
225             self.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 = ?;",
226                              (package1, package2))
227
228         shared = dict()
229         for filename1, size1, func1, filename2, size2, func2, hashvalue in fetchiter(self.cur):
230             funccomb = (func1, func2)
231             if funccomb not in hash_functions:
232                 continue
233             funcdict = shared.setdefault((filename1, filename2),
234                                          (size1, size2, dict()))[2]
235             funcdict[(func1, func2)] = hashvalue
236         shared = [dict(filename1=filename1, filename2=filename2, size1=size1,
237                        size2=size2, functions=functions)
238                   for (filename1, filename2), (size1, size2, functions)
239                   in shared.items()]
240         params = dict(
241             details1=details1,
242             details2=details2,
243             shared=shared)
244         return html_response(detail_template.render(params))
245
246     def show_hash(self, function, hashvalue):
247         self.cur.execute("SELECT package, filename, size, function FROM content WHERE hash = ?;",
248                          (hashvalue,))
249         entries = [dict(package=package, filename=filename, size=size,
250                         function=otherfunc)
251                    for package, filename, size, otherfunc in fetchiter(self.cur)
252                    if (function, otherfunc) in hash_functions]
253         if not entries:
254             raise NotFound()
255         params = dict(function=function, hashvalue=hashvalue, entries=entries)
256         return html_response(hash_template.render(params))
257
258 def main():
259     app = Application(sqlite3.connect("test.sqlite3"))
260     #app = DebuggedApplication(app, evalex=True)
261     make_server("0.0.0.0", 8800, app).serve_forever()
262
263 if __name__ == "__main__":
264     main()