#!/usr/bin/python import datetime import sqlite3 from wsgiref.simple_server import make_server import jinja2 from werkzeug.exceptions import HTTPException, NotFound from werkzeug.routing import Map, Rule, RequestRedirect from werkzeug.wrappers import Request, Response from dedup.utils import fetchiter hash_functions = [ ("sha512", "sha512"), ("image_sha512", "image_sha512"), ("gzip_sha512", "gzip_sha512"), ("sha512", "gzip_sha512"), ("gzip_sha512", "sha512")] jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(".")) def format_size(size): assert isinstance(size, int) size = float(size) fmt = "%d B" if size >= 1024: size /= 1024 fmt = "%.1f KB" if size >= 1024: size /= 1024 fmt = "%.1f MB" if size >= 1024: size /= 1024 fmt = "%.1f GB" return fmt % size def function_combination(function1, function2): if function1 == function2: return function1 return "%s -> %s" % (function1, function2) jinjaenv.filters["format_size"] = format_size base_template = jinjaenv.get_template("base.html") package_template = jinjaenv.from_string( """{% extends "base.html" %} {% block title %}duplication of {{ package|e }}{% endblock %} {% block header %}{% endblock %} {% block content %}

{{ package|e }}

Version: {{ version|e }}

Architecture: {{ architecture|e }}

Number of files: {{ num_files }}

Total size: {{ total_size|format_size }}

{%- if shared -%} {%- for function, sharing in shared.items() -%}

sharing with respect to {{ function|e }}

{%- for entry in sharing|sort(attribute="savable", reverse=true) -%} {%- if entry.package %}{{ entry.package|e }}{% else %}self{% endif %} compare {%- endfor -%}
packagefiles shareddata shared
{{ entry.duplicate }} ({{ (100 * entry.duplicate / num_files)|int }}%) {{ entry.savable|format_size }} ({{ (100 * entry.savable / total_size)|int }}%)
{%- endfor -%} {%- endif -%} {% endblock %}""") detail_template = jinjaenv.from_string( """{% extends "base.html" %} {% block title %}sharing between {{ details1.package|e }} and {{ details2.package|e }}{% endblock%} {% block content %}

{{ details1.package|e }} <-> {{ details2.package|e }}

{%- for entry in shared -%} {%- endfor -%}
{{ details1.package|e }}{{ details2.package|e }}
sizefilenamehash functionssizefilenamehash functions
{{ entry.size1|format_size }}{{ entry.filename1 }} {%- for funccomb, hashvalue in entry.functions.items() %}{{ funccomb[0]|e }} {% endfor %} {{ entry.size2|format_size }}{{ entry.filename2 }} {%- for funccomb, hashvalue in entry.functions.items() %}{{ funccomb[1]|e }} {% endfor %}
{% endblock %}""") hash_template = jinjaenv.from_string( """{% extends "base.html" %} {% block title %}information on {{ function|e }} hash {{ hashvalue|e }}{% endblock %} {% block content %}

{{ function|e }} {{ hashvalue|e }}

{%- for entry in entries -%} {%- endfor -%}
packagefilenamesizedifferent function
{{ entry.package|e }} {{ entry.filename|e }}{{ entry.size|format_size }} {% if function != entry.function %}{{ entry.function|e }}{% endif %}
{% endblock %}""") index_template = jinjaenv.from_string( """{% extends "base.html" %} {% block title %}Debian duplication detector{% endblock %} {% block header %} {% endblock %} {% block content %}

Debian duplication detector

{% endblock %}""") source_template = jinjaenv.from_string( """{% extends "base.html" %} {% block title %}overview of {{ source|e }}{% endblock %} {% block content %}

overview of {{ source|e }}

