also move the static directory into the dedup package
[~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 from werkzeug.wsgi import SharedDataMiddleware
12
13 from dedup.utils import fetchiter
14
15 hash_functions = [
16         ("sha512", "sha512"),
17         ("image_sha512", "image_sha512"),
18         ("gzip_sha512", "gzip_sha512"),
19         ("sha512", "gzip_sha512"),
20         ("gzip_sha512", "sha512")]
21
22 jinjaenv = jinja2.Environment(loader=jinja2.PackageLoader("dedup", "templates"))
23
24 def format_size(size):
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 # Workaround for jinja bug #59 (broken filesizeformat)
44 jinjaenv.filters["filesizeformat"] = format_size
45
46 base_template = jinjaenv.get_template("base.html")
47 package_template = jinjaenv.get_template("binary.html")
48 detail_template = jinjaenv.get_template("compare.html")
49 hash_template = jinjaenv.get_template("hash.html")
50 index_template = jinjaenv.get_template("index.html")
51 source_template = jinjaenv.get_template("source.html")
52
53 def encode_and_buffer(iterator):
54     buff = b""
55     for elem in iterator:
56         buff += elem.encode("utf8")
57         if len(buff) >= 2048:
58             yield buff
59             buff = b""
60     if buff:
61         yield buff
62
63 def html_response(unicode_iterator, max_age=24 * 60 * 60):
64     resp = Response(encode_and_buffer(unicode_iterator), mimetype="text/html")
65     resp.cache_control.max_age = max_age
66     resp.expires = datetime.datetime.now() + datetime.timedelta(seconds=max_age)
67     return resp
68
69 class Application(object):
70     def __init__(self, db):
71         self.db = db
72         self.routingmap = Map([
73             Rule("/", methods=("GET",), endpoint="index"),
74             Rule("/binary/<package>", methods=("GET",), endpoint="package"),
75             Rule("/compare/<package1>/<package2>", methods=("GET",), endpoint="detail"),
76             Rule("/hash/<function>/<hashvalue>", methods=("GET",), endpoint="hash"),
77             Rule("/source/<package>", methods=("GET",), endpoint="source"),
78         ])
79
80     @Request.application
81     def __call__(self, request):
82         mapadapter = self.routingmap.bind_to_environ(request.environ)
83         try:
84             endpoint, args = mapadapter.match()
85             if endpoint == "package":
86                 return self.show_package(args["package"])
87             elif endpoint == "detail":
88                 return self.show_detail(args["package1"], args["package2"])
89             elif endpoint == "hash":
90                 return self.show_hash(args["function"], args["hashvalue"])
91             elif endpoint == "index":
92                 if not request.environ["PATH_INFO"]:
93                     raise RequestRedirect(request.environ["SCRIPT_NAME"] + "/")
94                 return html_response(index_template.render(dict(urlroot="")))
95             elif endpoint == "source":
96                 return self.show_source(args["package"])
97             raise NotFound()
98         except HTTPException as e:
99             return e
100
101     def get_details(self, package):
102         cur = self.db.cursor()
103         cur.execute("SELECT id, version, architecture FROM package WHERE name = ?;",
104                     (package,))
105         row = cur.fetchone()
106         if not row:
107             raise NotFound()
108         pid, version, architecture = row
109         details = dict(pid=pid,
110                        package=package,
111                        version=version,
112                        architecture=architecture)
113         cur.execute("SELECT count(filename), sum(size) FROM content WHERE pid = ?;",
114                     (pid,))
115         num_files, total_size = cur.fetchone()
116         if total_size is None:
117             total_size = 0
118         details.update(dict(num_files=num_files, total_size=total_size))
119         return details
120
121     def get_dependencies(self, pid):
122         cur = self.db.cursor()
123         cur.execute("SELECT required FROM dependency WHERE pid = ?;",
124                     (pid,))
125         return set(row[0] for row in fetchiter(cur))
126
127     def cached_sharedstats(self, pid):
128         cur = self.db.cursor()
129         sharedstats = {}
130         cur.execute("SELECT pid2, package.name, f1.name, f2.name, files, size FROM sharing JOIN package ON sharing.pid2 = package.id JOIN function AS f1 ON sharing.fid1 = f1.id JOIN function AS f2 ON sharing.fid2 = f2.id WHERE pid1 = ?;",
131                     (pid,))
132         for pid2, package2, func1, func2, files, size in fetchiter(cur):
133             if (func1, func2) not in hash_functions:
134                 continue
135             curstats = sharedstats.setdefault(
136                     function_combination(func1, func2), list())
137             if pid2 == pid:
138                 package2 = None
139             curstats.append(dict(package=package2, duplicate=files, savable=size))
140         return sharedstats
141
142     def show_package(self, package):
143         params = self.get_details(package)
144         params["dependencies"] = self.get_dependencies(params["pid"])
145         params["shared"] = self.cached_sharedstats(params["pid"])
146         params["urlroot"] = ".."
147         cur = self.db.cursor()
148         cur.execute("SELECT content.filename, issue.issue FROM content JOIN issue ON content.id = issue.cid WHERE content.pid = ?;",
149                     (params["pid"],))
150         params["issues"] = dict(cur.fetchall())
151         cur.close()
152         return html_response(package_template.render(params))
153
154     def compute_comparison(self, pid1, pid2):
155         """Compute a sequence of comparison objects ordery by the size of the
156         object in the first package. Each element of the sequence is a dict
157         defining the following keys:
158          * filenames: A set of filenames in package 1 (pid1) all referring to
159            the same object.
160          * size: Size of the object in bytes.
161          * matches: A mapping from filenames in package 2 (pid2) to a mapping
162            from hash function pairs to hash values.
163         """
164         cur = self.db.cursor()
165         cur.execute("SELECT content.id, content.filename, content.size, hash.hash FROM content JOIN hash ON content.id = hash.cid JOIN duplicate ON content.id = duplicate.cid JOIN function ON hash.fid = function.id WHERE pid = ? AND function.name = 'sha512' ORDER BY size DESC;",
166                     (pid1,))
167         cursize = -1
168         files = dict()
169         minmatch = 2 if pid1 == pid2 else 1
170         for cid, filename, size, hashvalue in fetchiter(cur):
171             if cursize != size:
172                 for entry in files.values():
173                     if len(entry["matches"]) >= minmatch:
174                         yield entry
175                 files.clear()
176                 cursize = size
177
178             if hashvalue in files:
179                 files[hashvalue]["filenames"].add(filename)
180                 continue
181
182             entry = dict(filenames=set((filename,)), size=size, matches={})
183             files[hashvalue] = entry
184
185             cur2 = self.db.cursor()
186             cur2.execute("SELECT fa.name, ha.hash, fb.name, filename FROM hash AS ha JOIN hash AS hb ON ha.hash = hb.hash JOIN content ON hb.cid = content.id JOIN function AS fa ON ha.fid = fa.id JOIN function AS fb ON hb.fid = fb.id WHERE ha.cid = ? AND pid = ?;",
187                          (cid, pid2))
188             for func1, hashvalue, func2, filename in fetchiter(cur2):
189                 entry["matches"].setdefault(filename, {})[func1, func2] = \
190                         hashvalue
191             cur2.close()
192         cur.close()
193
194         for entry in files.values():
195             if len(entry["matches"]) >= minmatch:
196                 yield entry
197
198     def show_detail(self, package1, package2):
199         details1 = details2 = self.get_details(package1)
200         if package1 != package2:
201             details2 = self.get_details(package2)
202
203         shared = self.compute_comparison(details1["pid"], details2["pid"])
204         params = dict(
205             details1=details1,
206             details2=details2,
207             urlroot="../..",
208             shared=shared)
209         return html_response(detail_template.stream(params))
210
211     def show_hash(self, function, hashvalue):
212         cur = self.db.cursor()
213         cur.execute("SELECT package.name, content.filename, content.size, function.name FROM hash JOIN content ON hash.cid = content.id JOIN package ON content.pid = package.id JOIN function ON hash.fid = function.id WHERE hash = ?;",
214                     (hashvalue,))
215         entries = [dict(package=package, filename=filename, size=size,
216                         function=otherfunc)
217                    for package, filename, size, otherfunc in fetchiter(cur)
218                    if (function, otherfunc) in hash_functions]
219         if not entries:
220             raise NotFound()
221         params = dict(function=function, hashvalue=hashvalue, entries=entries,
222                       urlroot="../..")
223         return html_response(hash_template.render(params))
224
225     def show_source(self, package):
226         cur = self.db.cursor()
227         cur.execute("SELECT name FROM package WHERE source = ?;",
228                     (package,))
229         binpkgs = dict.fromkeys(pkg for pkg, in fetchiter(cur))
230         if not binpkgs:
231             raise NotFound
232         cur.execute("SELECT p1.name, p2.name, f1.name, f2.name, sharing.files, sharing.size FROM sharing JOIN package AS p1 ON sharing.pid1 = p1.id JOIN package AS p2 ON sharing.pid2 = p2.id JOIN function AS f1 ON sharing.fid1 = f1.id JOIN function AS f2 ON sharing.fid2 = f2.id WHERE p1.source = ?;",
233                     (package,))
234         for binary, otherbin, func1, func2, files, size in fetchiter(cur):
235             entry = dict(package=otherbin,
236                          funccomb=function_combination(func1, func2),
237                          duplicate=files, savable=size)
238             oldentry = binpkgs.get(binary)
239             if not (oldentry and oldentry["savable"] >= size):
240                 binpkgs[binary] = entry
241         params = dict(source=package, packages=binpkgs, urlroot="..")
242         return html_response(source_template.render(params))
243
244 def main():
245     app = Application(sqlite3.connect("test.sqlite3"))
246     app = SharedDataMiddleware(app, {"/": ("dedup", "static")})
247     make_server("0.0.0.0", 8800, app).serve_forever()
248
249 if __name__ == "__main__":
250     main()