webapp: add concept of "build architecture" to frontend
[~helmut/crossqa.git] / build.py
1 #!/usr/bin/python3
2 # SPDX-License-Identifier: GPL-2.0+
3
4 import argparse
5 import collections
6 import contextlib
7 import datetime
8 import lzma
9 import os
10 import os.path
11 import sqlite3
12 import subprocess
13 import time
14
15 from common import decompress_stream, yield_lines, yield_chunks
16
17 def scan_log_status(filelike):
18     it = yield_chunks(filelike)
19     it = decompress_stream(it, lzma.LZMADecompressor())
20     it = yield_lines(it)
21     last_lines = collections.deque(it, 25)
22     status = [l.split(b':', 1)[1].strip()
23               for l in last_lines if l.startswith(b"Status:")]
24     if status:
25         return status[0].decode("ascii")
26     return "unknown"
27
28
29 def do_build(source, version, architecture, server):
30     now = datetime.datetime.utcnow().replace(microsecond=0)
31     logtarget = "%s_%s_%s_%s.log.xz" % (source, version, architecture,
32                                         now.strftime("%Y%m%d%H%M%S"))
33     cmdline = ["ssh", server, "sh", "/dev/stdin", architecture,
34                "%s_%s" % (source, version)]
35     logname = os.path.join("logs", logtarget)
36     with open(logname, "w+b") as output:
37         with open("build.sh", "rb") as instructions:
38             code = subprocess.call(cmdline, stdin=instructions, stdout=output)
39         output.seek(0)
40         status = scan_log_status(output)
41     if code == 255:
42         os.unlink(logname)
43         time.sleep(300)
44         raise RuntimeError("ssh failed")
45     print("status %s code %d" % (status, code))
46     return (now, code == 0, logtarget, status == "given-back")
47
48 def main():
49     argp = argparse.ArgumentParser()
50     argp.add_argument("server", help="machine to build on")
51     args = argp.parse_args()
52     db = sqlite3.connect("db", detect_types=sqlite3.PARSE_DECLTYPES)
53     with contextlib.closing(db.cursor()) as cur:
54         cur.execute("BEGIN IMMEDIATE;")
55         cur.execute("""
56             SELECT d.source, d.version, d.architecture, r.id
57                 FROM depstate AS d
58                     JOIN buildrequests AS r
59                         ON d.architecture = ifnull(r.architecture, d.architecture)
60                             AND d.source = r.source
61                     JOIN depcheck
62                         ON d.architecture = depcheck.architecture
63                 WHERE d.satisfiable = 1 AND depcheck.giveback = 0
64                     AND NOT EXISTS (SELECT 1 FROM building
65                         WHERE d.source = building.source
66                             OR d.architecture = building.architecture)
67                 ORDER BY r.priority DESC, r.requesttime ASC, random()
68                 LIMIT 1;""")
69         row = cur.fetchone()
70         if not row:
71             cur.execute("""
72                 SELECT source, version, depstate.architecture, NULL
73                     FROM depstate JOIN depcheck
74                         ON depstate.architecture = depcheck.architecture
75                     WHERE satisfiable = 1 AND giveback = 0
76                     ORDER BY random() LIMIT 1;""")
77             row = cur.fetchone()
78         if not row:
79             cur.execute("ROLLBACK;")
80             print("no package satisfiable")
81             time.sleep(60)
82             return
83         source, version, architecture, requestid = row
84         cur.execute("""INSERT INTO building (source, architecture, pid)
85                            VALUES (?, ?, ?);""",
86                     (source, architecture, os.getpid()))
87         cur.execute("COMMIT;")
88     try:
89         print("building %s_%s for %s%s" %
90               (source, version, architecture,
91                "" if requestid is None else " (request %d)" % requestid))
92         timestamp, success, filename, giveback = \
93             do_build(source, version, architecture, args.server)
94         with contextlib.closing(db.cursor()) as cur:
95             cur.execute("""INSERT INTO builds
96                             (source, version, architecture, success, starttime,
97                              filename) VALUES (?, ?, ?, ?, ?, ?);""",
98                         (source, version, architecture, success, timestamp,
99                          filename))
100             if requestid is not None:
101                 cur.execute("DELETE FROM buildrequests WHERE id = ?;",
102                             (requestid,))
103             if giveback:
104                 cur.execute("""UPDATE depcheck SET giveback = 1
105                                 WHERE architecture = ?;""",
106                             (architecture,))
107     finally:
108         with contextlib.closing(db.cursor()) as cur:
109             cur.execute("DELETE FROM building WHERE pid = ?;", (os.getpid(),))
110         db.commit()
111
112 if __name__ == "__main__":
113     main()