Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions tools/farm/farmd
Original file line number Diff line number Diff line change
Expand Up @@ -1445,13 +1445,14 @@ class Farm:
self.cool[alias] = time.time() + (0 if self.fake else 20)
return
t0, started = time.time(), L.now()
job = L.read_json(L.job_path(jid))
job = None
res, h0, touched = None, {}, False
self.stop_reason.pop(alias, None)
if not hasattr(self, "running_job"):
self.running_job = {}
self.running_job[alias] = jid
try:
job = L.read_json(L.job_path(jid)) # inside the try: a read error must still release the lock
gs, gwhy, h0 = self.gate_check(dev, starting=True)
if gs != "ok":
log(f"{alias}: gated ({gs}: {gwhy}); {jid}/{cls} stays pending")
Expand Down Expand Up @@ -1499,7 +1500,12 @@ class Farm:
return
why_stop = self.stop_reason.pop(alias, None)
if res is None and why_stop == "cancelled":
self.upd(jid, lambda x: x["parts"][cls].update(state="cancelled"))
j = self.upd(jid, lambda x: x["parts"][cls].update(state="cancelled"))
if not any(p.get("state") == "running" for p in (j or {}).get("parts", {}).values()):
try: # else a requeued part of this job would be stopped at once
os.unlink(os.path.join(L.state_dir(), "cancel", jid))
except OSError:
pass
log(f"{alias}: {jid}/{cls} cancelled by the owner; lock released")
return
if res is None and why_stop: # owner policy (charger removed / disabled): clean stop, no blame, no retry count
Expand Down
54 changes: 35 additions & 19 deletions tools/farm/farmlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,26 +127,35 @@ def run_watched(cmd, timeout, alive, grace=45, poll=5, **kw):
th.start()
t0, lost = time.time(), None
rc = None
while rc is None:
try:
rc = p.wait(poll)
except subprocess.TimeoutExpired:
if time.time() - t0 > timeout:
rc = 124
elif (st := alive()) == "stop":
rc = 125
elif st:
lost = None
else:
lost = lost or time.time()
if time.time() - lost > grace:
try:
while rc is None:
try:
rc = p.wait(poll)
except subprocess.TimeoutExpired:
if time.time() - t0 > timeout:
rc = 124
elif (st := alive()) == "stop":
rc = 125
if rc in (124, 125):
try:
os.killpg(p.pid, signal.SIGKILL)
except OSError:
pass
p.wait()
elif st:
lost = None
else:
lost = lost or time.time()
if time.time() - lost > grace:
rc = 125
if rc in (124, 125):
try:
os.killpg(p.pid, signal.SIGKILL)
except OSError:
pass
p.wait()
except BaseException:
# alive() (or anything in the loop) raised: never leave the child group driving the phone
try:
os.killpg(p.pid, signal.SIGKILL)
except OSError:
pass
p.wait()
raise
th.join(5)
txt = (out[0] if out else b"").decode(errors="replace")
return rc, txt + ("\nDEVICE-LOST" if rc == 125 else "\nTIMEOUT" if rc == 124 else "")
Expand All @@ -157,6 +166,12 @@ def store_route(alias, addr, path=None):
`ip:5555` entry in `wireless`/`address` is replaced, other routes (other ports) stay, none yet -> a `wireless` line is added.
Text edit (comments and other entries untouched), atomic. -> True if the file changed."""
path = path or devices_path()
with open(path + ".lock", "a") as lk: # serialize the read-modify-write between writers (farmd threads, farm CLI)
fcntl.flock(lk, fcntl.LOCK_EX)
return _store_route(alias, addr, path)


def _store_route(alias, addr, path):
lines = open(path).read().split("\n")
start = next((i for i, l in enumerate(lines) if re.match(r'\s*alias\s*=\s*"%s"' % re.escape(alias), l)), None)
if start is None:
Expand Down Expand Up @@ -192,6 +207,7 @@ def store_route(alias, addr, path=None):
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-")
with os.fdopen(fd, "w") as f:
f.write("\n".join(lines))
os.chmod(tmp, os.stat(path).st_mode & 0o7777) # mkstemp is 0600: keep the file's own mode
os.replace(tmp, path)
return True

Expand Down
69 changes: 68 additions & 1 deletion tools/farm/test_farm.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ def farm(self, *a):
return r.returncode, r.stdout.strip(), r.stderr

def farmd(self):
r = subprocess.run([sys.executable, HERE + "/farmd", "--fake", "--once"], capture_output=True, text=True, env=self.env, timeout=60)
r = subprocess.run([sys.executable, HERE + "/farmd", "--fake", "--once"], capture_output=True, text=True, env=self.env, timeout=240)
self.assertEqual(r.returncode, 0, r.stderr)
return r.stdout

Expand Down Expand Up @@ -668,6 +668,73 @@ def test_store_route_idempotent(self):
self.assertIn("# keep", open(p).read())
self.assertFalse(L.store_route("dev-c", "198.51.100.22:5555", p))

def test_store_route_keeps_file_mode(self):
p = self.d + "/devices.toml"
os.chmod(p, 0o644)
self.assertTrue(L.store_route("dev-b", "198.51.100.8:5555", p))
self.assertEqual(os.stat(p).st_mode & 0o777, 0o644) # mkstemp's 0600 must not leak through

def test_run_watched_kills_the_group_when_alive_raises(self):
pidf = self.d + "/child.pid"
def boom():
raise RuntimeError("alive broke")
with self.assertRaises(RuntimeError):
L.run_watched(["sh", "-c", "echo $$ > %s; exec sleep 60" % pidf], 100, boom, poll=0.5)
pid = int(open(pidf).read())
time.sleep(0.3)
self.assertFalse(os.path.exists("/proc/%d" % pid) and "sleep" in open("/proc/%d/cmdline" % pid).read())

def test_run_part_read_error_releases_the_phone_lock(self):
import importlib.machinery, importlib.util, threading
ld = importlib.machinery.SourceFileLoader("farmd_rp", HERE + "/farmd")
fd = importlib.util.module_from_spec(importlib.util.spec_from_loader("farmd_rp", ld))
ld.exec_module(fd)
f = object.__new__(fd.Farm)
dev = {"alias": "dev-a", "class": "v11", "serial": "S", "lock": "cmf"}
f.fake, f.devs, f.cool, f.stop_reason, f.jl = True, {"dev-a": dev}, {}, {}, threading.Lock()
f.is_disabled = lambda d: False
L.write_json(L.job_path("jx"), {"id": "jx", "suite": "smoke", "parts": {"v11": {"state": "pending"}}})
real, n = L.read_json, [0]
def flaky(path):
if path == L.job_path("jx") and n[0] >= 1:
raise ValueError("torn json")
n[0] += 1
return real(path)
L.read_json = flaky
self.addCleanup(setattr, L, "read_json", real)
err = None
try:
f._run_part("jx", "v11", "dev-a")
except Exception as e:
err = e # keeps the traceback (and so any leaked lock fd) alive
L.read_json = real
self.assertIsNotNone(err)
lk = L.PhoneLock(dev, True)
self.assertTrue(lk.acquire(), "lock leaked by _run_part")
lk.release()

def test_cancelled_part_removes_the_cancel_marker(self):
import importlib.machinery, importlib.util, threading
ld = importlib.machinery.SourceFileLoader("farmd_cm", HERE + "/farmd")
fd = importlib.util.module_from_spec(importlib.util.spec_from_loader("farmd_cm", ld))
ld.exec_module(fd)
f = object.__new__(fd.Farm)
dev = {"alias": "dev-a", "class": "v11", "serial": "S", "lock": "cmf"}
f.fake, f.devs, f.cool, f.stop_reason, f.jl, f.restore_pending = True, {"dev-a": dev}, {}, {}, threading.Lock(), set()
f.is_disabled = lambda d: False
f.gate_check = lambda d, starting=False: ("ok", "", {})
f.preflight = lambda d: (True, "")
f.build = lambda job: ("sha", "")
f.qrestore = lambda d: None
f.suite_smoke = lambda job, d: (f.stop_reason.update({"dev-a": "cancelled"}), {"lost": True})[1] # owner cancelled mid-run
L.write_json(L.job_path("jc"), {"id": "jc", "suite": "smoke", "parts": {"v11": {"state": "pending", "attempts": 0}}})
os.makedirs(self.d + "/state/cancel", exist_ok=True)
marker = self.d + "/state/cancel/jc"
open(marker, "w").close()
f._run_part("jc", "v11", "dev-a")
self.assertEqual(L.read_json(L.job_path("jc"))["parts"]["v11"]["state"], "cancelled")
self.assertFalse(os.path.exists(marker))

def test_unreachable_stored_route_is_a_soft_miss(self):
calls = []
L._ROUTE_MISS.clear()
Expand Down