mvd001/cyberset / scripts /graphs /graph_worker.py
mvd001's picture
download
raw
16.9 kB
#!/usr/bin/env python3
"""cyberset Stage 4 graph worker.
Claims batches from work/graphs/plan.parquet in batch_id order (= priority order), writes the
sample files, runs joern-parse + export_graphs.sc, encodes the graphs with the shared vocab, and
writes work/graphs/batches/b<id>.parquet + status/b<id>.parquet + done/b<id>.json.
Resumable: done batches are skipped; claims held by dead pids are released on startup.
"""
import argparse, json, os, re, shutil, signal, sqlite3, subprocess, sys, textwrap, threading, time
from pathlib import Path
import numpy as np, pyarrow as pa, pyarrow.parquet as pq
ROOT = Path(__file__).resolve().parents[2]
W = ROOT / "work/graphs"
JOERN = Path("/workspace/tools/joern/v4.0.645/joern-cli")
TOOL_VERSION = "v4.0.645"
EXPORT = ROOT / "scripts/graphs/export_graphs.sc"
ETYPE = {"AST": 0, "CFG": 1, "CDG": 2, "REACHING_DEF": 3, "CALL": 4, "CONTAINS": 5}
REPRS = [("AST", (0,)), ("CFG", (1,)), ("CDG", (2,)), ("DDG", (3,)), ("PDG", (2, 3)), ("CALL", (5, 4))]
EXT = {"c": ".c", "c_or_cpp": ".c", "c_or_cpp_header": ".c", "cpp": ".cpp", "java": ".java", "csharp": ".cs",
"kotlin": ".kt", "kts": ".kt", "javascript": ".js", "typescript": ".ts", "tsx": ".tsx", "python": ".py",
"php": ".php", "go": ".go", "ruby": ".rb", "rust": ".rs", "swift": ".swift"}
JAVA_TYPE = re.compile(r"^\s*(package|import|using)\b|^\s*((public|private|protected|abstract|final|static|sealed|partial|internal)\s+)*(class|interface|enum|record|namespace|struct)\s")
JS_METHOD = re.compile(r"^\s*((static|async|get|set|public|private|protected|readonly|override)\s+|\*\s*)*[A-Za-z_$#][\w$]*\s*(<[^>]*>)?\s*\([^)]*\)\s*(:\s*[^{=]+)?\{")
PHP_METHOD = re.compile(r"^\s*((public|private|protected|static|abstract|final)\s+)+")
def wrap(lang_detail, code):
"""returns (text, line_offset)"""
c = code.replace("\r\n", "\n")
if lang_detail in ("java", "csharp"):
if not JAVA_TYPE.match(c): return "class __W {\n" + c + "\n}\n", 1
elif lang_detail == "go":
if not re.match(r"^\s*package\s", c): return "package p\n" + c + "\n", 1
elif lang_detail == "php":
body, off = c, 0
if not body.lstrip().startswith("<?"):
if PHP_METHOD.match(body): return "<?php\nclass __W {\n" + body + "\n}\n", 2
return "<?php\n" + body + "\n", 1
elif lang_detail == "python":
return textwrap.dedent(c) + "\n", 0
elif lang_detail in ("javascript", "typescript", "tsx"):
if JS_METHOD.match(c) and not re.match(r"^\s*(function|if|for|while|switch|catch|return)\b", c):
return "class __W {\n" + c + "\n}\n", 1
return c + "\n", 0
def log(k, msg):
print(time.strftime("%Y-%m-%d %H:%M:%S"), f"[w{k}]", msg, flush=True)
class RssPoller(threading.Thread):
"""peak RSS (MB) of a process session"""
def __init__(self, pid):
super().__init__(daemon=True); self.sid = pid; self.peak = 0; self.stop = False
def run(self):
while not self.stop:
tot = 0
for p in os.listdir("/proc"):
if not p.isdigit(): continue
try:
st = open(f"/proc/{p}/stat").read().rsplit(")", 1)[1].split()
if int(st[3]) == self.sid: # session id field (6th overall) -> index 3 after ')' split: state ppid pgrp session
tot += int(st[21]) * 4096
except Exception: pass
self.peak = max(self.peak, tot); time.sleep(1)
def run(cmd, timeout, env, logf, cwd=None):
t0 = time.time()
with open(logf, "ab") as lf:
p = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT, env=env, start_new_session=True, cwd=cwd)
poll = RssPoller(p.pid); poll.start()
try:
rc = p.wait(timeout=timeout); to = False
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL); p.wait(); rc = -9; to = True
poll.stop = True; poll.join()
return rc, to, time.time() - t0, poll.peak / 2**20
class Vocab:
def __init__(self, path):
self.db = sqlite3.connect(path, timeout=600, isolation_level=None)
self.db.execute("PRAGMA journal_mode=WAL")
for t in ("node_type", "token"):
self.db.execute(f"CREATE TABLE IF NOT EXISTS {t} (id INTEGER PRIMARY KEY, s TEXT UNIQUE NOT NULL)")
self.cache = {"node_type": {}, "token": {}}
def ids(self, table, strings):
c = self.cache[table]; new = [s for s in set(strings) if s not in c]
if new:
self.db.execute("BEGIN IMMEDIATE")
self.db.executemany(f"INSERT OR IGNORE INTO {table}(s) VALUES (?)", [(s,) for s in new])
for i in range(0, len(new), 900):
ch = new[i:i + 900]
for id_, s in self.db.execute(f"SELECT id, s FROM {table} WHERE s IN ({','.join('?' * len(ch))})", ch):
c[s] = id_
self.db.execute("COMMIT")
return c
def joern_batch(files, srcdir, frontend, wd, k, xmx, logf):
"""parse+export a list of file names (already in srcdir). returns (dict name->graph, status) ; status in ok/fail/timeout"""
run_dir = wd / f"run{time.time_ns()}"; (run_dir / "src").mkdir(parents=True)
if frontend == "rust": # rust2cpg needs a cargo crate; every sample is a module of src/lib.rs
(run_dir / "src" / "src").mkdir()
(run_dir / "src" / "Cargo.toml").write_text('[package]\nname = "w"\nversion = "0.1.0"\nedition = "2021"\n')
(run_dir / "src" / "src" / "lib.rs").write_text("".join(f"#[allow(unused)] mod {f.rsplit('.', 1)[0]};\n" for f in files))
for f in files: os.link(srcdir / f, run_dir / "src" / "src" / f)
else:
for f in files: os.link(srcdir / f, run_dir / "src" / f)
env = dict(os.environ, JAVA_OPTS=f"-Xmx{xmx}")
n = len(files); m = {"n": n}
tmo = 120 + 0.5 * n + (240 if n <= 2 else 0)
rc, to, dt, rss = run([str(JOERN / "joern-parse"), str(run_dir / "src"), "-o", str(run_dir / "cpg.bin"), "--language", frontend],
tmo, env, logf, cwd=run_dir)
m.update(parse_s=dt, parse_rss=rss)
if to or rc != 0 or not (run_dir / "cpg.bin").exists():
shutil.rmtree(run_dir, ignore_errors=True); return None, ("timeout" if to else "parse_failed"), m
rc, to, dt, rss = run([str(JOERN / "joern"), "--script", str(EXPORT), "--param", f"cpgFile={run_dir/'cpg.bin'}",
"--param", f"outFile={run_dir/'out.jsonl'}"], tmo * 2, env, logf, cwd=run_dir)
m.update(export_s=dt, export_rss=rss, cpg_mb=(run_dir / "cpg.bin").stat().st_size / 2**20)
if to or rc != 0 or not (run_dir / "out.jsonl").exists():
shutil.rmtree(run_dir, ignore_errors=True); return None, ("timeout" if to else "export_failed"), m
out = {}
with open(run_dir / "out.jsonl") as fh:
for line in fh:
g = json.loads(line); out[os.path.basename(g["f"])] = g
shutil.rmtree(run_dir, ignore_errors=True)
return out, "ok", m
def process(files, srcdir, frontend, wd, k, xmx, logf, results, status, metrics, depth=0):
out, st, m = joern_batch(files, srcdir, frontend, wd, k, xmx, logf)
metrics.append(dict(m, status=st, depth=depth))
if st == "ok":
for f in files:
if f in out: results[f] = out[f]
else: status[f] = ("no_graph", "")
return
if depth == 0 and m.get("parse_s", 99) < 8 and m.get("export_s", 99) < 8:
raise SystemExit(f"joern failed in <8s on a whole batch ({st}) - environment problem, see joern log")
if len(files) == 1:
status[files[0]] = ("timeout" if st == "timeout" else "parse_failed", st); return
h = len(files) // 2
log(k, f" {st} on {len(files)} files -> bisect")
process(files[:h], srcdir, frontend, wd, k, xmx, logf, results, status, metrics, depth + 1)
process(files[h:], srcdir, frontend, wd, k, xmx, logf, results, status, metrics, depth + 1)
NODE_T = pa.struct([("idx", pa.int32()), ("type", pa.int16()), ("token", pa.int32()), ("line", pa.int32())])
def encode(rows, results, offsets, vocab):
"""rows: list of plan dicts with fname. returns pyarrow table of code_graph rows"""
labs, toks = set(), set()
for g in results.values():
for n in g["n"]: labs.add(n[0]); toks.add(n[1])
lid = vocab.ids("node_type", labs); tid = vocab.ids("token", toks)
cols = {k: [] for k in ("sample_id", "repr", "frontend", "priority_group", "language", "split", "num_nodes", "num_edges")}
n_off, e_off = [0], [0]; NI, NT, NK, NL, EF = [], [], [], [], []
for r in rows:
g = results.get(r["fname"])
if g is None: continue
nodes = g["n"]; N = len(nodes); A = g.get("a", N)
typ = np.array([lid[x[0]] for x in nodes], dtype=np.int16)
tok = np.array([tid[x[1]] for x in nodes], dtype=np.int32)
ln = np.array([x[2] for x in nodes], dtype=np.int32)
off = offsets[r["fname"]]
ln = np.where(ln >= 0, ln - off, -1).astype(np.int32)
E = np.array([[e[0], e[1], ETYPE[e[2]]] for e in g["e"]], dtype=np.int32).reshape(-1, 3)
is_method = (typ == lid.get("METHOD", -999)); is_method[A:] = False
meth_idx = np.nonzero(is_method)[0]
for rep, ets in REPRS:
es = E[np.isin(E[:, 2], ets)]
if rep == "AST": keep = np.arange(A)
else:
keep = np.unique(np.concatenate([es[:, 0], es[:, 1], meth_idx if rep != "CALL" or len(es) else meth_idx]))
remap = np.full(N, -1, dtype=np.int64); remap[keep] = np.arange(len(keep))
loc = np.stack([remap[es[:, 0]], remap[es[:, 1]], es[:, 2]], axis=1).astype(np.int32) if len(es) else np.zeros((0, 3), np.int32)
NI.append(keep.astype(np.int32)); NT.append(typ[keep]); NK.append(tok[keep]); NL.append(ln[keep]); EF.append(loc.ravel())
n_off.append(n_off[-1] + len(keep)); e_off.append(e_off[-1] + len(loc))
for c, v in (("sample_id", r["sample_id"]), ("repr", rep), ("frontend", r["frontend"]), ("priority_group", r["priority_group"]),
("language", r["language"]), ("split", r["split"]), ("num_nodes", len(keep)), ("num_edges", len(loc))):
cols[c].append(v)
if not cols["sample_id"]: return None
cat = lambda L, dt: np.concatenate(L).astype(dt) if L else np.zeros(0, dt)
st = pa.StructArray.from_arrays([pa.array(cat(NI, np.int32)), pa.array(cat(NT, np.int16)), pa.array(cat(NK, np.int32)), pa.array(cat(NL, np.int32))], fields=list(NODE_T))
nodes = pa.ListArray.from_arrays(pa.array(n_off, pa.int32()), st)
edges = pa.ListArray.from_arrays(pa.array(e_off, pa.int32()), pa.FixedSizeListArray.from_arrays(pa.array(cat(EF, np.int32)), 3))
n = len(cols["sample_id"])
return pa.table({"sample_id": pa.array(cols["sample_id"], pa.string()), "repr": pa.array(cols["repr"], pa.string()),
"tool": pa.array(["joern"] * n), "tool_version": pa.array([TOOL_VERSION] * n),
"frontend": pa.array(cols["frontend"]), "priority_group": pa.array(cols["priority_group"]),
"num_nodes": pa.array(cols["num_nodes"], pa.int32()), "num_edges": pa.array(cols["num_edges"], pa.int32()),
"nodes": nodes, "edges": edges, "graph_blob_uri": pa.nulls(n, pa.string()),
"language": pa.array(cols["language"]), "split": pa.array(cols["split"])})
def claim(bid):
p = W / "claim" / f"b{bid}"
try:
fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY); os.write(fd, str(os.getpid()).encode()); os.close(fd); return True
except FileExistsError: return False
def release_stale():
for p in (W / "claim").iterdir():
try: pid = int(p.read_text() or 0)
except Exception: pid = 0
if not pid or not Path(f"/proc/{pid}").exists(): p.unlink(missing_ok=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--worker", type=int, default=0); ap.add_argument("--xmx", default="3g")
ap.add_argument("--pilot-only", action="store_true"); ap.add_argument("--max-batch", type=int, default=10**9)
ap.add_argument("--stop-file", default=str(W / "STOP"))
a = ap.parse_args(); k = a.worker
for d in ("done", "claim", "batches", "status", "tmp"): (W / d).mkdir(parents=True, exist_ok=True)
release_stale()
meta = pq.read_table(W / "plan.parquet", columns=["batch_id", "pilot", "frontend"]).to_pandas()
meta = meta[meta.batch_id >= 0]
bids = sorted(set(meta[meta.pilot].batch_id) if a.pilot_only else set(meta.batch_id))
vocab = Vocab(str(W / "vocab.sqlite"))
logf = ROOT / f"logs/graphs/joern_w{k}.log"
for bid in bids:
if bid > a.max_batch or Path(a.stop_file).exists(): break
if (W / "done" / f"b{bid}.json").exists() or not claim(bid): continue
t0 = time.time()
tb = pq.read_table(W / "plan.parquet", filters=[("batch_id", "=", int(bid))],
columns=["sample_id", "language", "language_detail", "split", "frontend", "priority_group", "code", "pilot"])
rows = tb.to_pylist(); del tb
wd = W / "tmp" / f"b{bid}"; shutil.rmtree(wd, ignore_errors=True); src = wd / "src"; src.mkdir(parents=True)
offsets = {}
for i, r in enumerate(rows):
text, off = wrap(r["language_detail"], r["code"] or "")
r["fname"] = f"s{i}{EXT.get(r['language_detail'], '.txt')}"; offsets[r["fname"]] = off
(src / r["fname"]).write_text(text, encoding="utf-8", errors="surrogatepass")
r["code"] = None
frontend = rows[0]["frontend"]
results, status, metrics = {}, {}, []
process([r["fname"] for r in rows], src, frontend, wd, k, a.xmx, logf, results, status, metrics)
if frontend == "c": # dataset language labels mix C and C++: retry no-graph files with the other dialect
retry = {}
for f, (st_, _) in list(status.items()):
if st_ == "no_graph":
alt = f.rsplit(".", 1)[0] + (".c" if f.endswith(".cpp") else ".cpp")
os.replace(src / f, src / alt); retry[alt] = f
if retry:
res2, st2 = {}, {}
process(sorted(retry), src, frontend, wd, k, a.xmx, logf, res2, st2, metrics, depth=1)
for alt, g in res2.items():
results[retry[alt]] = g; status.pop(retry[alt], None)
for alt, (s2, e2) in st2.items():
if s2 != "no_graph": status[retry[alt]] = (s2, "retry:" + e2)
t1 = time.time()
tbl = encode(rows, results, offsets, vocab)
out_bytes = 0
if tbl is not None:
tmp = W / "batches" / f".b{bid}.parquet"
pq.write_table(tbl, tmp, compression="zstd", compression_level=6)
out_bytes = tmp.stat().st_size; os.replace(tmp, W / "batches" / f"b{bid}.parquet")
el = time.time() - t0
stt = pa.table({"sample_id": [r["sample_id"] for r in rows], "language": [r["language"] for r in rows],
"split": [r["split"] for r in rows], "priority_group": [r["priority_group"] for r in rows],
"frontend": [r["frontend"] for r in rows], "pilot": [r["pilot"] for r in rows],
"status": [("ok" if r["fname"] in results else status.get(r["fname"], ("no_graph", ""))[0]) for r in rows],
"error": [status.get(r["fname"], ("", ""))[1] for r in rows],
"num_nodes": pa.array([len(results[r["fname"]]["n"]) if r["fname"] in results else 0 for r in rows], pa.int32()),
"batch_id": pa.array([int(bid)] * len(rows), pa.int32()),
"batch_seconds_per_fn": pa.array([el / len(rows)] * len(rows), pa.float32())})
tmp = W / "status" / f".b{bid}.parquet"; pq.write_table(tmp_t := stt, tmp, compression="zstd"); os.replace(tmp, W / "status" / f"b{bid}.parquet")
nok = len(results)
rec = dict(batch=int(bid), worker=k, frontend=frontend, n=len(rows), ok=nok, seconds=round(el, 1), joern_s=round(t1 - t0, 1),
out_bytes=out_bytes, peak_rss_mb=round(max([max(m.get("parse_rss", 0), m.get("export_rss", 0)) for m in metrics]), 0),
runs=len(metrics), statuses={s: list(stt.column("status").to_pylist()).count(s) for s in set(stt.column("status").to_pylist())},
first=metrics[0], ts=time.time())
(W / "done" / f"b{bid}.json").write_text(json.dumps(rec))
with open(W / "metrics.jsonl", "a") as fh: fh.write(json.dumps(rec) + "\n")
shutil.rmtree(wd, ignore_errors=True); (W / "claim" / f"b{bid}").unlink(missing_ok=True)
log(k, f"b{bid} {frontend} n={len(rows)} ok={nok} {el:.0f}s ({len(rows)/el:.1f} fn/s) rss={rec['peak_rss_mb']}MB out={out_bytes/2**20:.1f}MB runs={len(metrics)}")
log(k, "worker exit")
if __name__ == "__main__":
main()

Xet Storage Details

Size:
16.9 kB
·
Xet hash:
f0cd959b72d629b65b3fcc71f466f246ba23aaf7213b8169f98daab7c2bc664a

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.