Repository navigation
farm: small robustness fixes from the farm review (M1, M3, M6, L items) #85
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
36e8ea6
6c8185c
0846a33
9609d7d
46a01d4
e3c6489
ba6c5e8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -64,6 +64,7 @@ ADB_READ_FAILED = "adb-read-failed" | |
|
|
||
|
|
||
| class Farm: | ||
| dst_lock = threading.RLock() # set_dstate is called from workers and the tick (class level: tests build Farm without __init__) | ||
| def __init__(self, fake, once, poll): | ||
| self.fake, self.once, self.poll = fake, once, poll | ||
| self.cfg, self.devs = L.load_devices() | ||
|
|
@@ -93,7 +94,7 @@ class Farm: | |
| self.sweeping, self.sweep_run, self.prebuild_t, self._cl = {}, set(), None, None | ||
| self.idle_since = {} # alias -> when it last stopped doing real (non-sweep) work or became healthy | ||
| self.last_auto = 0 | ||
| self.restore_pending = set() # phones whose last hold was cut short by a restart: restore before the next use | ||
| self.restore_pending = H.load_restore() # persisted (holdlib): survives further restarts; phones whose last hold was cut short by a restart: restore before the next use | ||
| self.menu_next = {} # alias -> next time to probe its MediaDeck versionCode | ||
|
|
||
| # ---------- devices | ||
|
|
@@ -160,14 +161,15 @@ class Farm: | |
| return "usb" if t == self.devs[alias]["serial"] else ("mdns" if t.startswith("adb-") else "wireless") if t else "" | ||
|
|
||
| def set_dstate(self, alias, status, note="", **extra): | ||
| cur = self.dstate.get(alias, {}) | ||
| if cur.get("status") != status: | ||
| keep = {k: cur[k] for k in ("batt", "temp_c", "thermal", "wireless") if k in cur} | ||
| self.dstate[alias] = dict(keep, status=status, since=time.time(), note=note, since_iso=L.now()) | ||
| else: | ||
| cur["note"] = note | ||
| self.dstate[alias].update(extra) | ||
| L.write_json(self.st_path, self.dstate) | ||
| with self.dst_lock: # workers and the tick call this concurrently: serialise mutation and dump | ||
| cur = self.dstate.get(alias, {}) | ||
| if cur.get("status") != status: | ||
| keep = {k: cur[k] for k in ("batt", "temp_c", "thermal", "wireless") if k in cur} | ||
| self.dstate[alias] = dict(keep, status=status, since=time.time(), note=note, since_iso=L.now()) | ||
| else: | ||
| cur["note"] = note | ||
| self.dstate[alias].update(extra) | ||
| L.write_json(self.st_path, json.loads(json.dumps(self.dstate))) | ||
|
|
||
| # ---------- health gates | ||
| def is_disabled(self, dev): | ||
|
|
@@ -1442,7 +1444,7 @@ class Farm: | |
| ok = rc == 0 and "PROBLEM" not in out and not ps.strip() | ||
| return ok, (note + (" STILL RUNNING" if ps.strip() else "") + ("" if rc == 0 and "PROBLEM" not in out else f" qrestore rc={rc}: {(out.strip().splitlines() or [''])[-1][:100]}")).strip() | ||
|
|
||
| def run_hold(self, hid, alias): | ||
| def run_hold(self, hid, alias, adopt=False): | ||
| dev = dict(self.devs[alias]) # a snapshot: devices.toml edits during the hold must not retarget the cleanup or the lock name | ||
| lock = L.PhoneLock(dev, self.fake) | ||
| h = L.read_json(H.path(hid)) | ||
|
|
@@ -1452,7 +1454,7 @@ class Farm: | |
| L.write_json(H.path(hid), h2) | ||
| log(f"{alias}: hold {hid} ended: {reason}" + (f" ({kw['clean_note']})" if kw.get("clean_note") else "")) | ||
| self.wake.set() | ||
| if H.released(hid) or H.age(hid) > H.HB_STALE: | ||
| if not adopt and (H.released(hid) or H.age(hid) > H.HB_STALE): | ||
| return done("cancelled while queued" if H.released(hid) else "caller lost while queued") | ||
| if self.is_disabled(dev): | ||
| self.cool[alias] = time.time() + (0 if self.fake else 30) | ||
|
|
@@ -1462,22 +1464,28 @@ class Farm: | |
| return | ||
| touched = False | ||
| try: | ||
| gs, gwhy, _ = self.gate_check(dev) | ||
| if gs != "ok": | ||
| log(f"{alias}: gated ({gs}: {gwhy}); hold {hid} stays queued") | ||
| self.cool[alias] = time.time() + (0 if self.fake else 60) | ||
| return | ||
| h = L.read_json(H.path(hid)) | ||
| if H.released(hid) or H.age(hid) > H.HB_STALE or self.is_disabled(dev): # cancelled while the gate was being read | ||
| return done("cancelled while queued" if H.released(hid) else "caller lost or phone disabled while queued") | ||
| if alias in self.restore_pending: # a hold was cut short by a farmd restart: the phone may still be in its state | ||
| self.hold_cleanup(dev) | ||
| self.restore_pending.discard(alias) | ||
| touched = True | ||
| now = time.time() | ||
| h.update(state="active", started=L.now(), deadline=now + h["max_s"], lock=dev["lock"], serial=self.tid.get(alias) or dev["serial"]) | ||
| L.write_json(H.path(hid), h) | ||
| log(f"{alias}: hold {hid} active (max {h['max_s']}s, waited {int(now - h['seq'] / 1e9)}s)") | ||
| if adopt: # M4: farmd restarted under a live hold; its caller's command still runs on the phone | ||
| touched = True | ||
| h = L.read_json(H.path(hid)) | ||
| log(f"{alias}: hold {hid} re-adopted after a farmd restart (deadline in {int(h.get('deadline', 0) - time.time())}s)") | ||
| else: | ||
| gs, gwhy, _ = self.gate_check(dev) | ||
| if gs != "ok": | ||
| log(f"{alias}: gated ({gs}: {gwhy}); hold {hid} stays queued") | ||
| self.cool[alias] = time.time() + (0 if self.fake else 60) | ||
| return | ||
| h = L.read_json(H.path(hid)) | ||
| if H.released(hid) or H.age(hid) > H.HB_STALE or self.is_disabled(dev): # cancelled while the gate was being read | ||
| return done("cancelled while queued" if H.released(hid) else "caller lost or phone disabled while queued") | ||
| if alias in self.restore_pending: # a hold was cut short by a farmd restart: the phone may still be in its state | ||
| self.hold_cleanup(dev) | ||
| self.restore_pending.discard(alias) | ||
| H.clear_restore(alias) | ||
| touched = True | ||
| now = time.time() | ||
| h.update(state="active", started=L.now(), deadline=now + h["max_s"], lock=dev["lock"], serial=self.tid.get(alias) or dev["serial"]) | ||
| L.write_json(H.path(hid), h) | ||
| log(f"{alias}: hold {hid} active (max {h['max_s']}s, waited {int(now - h['seq'] / 1e9)}s)") | ||
| while True: | ||
| why = H.end_reason(h, H.age(hid), H.released(hid), disabled=self.is_disabled(dev)) | ||
| if why: | ||
|
|
@@ -1493,6 +1501,8 @@ class Farm: | |
| done(why, clean=clean, clean_note=note) | ||
| except Exception: | ||
| log(f"{alias}: hold {hid} error: " + traceback.format_exc()[-300:]) | ||
| if not touched: | ||
| self.cool[alias] = time.time() + (0 if self.fake else 30) # do not re-tick and retry at full speed | ||
| if touched: | ||
| try: | ||
| clean, note = (False, "restore deferred: disabled by owner") if self.is_disabled(dev) else self.hold_cleanup(dev) | ||
|
|
@@ -1553,6 +1563,7 @@ class Farm: | |
| if alias in self.restore_pending and not menu: # an earlier hold was cut short by a farmd restart | ||
| self.hold_cleanup(dev) | ||
| self.restore_pending.discard(alias) | ||
| H.clear_restore(alias) | ||
| touched = not menu # menubench restores the phone itself | ||
| self.upd(jid, lambda x: x["parts"][cls].update(state="running", device=alias)) | ||
| sha, why = self.build(job) | ||
|
|
@@ -1566,7 +1577,7 @@ class Farm: | |
| and "(fake)" not in res.get("notes", "") and not self.is_disabled(dev)): | ||
| log(f"{alias}: {jid}/{cls} driver sha mismatch ({res.get('notes', '')[:80]}); re-pushing and retrying once inside the hold") | ||
| res = getattr(self, "suite_" + job["suite"])(job, dev) # shellroute pushes + verifies afresh; still invalid -> normal requeue | ||
| if res.get("lost") or (self.fake is False and alias not in self.attached() and res["verdict"] != "pass"): | ||
| if res.get("lost") or (self.fake is False and alias not in self.attached() and res.get("verdict") != "pass"): | ||
| res = None # phone vanished mid-run: do not blame the commit, retry later | ||
| except Exception: | ||
| res = {"verdict": "error", "notes": "farmd exception: " + traceback.format_exc()[-300:]} | ||
|
|
@@ -2008,15 +2019,35 @@ class Farm: | |
| self.threads = {a: t for a, t in self.threads.items() if t.is_alive()} | ||
| for h in H.list_holds(): # farmd restarted mid-hold: its lock died with it | ||
| if h["state"] == "active" and not any(t.name == "hold/" + h["device"] for t in self.threads.values()): | ||
| al = h["device"] | ||
| if (al in self.devs and al not in self.threads and not H.released(h["id"]) and H.age(h["id"]) <= H.HB_STALE | ||
| and time.time() < h.get("deadline", 0) and not self.is_disabled(self.devs[al])): | ||
| t = threading.Thread(target=self.run_hold, args=(h["id"], al, True), name=f"hold/{al}", daemon=False) # M4: re-adopt the live hold | ||
| self.threads[al] = t | ||
| t.start() | ||
| continue | ||
| h.update(state="done", ended=L.now(), reason="farmd restarted", clean=False, clean_note="restore runs before the next job or hold") | ||
| L.write_json(H.path(h["id"]), h) | ||
| self.restore_pending.add(h["device"]) | ||
| H.mark_restore(h["device"]) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Create the restore marker before changing the recovered record. The hold path writes Create the marker first. If recovery stops after that operation, the next daemon can still discover the required restoration. Also applies to: 1917-1917
|
||
| H.gc() | ||
| for j in B.order_jobs(jobs): # explicit jobs first, auto bench after them (sweep is last: real_pending) | ||
| for cls, p in j["parts"].items(): | ||
| if p["state"] == "running" and not any(t.name.startswith(j["id"] + "/" + cls) for t in self.threads.values()): | ||
| self.part_set(j["id"], cls, state="pending") # farmd restarted mid-run | ||
| p["state"] = "pending" | ||
| def recover_interrupted_part(job): | ||
| part = job["parts"][cls] | ||
| if part["state"] != "running" or part.get("verdict") in self.TERMINAL_VERDICTS: | ||
| return | ||
| alias = part.get("device") | ||
| if job["suite"] != "menu" and alias: | ||
| H.mark_restore(alias) | ||
| self.restore_pending.add(alias) | ||
| part["attempts"] = part.get("attempts", 0) + 1 | ||
| if part["attempts"] < RETRIES: | ||
| part["state"] = "pending" | ||
| else: | ||
| part.update(state="done", verdict="error") | ||
| p.update(self.upd(j["id"], recover_interrupted_part)["parts"][cls]) | ||
| if p["state"] != "pending": | ||
| continue | ||
| if j["suite"] == "menu" and self.menu_stale(j): | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Re-adopted holds must keep the recorded phone and lock.
After a farmd restart, the adopt branch of
run_holdbuilds its lock and cleanup target from the currentdevices.tomlmapping. It does not compare that mapping with the hold record.reload_devicesallowslockandserialto change in the live table without any check for active holds. The hold's caller still runs its command on the recorded phone with the recorded lock name, as set infarm:236-238. If the alias now maps to a different phone, farmd can lock and clean up the wrong phone while the caller's command keeps running on the original phone without farmd's lock.Adoption must act only on the phone and lock recorded in the hold. When the current lock name differs from
h["lock"], or the current phone differs from the recorded phone, the adopted hold must end without cleanup and log the mismatch. Compare the lock name directly. The recordedserialcan be a transport ID rather than a bare serial, so resolve it against the live transport before comparing it with the configured serial.