{% for package, sharing in packages.items() %} {% endfor %}
binary from {{ source|e }}savableother package
{{ package|e }} {%- if sharing -%} {{ sharing.savable|format_size }}{{ sharing.package|e }} compare {%- else -%}{%- endif -%}
{% endblock %}""") def encode_and_buffer(iterator): buff = b"" for elem in iterator: buff += elem.encode("utf8") if len(buff) >= 2048: yield buff buff = b"" if buff: yield buff def html_response(unicode_iterator, max_age=24 * 60 * 60): resp = Response(encode_and_buffer(unicode_iterator), mimetype="text/html") resp.cache_control.max_age = max_age resp.expires = datetime.datetime.now() + datetime.timedelta(seconds=max_age) return resp def generate_shared(rows): """internal helper from show_detail""" entry = None for filename1, size1, func1, filename2, size2, func2, hashvalue in rows: funccomb = (func1, func2) if funccomb not in hash_functions: continue if entry and (entry["filename1"] != filename1 or entry["filename2"] != filename2): yield entry entry = None if entry: funcdict = entry["functions"] else: funcdict = dict() entry = dict(filename1=filename1, filename2=filename2, size1=size1, size2=size2, functions=funcdict) funcdict[funccomb] = hashvalue if entry: yield entry class Application(object): def __init__(self, db): self.db = db self.routingmap = Map([ Rule("/", methods=("GET",), endpoint="index"), Rule("/binary/", methods=("GET",), endpoint="package"), Rule("/compare//", methods=("GET",), endpoint="detail"), Rule("/hash//", methods=("GET",), endpoint="hash"), Rule("/source/", methods=("GET",), endpoint="source"), ]) @Request.application def __call__(self, request): mapadapter = self.routingmap.bind_to_environ(request.environ) try: endpoint, args = mapadapter.match() if endpoint == "package": return self.show_package(args["package"]) elif endpoint == "detail": return self.show_detail(args["package1"], args["package2"]) elif endpoint == "hash": return self.show_hash(args["function"], args["hashvalue"]) elif endpoint == "index": if not request.environ["PATH_INFO"]: raise RequestRedirect(request.environ["SCRIPT_NAME"] + "/") return html_response(index_template.stream()) elif endpoint == "source": return self.show_source(args["package"]) raise NotFound() except HTTPException as e: return e def get_details(self, package): cur = self.db.cursor() cur.execute("SELECT version, architecture FROM package WHERE package = ?;", (package,)) row = cur.fetchone() if not row: raise NotFound() version, architecture = row details = dict(package=package, version=version, architecture=architecture) cur.execute("SELECT count(filename), sum(size) FROM content WHERE package = ?;", (package,)) num_files, total_size = cur.fetchone() details.update(dict(num_files=num_files, total_size=total_size)) return details def get_dependencies(self, package): cur = self.db.cursor() cur.execute("SELECT required FROM dependency WHERE package = ?;", (package,)) return set(row[0] for row in fetchiter(cur)) def cached_sharedstats(self, package): cur = self.db.cursor() sharedstats = {} cur.execute("SELECT package2, func1, func2, files, size FROM sharing WHERE package1 = ?;", (package,)) for package2, func1, func2, files, size in fetchiter(cur): if (func1, func2) not in hash_functions: continue curstats = sharedstats.setdefault( function_combination(func1, func2), list()) if package2 == package: package2 = None curstats.append(dict(package=package2, duplicate=files, savable=size)) return sharedstats def show_package(self, package): params = self.get_details(package) params["dependencies"] = self.get_dependencies(package) params["shared"] = self.cached_sharedstats(package) return html_response(package_template.render(params)) def show_detail(self, package1, package2): cur = self.db.cursor() if package1 == package2: details1 = details2 = self.get_details(package1) 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;", (package1, package1)) else: details1 = self.get_details(package1) details2 = self.get_details(package2) 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;", (package1, package2)) shared = generate_shared(fetchiter(cur)) # The cursor will be in use until the template is fully rendered. params = dict( details1=details1, details2=details2, shared=shared) return html_response(detail_template.stream(params)) def show_hash(self, function, hashvalue): cur = self.db.cursor() cur.execute("SELECT content.package, content.filename, content.size, hash.function FROM content JOIN hash ON content.id = hash.cid WHERE hash = ?;", (hashvalue,)) entries = [dict(package=package, filename=filename, size=size, function=otherfunc) for package, filename, size, otherfunc in fetchiter(cur) if (function, otherfunc) in hash_functions] if not entries: raise NotFound() params = dict(function=function, hashvalue=hashvalue, entries=entries) return html_response(hash_template.render(params)) def show_source(self, package): cur = self.db.cursor() cur.execute("SELECT package FROM package WHERE source = ?;", (package,)) binpkgs = dict.fromkeys(pkg for pkg, in fetchiter(cur)) if not binpkgs: raise NotFound 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 = ?;", (package,)) for binary, otherbin, func1, func2, files, size in fetchiter(cur): entry = dict(package=otherbin, funccomb=function_combination(func1, func2), duplicate=files, savable=size) oldentry = binpkgs.get(binary) if not (oldentry and oldentry["savable"] >= size): binpkgs[binary] = entry params = dict(source=package, packages=binpkgs) return html_response(source_template.render(params)) def main(): app = Application(sqlite3.connect("test.sqlite3")) #app = DebuggedApplication(app, evalex=True) make_server("0.0.0.0", 8800, app).serve_forever() if __name__ == "__main__": main()