schema: reference hash functions by integer key
[~helmut/debian-dedup.git] / autoimport.py
1 #!/usr/bin/python
2 """This scrip takes a directory or a http base url to a mirror and imports all
3 packages contained. It has rather strong assumptions on the working directory.
4 """
5
6 import gzip
7 import io
8 import multiprocessing
9 import optparse
10 import os
11 import sqlite3
12 import subprocess
13 import urllib
14
15 import concurrent.futures
16 from debian import deb822
17 from debian.debian_support import version_compare
18
19 from readyaml import readyaml
20
21 def process_http(pkgs, url):
22     pkglist = urllib.urlopen(url + "/dists/sid/main/binary-amd64/Packages.gz").read()
23     pkglist = gzip.GzipFile(fileobj=io.BytesIO(pkglist)).read()
24     pkglist = io.BytesIO(pkglist)
25     pkglist = deb822.Packages.iter_paragraphs(pkglist)
26     for pkg in pkglist:
27         name = pkg["Package"]
28         if name in pkgs and \
29                 version_compare(pkgs[name]["version"], pkg["Version"]) > 0:
30             continue
31         pkgs[name] = dict(version=pkg["Version"],
32                           filename="%s/%s" % (url, pkg["Filename"]))
33
34 def process_file(pkgs, filename):
35     base = os.path.basename(filename)
36     if not base.endswith(".deb"):
37         raise ValueError("filename does not end in .deb")
38     parts = base.split("_")
39     if len(parts) != 3:
40         raise ValueError("filename not in form name_version_arch.deb")
41     name, version, _ = parts
42     version = urllib.unquote(version)
43     if name in pkgs and version_compare(pkgs[name]["version"], version) > 0:
44         return
45     pkgs[name] = dict(version=version, filename=filename)
46
47 def process_dir(pkgs, d):
48     for entry in os.listdir(d):
49         try:
50             process_file(pkgs, os.path.join(d, entry))
51         except ValueError:
52             pass
53
54 def process_pkg(name, filename):
55     print("importing %s" % filename)
56     if filename.startswith("http://"):
57         with open(os.path.join("tmp", name), "w") as outp:
58             dl = subprocess.Popen(["curl", "-s", filename],
59                                   stdout=subprocess.PIPE, close_fds=True)
60             imp = subprocess.Popen(["python", "importpkg.py"], stdin=dl.stdout,
61                                    stdout=outp, close_fds=True)
62             if imp.wait():
63                 raise ValueError("importpkg failed")
64             if dl.wait():
65                 raise ValueError("curl failed")
66     else:
67         with open(filename) as inp:
68             with open(os.path.join("tmp", name), "w") as outp:
69                 subprocess.check_call(["python", "importpkg.py"], stdin=inp,
70                                       stdout=outp, close_fds=True)
71     print("preprocessed %s" % name)
72
73 def main():
74     parser = optparse.OptionParser()
75     parser.add_option("-n", "--new", action="store_true",
76                       help="avoid reimporting same versions")
77     parser.add_option("-p", "--prune", action="store_true",
78                       help="prune packages old packages")
79     options, args = parser.parse_args()
80     subprocess.check_call(["mkdir", "-p", "tmp"])
81     db = sqlite3.connect("test.sqlite3")
82     cur = db.cursor()
83     cur.execute("PRAGMA foreign_keys = ON;")
84     e = concurrent.futures.ThreadPoolExecutor(multiprocessing.cpu_count())
85     pkgs = {}
86     for d in args:
87         print("processing %s" % d)
88         if d.startswith("http://"):
89             process_http(pkgs, d)
90         elif os.path.isdir(d):
91             process_dir(pkgs, d)
92         else:
93             process_file(pkgs, d)
94
95     print("reading database")
96     cur.execute("SELECT name, version FROM package;")
97     knownpkgs = dict((row[0], row[1]) for row in cur.fetchall())
98     distpkgs = set(pkgs.keys())
99     if options.new:
100         for name in distpkgs:
101             if name in knownpkgs and version_compare(pkgs[name]["version"],
102                     knownpkgs[name]) <= 0:
103                 del pkgs[name]
104     knownpkgs = set(knownpkgs)
105
106     with e:
107         fs = {}
108         for name, pkg in pkgs.items():
109             fs[e.submit(process_pkg, name, pkg["filename"])] = name
110
111         for f in concurrent.futures.as_completed(fs.keys()):
112             name = fs[f]
113             if f.exception():
114                 print("%s failed to import: %r" % (name, f.exception()))
115                 continue
116             inf = os.path.join("tmp", name)
117             print("sqlimporting %s" % name)
118             with open(inf) as inp:
119                 try:
120                     readyaml(db, inp)
121                 except Exception as exc:
122                     print("%s failed sql with exception %r" % (name, exc))
123                 else:
124                     os.unlink(inf)
125
126     if options.prune:
127         delpkgs = knownpkgs - distpkgs
128         print("clearing packages %s" % " ".join(delpkgs))
129         cur.executemany("DELETE FROM package WHERE name = ?;",
130                         ((pkg,) for pkg in delpkgs))
131         # Tables content, dependency and sharing will also be pruned
132         # due to ON DELETE CASCADE clauses.
133         db.commit()
134
135 if __name__ == "__main__":
136     main()