493 lines
20 KiB
Python
493 lines
20 KiB
Python
"""Durable tracker-maintenance intents; bounded attempts belong to Commands.
|
|
|
|
An outage ends an attempt, not its owning intent. No downstream output action
|
|
is admitted here. State changes reconcile the actual B2 image before retrying.
|
|
"""
|
|
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import threading
|
|
import time
|
|
import uuid
|
|
|
|
from . import actions, full_configuration, sim_selection
|
|
|
|
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"}
|
|
PENDING = {"queued", "dispatched"}
|
|
RETRY = {"expired", "unconfirmed", "uncertain", "not_applied"}
|
|
FACTS = {
|
|
"transport",
|
|
"stage",
|
|
"dispatched_at",
|
|
"received_at",
|
|
"device_accepted_at",
|
|
"device_code",
|
|
"roundtrip_seconds",
|
|
"reconnected_at",
|
|
"reconnect_seconds",
|
|
"verified_at",
|
|
"configuration",
|
|
"configuration_sha256",
|
|
"configuration_received_at",
|
|
"write_reply_sent_at",
|
|
"active_sim",
|
|
"telemetry_measured_at",
|
|
"unchanged",
|
|
"sim_guard_verified",
|
|
}
|
|
|
|
|
|
class Operations:
|
|
def __init__(self, store, commands):
|
|
self.store, self.commands = store, commands
|
|
# Only local SQLite work under this lock; never sockets, sleeps or device I/O.
|
|
self.lock = threading.RLock()
|
|
with store.db() as db:
|
|
db.executescript("""
|
|
CREATE TABLE IF NOT EXISTS operations(
|
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,
|
|
imei TEXT NOT NULL,state TEXT NOT NULL,digest TEXT NOT NULL,body TEXT NOT NULL);
|
|
CREATE INDEX IF NOT EXISTS operations_pending ON operations(imei,state,seq);
|
|
CREATE TABLE IF NOT EXISTS operation_attempts(
|
|
operation TEXT NOT NULL,number INTEGER NOT NULL,id TEXT UNIQUE NOT NULL,
|
|
body TEXT NOT NULL,PRIMARY KEY(operation,number));
|
|
CREATE TABLE IF NOT EXISTS operation_modem(
|
|
imei TEXT PRIMARY KEY,body TEXT NOT NULL);
|
|
CREATE TABLE IF NOT EXISTS operation_stops(id TEXT PRIMARY KEY,kind TEXT NOT NULL);
|
|
""")
|
|
|
|
def save(self, value):
|
|
with self.store.db() as db:
|
|
encoded = json.dumps(value)
|
|
db.execute(
|
|
"UPDATE operations SET state=?,body=? WHERE id=? AND body<>?",
|
|
(value["state"], encoded, value["id"], encoded),
|
|
)
|
|
|
|
def submit(self, body):
|
|
body = dict(body)
|
|
if (
|
|
not re.fullmatch(r"[a-f0-9]{32}", body.get("id", ""))
|
|
or body.get("kind") not in KINDS
|
|
or not self.store.admitted(body.get("imei"))
|
|
):
|
|
raise ValueError("unsupported operation")
|
|
if body["kind"] in full_configuration.KINDS:
|
|
if not re.fullmatch(r"[0-9]{6}", body.get("password", "")):
|
|
raise ValueError("invalid password")
|
|
full_configuration.prepare(body)
|
|
else:
|
|
actions.prepare(body)
|
|
digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
|
|
with self.lock, self.store.db() as db:
|
|
db.execute("BEGIN IMMEDIATE")
|
|
stopped = db.execute(
|
|
"SELECT kind FROM operation_stops WHERE id=?", (body["id"],)
|
|
).fetchone()
|
|
if stopped:
|
|
return {
|
|
"id": body["id"],
|
|
"kind": stopped[0],
|
|
"state": "stopped",
|
|
"durable": True,
|
|
"runtime_phase": "stopped",
|
|
"stop_requested": True,
|
|
"attempt_count": 0,
|
|
}
|
|
old = db.execute(
|
|
"SELECT digest,body FROM operations WHERE id=?", (body["id"],)
|
|
).fetchone()
|
|
if old:
|
|
if old[0] != digest:
|
|
raise ValueError("idempotency conflict")
|
|
return self.public(json.loads(old[1]))
|
|
count = db.execute(
|
|
"SELECT count(*) FROM operations WHERE imei=? AND state IN ('queued','dispatched')",
|
|
(body["imei"],),
|
|
).fetchone()[0]
|
|
if count >= 32:
|
|
raise ValueError("operation queue full")
|
|
value = {
|
|
"id": body["id"],
|
|
"imei": body["imei"],
|
|
"kind": body["kind"],
|
|
"request": body,
|
|
"created_at": time.time(),
|
|
"state": "queued",
|
|
"runtime_phase": "waiting-link",
|
|
"attempt_count": 0,
|
|
"next_attempt_at": 0,
|
|
"phase": "execute",
|
|
"result": {},
|
|
}
|
|
db.execute(
|
|
"INSERT INTO operations(id,imei,state,digest,body) VALUES(?,?,?,?,?)",
|
|
(body["id"], body["imei"], value["state"], digest, json.dumps(value)),
|
|
)
|
|
return self.public(value)
|
|
|
|
@staticmethod
|
|
def public(value):
|
|
result = {k: v for k, v in value.get("result", {}).items() if k in FACTS}
|
|
result.update(
|
|
{
|
|
k: value[k]
|
|
for k in (
|
|
"id",
|
|
"kind",
|
|
"state",
|
|
"created_at",
|
|
"attempt_count",
|
|
"runtime_phase",
|
|
"next_attempt_at",
|
|
"stop_requested",
|
|
"reason",
|
|
)
|
|
if k in value
|
|
}
|
|
)
|
|
result["durable"] = True
|
|
if value.get("attempt"):
|
|
result["attempt_id"] = value["attempt"]["id"]
|
|
result["attempt_expires_at"] = value["attempt"]["not_after"]
|
|
return result
|
|
|
|
def pending(self, imei):
|
|
with self.store.db() as db:
|
|
return (
|
|
db.execute(
|
|
"SELECT 1 FROM operations WHERE imei=? AND state IN "
|
|
"('queued','dispatched') LIMIT 1",
|
|
(imei,),
|
|
).fetchone()
|
|
is not None
|
|
)
|
|
|
|
def fresh(self, imei):
|
|
return any(
|
|
0 <= time.monotonic() - self.commands.session_activity.get((imei, s), 0) <= 30
|
|
for s in tuple(self.commands.sessions.get(imei, ()))
|
|
)
|
|
|
|
def wait_delay(self, imei):
|
|
with self.store.db() as db:
|
|
row = db.execute(
|
|
"SELECT body FROM operations WHERE imei=? AND state IN "
|
|
"('queued','dispatched') ORDER BY seq LIMIT 1",
|
|
(imei,),
|
|
).fetchone()
|
|
if not row:
|
|
return None
|
|
value = json.loads(row[0])
|
|
if value.get("attempt"):
|
|
return 1
|
|
return max(1, value["next_attempt_at"] - time.time()) if self.fresh(imei) else None
|
|
|
|
def get(self, identifier):
|
|
with self.store.db() as db:
|
|
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
|
|
if not row:
|
|
with self.store.db() as db:
|
|
stopped = db.execute(
|
|
"SELECT kind FROM operation_stops WHERE id=?", (identifier,)
|
|
).fetchone()
|
|
if stopped:
|
|
return {
|
|
"id": identifier,
|
|
"kind": stopped[0],
|
|
"state": "stopped",
|
|
"durable": True,
|
|
"runtime_phase": "stopped",
|
|
"stop_requested": True,
|
|
"attempt_count": 0,
|
|
}
|
|
raise ValueError("unknown operation")
|
|
self.advance(json.loads(row[0])["imei"])
|
|
with self.store.db() as db:
|
|
value = json.loads(
|
|
db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()[0]
|
|
)
|
|
result = self.public(value)
|
|
attempt = value.get("attempt", value.get("result", {})).get("id")
|
|
if attempt:
|
|
result["transport"] = self.commands.transport.read(db, attempt)
|
|
return result
|
|
|
|
def cancel(self, identifier, kind=None):
|
|
if not re.fullmatch(r"[a-f0-9]{32}", identifier):
|
|
raise ValueError("invalid operation identity")
|
|
with self.lock, self.store.db() as db:
|
|
db.execute("BEGIN IMMEDIATE")
|
|
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
|
|
if not row:
|
|
if kind not in KINDS:
|
|
raise ValueError("unknown operation")
|
|
db.execute("INSERT OR IGNORE INTO operation_stops VALUES(?,?)", (identifier, kind))
|
|
return {
|
|
"id": identifier,
|
|
"kind": kind,
|
|
"state": "stopped",
|
|
"durable": True,
|
|
"runtime_phase": "stopped",
|
|
"stop_requested": True,
|
|
"attempt_count": 0,
|
|
}
|
|
value = json.loads(row[0])
|
|
if value["state"] in PENDING:
|
|
value["stop_requested"] = True
|
|
if not value.get("attempt"):
|
|
value.update(state="stopped", runtime_phase="stopped")
|
|
db.execute(
|
|
"UPDATE operations SET state=?,body=? WHERE id=?",
|
|
(value["state"], json.dumps(value), identifier),
|
|
)
|
|
return self.get(identifier)
|
|
|
|
def history(self, identifier, before=2**63 - 1):
|
|
with self.store.db() as db:
|
|
rows = db.execute(
|
|
"SELECT number,body FROM operation_attempts WHERE operation=? "
|
|
"AND number<? ORDER BY number DESC LIMIT 21",
|
|
(identifier, before),
|
|
).fetchall()
|
|
items = [json.loads(r[1]) for r in rows[:20]]
|
|
for item in items:
|
|
# Transport observations may be persisted just after the device
|
|
# reply already completed this attempt. Read their current facts.
|
|
item["transport"] = self.commands.transport.read(db, item["id"])
|
|
return {
|
|
"items": items,
|
|
"next_before": rows[19][0] if len(rows) > 20 else None,
|
|
}
|
|
|
|
def note_attempt(self, value, result):
|
|
item = {k: result[k] for k in FACTS - {"configuration"} if k in result}
|
|
item.update(
|
|
id=value["attempt"]["id"],
|
|
number=value["attempt_count"],
|
|
phase=value["phase"],
|
|
state=result["state"],
|
|
)
|
|
with self.store.db() as db:
|
|
old = db.execute(
|
|
"SELECT body FROM operation_attempts WHERE id=?", (item["id"],)
|
|
).fetchone()
|
|
if old:
|
|
previous = json.loads(old[0])
|
|
previous.pop("observed_at", None)
|
|
if previous == item:
|
|
return
|
|
item["observed_at"] = time.time()
|
|
db.execute(
|
|
"INSERT INTO operation_attempts VALUES(?,?,?,?) ON CONFLICT(operation,number) "
|
|
"DO UPDATE SET body=excluded.body",
|
|
(value["id"], value["attempt_count"], item["id"], json.dumps(item)),
|
|
)
|
|
|
|
def observe(self, imei, raw):
|
|
offset = 2
|
|
while offset < len(raw) - 1:
|
|
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
|
|
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
|
|
payload = raw[offset + 7 : offset + 7 + size]
|
|
if raw[offset] == 1 and 0 <= time.time() - measured <= 30:
|
|
for index in range(0, len(payload) - 4, 5):
|
|
if payload[index] != 99:
|
|
continue
|
|
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
|
|
value = {
|
|
"active_sim": 1 + ((ds2 >> 5) & 1),
|
|
"gprs": (ds2 >> 2) & 7,
|
|
"measured_at": measured,
|
|
}
|
|
with self.store.db() as db:
|
|
db.execute(
|
|
"INSERT INTO operation_modem VALUES(?,?) ON CONFLICT(imei) "
|
|
"DO UPDATE SET body=excluded.body WHERE "
|
|
"json_extract(excluded.body, '$.measured_at') >= "
|
|
"json_extract(operation_modem.body, '$.measured_at')",
|
|
(imei, json.dumps(value)),
|
|
)
|
|
offset += size + 8
|
|
|
|
def selected(self, value):
|
|
if (
|
|
self.commands.sim_guard.check(
|
|
value["imei"], value["request"].get("sim_guard"), after=value["created_at"]
|
|
)
|
|
!= "matched"
|
|
):
|
|
return None
|
|
with self.store.db() as db:
|
|
row = db.execute(
|
|
"SELECT body FROM operation_modem WHERE imei=?", (value["imei"],)
|
|
).fetchone()
|
|
data = json.loads(row[0]) if row else {}
|
|
return (
|
|
data
|
|
if sim_selection.matches(value["request"], data.get("active_sim"))
|
|
and data.get("gprs") == 4
|
|
and data.get("measured_at", 0) > value["created_at"]
|
|
and 0 <= time.time() - data["measured_at"] <= 30
|
|
else None
|
|
)
|
|
|
|
def reconcile(self, value, result):
|
|
request = value["request"]
|
|
digest = result.get("configuration_sha256")
|
|
target = hashlib.sha256(bytes.fromhex(request["target_configuration"])).hexdigest()
|
|
if digest == target:
|
|
if value["kind"] == "configure-all":
|
|
value.update(state="verified", runtime_phase="complete", result=result)
|
|
elif selected := self.selected(value):
|
|
value.update(
|
|
state="sim_selected",
|
|
runtime_phase="complete",
|
|
result={
|
|
**result,
|
|
"active_sim": selected["active_sim"],
|
|
"telemetry_measured_at": selected["measured_at"],
|
|
"sim_guard_verified": bool(request.get("sim_guard")),
|
|
},
|
|
)
|
|
else:
|
|
value.update(phase="execute", retry_predecessor=target)
|
|
elif digest == request["expected_sha256"]:
|
|
value.update(phase="execute", retry_predecessor=digest)
|
|
else:
|
|
value.update(
|
|
state="rejected",
|
|
reason="configuration_conflict",
|
|
runtime_phase="complete",
|
|
result=result,
|
|
)
|
|
|
|
def advance(self, imei):
|
|
with self.lock:
|
|
with self.store.db() as db:
|
|
row = db.execute(
|
|
"SELECT body FROM operations WHERE imei=? AND state IN "
|
|
"('queued','dispatched') ORDER BY seq LIMIT 1",
|
|
(imei,),
|
|
).fetchone()
|
|
if not row:
|
|
return
|
|
value = json.loads(row[0])
|
|
if not self.store.admitted(imei):
|
|
value.update(state="rejected", reason="device_revoked", runtime_phase="complete")
|
|
self.save(value)
|
|
return
|
|
if value.get("attempt"):
|
|
# Idempotent submission covers a crash before/after attempt admission.
|
|
# Read first: the accepted attempt may have completed while Core was away.
|
|
try:
|
|
result = self.commands.get(value["attempt"]["id"])
|
|
except ValueError:
|
|
if value.get("stop_requested"):
|
|
value.pop("attempt", None)
|
|
value.update(state="stopped", runtime_phase="stopped")
|
|
self.save(value)
|
|
return
|
|
try:
|
|
result = self.commands.submit(value["attempt"])
|
|
except ValueError:
|
|
return # A legacy operation/session admission still owns the channel.
|
|
value["result"] = result
|
|
self.note_attempt(value, result)
|
|
if result["state"] in PENDING:
|
|
value.update(
|
|
state=result["state"],
|
|
runtime_phase="checking-result"
|
|
if value["phase"] == "inspect"
|
|
else "executing",
|
|
)
|
|
self.save(value)
|
|
return
|
|
if value["phase"] == "inspect" and result["state"] == "observed":
|
|
self.reconcile(value, result)
|
|
elif result["state"] in {
|
|
"device_confirmed",
|
|
"observed",
|
|
"verified",
|
|
"sim_selected",
|
|
"reconnected",
|
|
}:
|
|
value.update(state=result["state"], runtime_phase="complete")
|
|
elif (
|
|
value["kind"] == "restart"
|
|
and result.get("device_code") == 0
|
|
and result.get("device_accepted_at")
|
|
):
|
|
value.update(state="accepted", runtime_phase="complete")
|
|
elif (
|
|
result["state"] in RETRY
|
|
or result.get("device_code") == 7
|
|
or result.get("reason") == "configuration_predecessor_mismatch"
|
|
):
|
|
if value["kind"] in {"configure-all", "select-sim"}:
|
|
value["phase"] = "inspect"
|
|
else:
|
|
value.update(state=result["state"], runtime_phase="complete")
|
|
if result.get("reason") == "sim_card_changed":
|
|
value["reason"] = "sim_card_changed"
|
|
value.pop("attempt", None)
|
|
if value["state"] in PENDING:
|
|
value.update(
|
|
state="stopped" if value.get("stop_requested") else "queued",
|
|
runtime_phase="stopped" if value.get("stop_requested") else "retry-wait",
|
|
next_attempt_at=time.time()
|
|
+ min(300, 5 * 2 ** min(value["attempt_count"] - 1, 6)),
|
|
)
|
|
self.save(value)
|
|
return
|
|
if value.get("stop_requested"):
|
|
value.update(state="stopped", runtime_phase="stopped")
|
|
self.save(value)
|
|
return
|
|
if value["next_attempt_at"] > time.time():
|
|
return
|
|
if not self.fresh(imei):
|
|
if value["runtime_phase"] != "waiting-link":
|
|
value.update(runtime_phase="waiting-link")
|
|
self.save(value)
|
|
return
|
|
if value["phase"] == "execute" and value["request"].get("sim_guard"):
|
|
guard = self.commands.sim_guard.check(imei, value["request"]["sim_guard"])
|
|
if guard != "matched":
|
|
if guard == "changed":
|
|
value.update(
|
|
state="rejected", runtime_phase="complete", reason="sim_card_changed"
|
|
)
|
|
else:
|
|
value.update(runtime_phase="waiting-identity")
|
|
self.save(value)
|
|
return
|
|
attempt = {**value["request"], "id": uuid.uuid4().hex}
|
|
if value["phase"] == "inspect":
|
|
attempt = {
|
|
k: v
|
|
for k, v in attempt.items()
|
|
if k in {"id", "imei", "password", "model", "firmware"}
|
|
}
|
|
attempt["kind"] = "read-configuration"
|
|
elif value.get("retry_predecessor"):
|
|
attempt["expected_sha256"] = value["retry_predecessor"]
|
|
lifetime = (
|
|
360
|
|
if attempt["kind"] == "select-sim"
|
|
else 30
|
|
if attempt["kind"] == "request-position"
|
|
else 180
|
|
)
|
|
attempt["not_after"] = time.time() + lifetime
|
|
value.update(
|
|
attempt=attempt,
|
|
attempt_count=value["attempt_count"] + 1,
|
|
result={},
|
|
runtime_phase="checking-result" if value["phase"] == "inspect" else "executing",
|
|
)
|
|
# The plan is durable before the attempt's separate transaction.
|
|
self.save(value)
|
|
self.advance(imei)
|