import re, datetime, sqlite3, collections, statistics as st LOG = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\logs\attendancehub_sync.log" DB = r"G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish\attendancehub_v2.db" SITE, SKEW = 12600, 84 # punch_label(UTC-inst) => P - (SITE - SKEW) = P - 12516 NOW = datetime.datetime.now(datetime.timezone.utc) def parse(s): if s is None: return None s = s.rstrip("Z") if "." in s: w, fr = s.split("."); fr = (fr + "0000000")[:7] else: w, fr = s, "0000000" return (datetime.datetime.fromisoformat(w).replace(tzinfo=datetime.timezone.utc) + datetime.timedelta(microseconds=int(fr) / 10)) # ---------- read ops ---------- patR = re.compile(r"^(\d{2}:\d{2}:\d{2})\.\d+ .*COM_OP device=([^:]+):read api=ReadAttendance " r".*?startUtc=(\S+) endUtc=(\S+) durationMs=(\d+) ok=(\S+)") reads = [] # ---------- live pings ---------- patP = re.compile(r"^(\d{2}:\d{2}:\d{2})\.\d+ .*COM_OP device=([^:]+):live api=LivenessPing " r".*?startUtc=(\S+) endUtc=(\S+) durationMs=(\d+) ok=(\S+)") pings = [] # ---------- connect / disconnect ---------- patC = re.compile(r"^(\d{2}:\d{2}:\d{2})\.\d+ .*COM_OP device=([^:]+):(\S+) api=(Connect_Net|Disconnect|RegEvent) " r".*?durationMs=(\d+) ok=(\S+)") conns = [] # ---------- session events ---------- patS = re.compile(r"^(\d{2}:\d{2}:\d{2}).*SESSION_(READ|LIVE)_RECREATE device=(\S+) reason=(\S+)") with open(LOG, "r", encoding="utf-8", errors="replace") as f: for ln in f: if "api=ReadAttendance" in ln: m = patR.match(ln) if m: t, d, s, e, ms, ok = m.groups() reads.append((t, d, parse(s), parse(e), int(ms), ok)) elif "api=LivenessPing" in ln: m = patP.match(ln) if m: t, d, s, e, ms, ok = m.groups() pings.append((t, d, parse(s), parse(e), int(ms), ok)) elif "api=Connect_Net" in ln or "api=Disconnect" in ln or "api=RegEvent" in ln: m = patC.match(ln) if m: conns.append(m.groups()) elif "SESSION_READ_RECREATE" in ln or "SESSION_LIVE_RECREATE" in ln: m = patS.match(ln) if m: conns.append(("SESS", m.group(1), m.group(3), m.group(2), "0", m.group(4))) print(f"now local = {datetime.datetime.now().strftime('%H:%M:%S')} " f"reads={len(reads)} pings={len(pings)}") busy = [r for r in reads if r[4] >= 20000] def punch_utc(label): """device label -> true UTC instant of the punch""" return parse(label) - datetime.timedelta(seconds=SITE - SKEW) # ================= TEST 1: punch MOMENT inside busy read ================= con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True, timeout=15) today = NOW.strftime("%Y-%m-%d") rows = con.execute( "SELECT personnel_code, device_id, punch_time, first_seen_at, source " "FROM punches WHERE first_seen_at >= ?", (today + "T00:00:00.0000000Z",)).fetchall() print("\n=== TEST 1: was the punch MOMENT inside a >=20s read on the SAME device? ===") inside_same, inside_other, outside = [], [], [] for pc, dev, pt, fs, src in rows: try: pu = punch_utc(pt) except Exception: continue hit_same = hit_other = None for r in busy: if r[2] <= pu <= r[3]: if r[1] == dev: hit_same = r else: hit_other = r if hit_same: inside_same.append((pc, dev, pu, src, hit_same[4])) elif hit_other: inside_other.append((pc, dev, pu, src, hit_other[4])) else: outside.append((pc, dev, pu, src)) print(f" punch MOMENT inside a long read on ITS OWN device : {len(inside_same)}") print(f" punch MOMENT inside a long read on ANOTHER device : {len(inside_other)}") print(f" punch MOMENT while device not busy : {len(outside)}") if inside_same: byd = collections.Counter(x[1] for x in inside_same) bysrc = collections.Counter(x[3] for x in inside_same) print(f" by device: {dict(byd)}") print(f" by source: {dict(bysrc)}") print(" --- samples (punch happened WHILE its own device was serving a long read) ---") for pc, dev, pu, src, ms in inside_same[:14]: print(f" {pu.strftime('%H:%M:%S')} pin={pc:<8} dev={dev:<16} src={src:<14} " f"readBusy={ms/1000:.0f}s") # ================= TEST 2: slow pings (device unresponsive) ================= print("\n=== TEST 2: LivenessPing > 3000ms (device unresponsive moments) ===") slow = [p for p in pings if p[4] > 3000] slow.sort(key=lambda x: -x[4]) print(f" count = {len(slow)} of {len(pings)}") for t, d, s, e, ms, ok in slow[:15]: # was it during a busy read? where = "inside-own-read" if any(r[1] == d and r[2] <= s <= r[3] for r in busy) else "NO-read-active" print(f" {t} {d:<16} {ms/1000:7.1f}s ok={ok} {where}") # ================= TEST 3: phase1-test-01 timeline ================= P1 = "phase1-test-01" print(f"\n=== TEST 3: {P1} (=172.24.30.9) — connection/session churn ===") for c in conns: if c[1] == P1: print(f" {c[0]} api={c[3]:<14} {int(c[4])/1000 if c[4].isdigit() else 0:7.2f}s ok={c[5]}") # ================= TEST 4: phase1 busy time vs punches ================= print(f"\n=== TEST 4: {P1} busy windows & its punches ===") p1_busy = [r for r in busy if r[1] == P1] total_busy = sum(r[4] for r in p1_busy) / 1000 print(f" long reads: {len(p1_busy)} total busy = {total_busy:.0f}s ({total_busy/60:.1f} min)") p1_punches = [x for x in inside_same + outside if x[1] == P1] during_p1 = [x for x in inside_same if x[1] == P1] print(f" its punches total today = {sum(1 for r in rows if r[1]==P1)}") print(f" of which moment fell inside ITS OWN busy read = {len(during_p1)}") for pc, dev, pu, src, ms in during_p1[:12]: print(f" {pu.strftime('%H:%M:%S')} pin={pc:<8} src={src:<14} readBusy={ms/1000:.0f}s") # ================= TEST 5: gaps where NO punch arrived on phase1 ================= print(f"\n=== TEST 5: {P1} — read gaps > 60s (device not being read) ===") p1r = sorted([r for r in reads if r[1] == P1], key=lambda x: x[2]) def secs(d): return d.hour*3600 + d.minute*60 + d.second g = [] for a, b in zip(p1r, p1r[1:]): delta = (b[2] - a[2]).total_seconds() if delta > 60: g.append((delta, a[0], b[0])) g.sort(reverse=True) for delta, a, b in g[:8]: print(f" gap={delta:6.0f}s {a} -> {b}") con.close()