triflix commited on
Commit
a1e95eb
·
verified ·
1 Parent(s): df27af3

Create worker.py

Browse files
Files changed (1) hide show
  1. worker.py +62 -0
worker.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # worker.py
2
+ import sys
3
+ import time
4
+ import sqlite3
5
+ import httpx
6
+ import os
7
+ import traceback
8
+
9
+ # Args: site_id, db_file, ping_interval_seconds
10
+ if len(sys.argv) < 4:
11
+ print("Usage: python worker.py <site_id> <db_file> <ping_interval_seconds>")
12
+ sys.exit(1)
13
+
14
+ site_id = int(sys.argv[1])
15
+ DB_FILE = sys.argv[2]
16
+ PING_INTERVAL_SECONDS = int(sys.argv[3])
17
+
18
+ def get_site_url(site_id):
19
+ conn = sqlite3.connect(DB_FILE)
20
+ cur = conn.cursor()
21
+ cur.execute("SELECT url FROM sites WHERE id = ?", (site_id,))
22
+ row = cur.fetchone()
23
+ conn.close()
24
+ return row[0] if row else None
25
+
26
+ def record_ping(site_id, status_code=None, latency_ms=None, error=None):
27
+ conn = sqlite3.connect(DB_FILE)
28
+ cur = conn.cursor()
29
+ cur.execute("""
30
+ INSERT INTO pings (site_id, status_code, latency_ms, error)
31
+ VALUES (?, ?, ?, ?)
32
+ """, (site_id, status_code, latency_ms, error))
33
+ conn.commit()
34
+ conn.close()
35
+
36
+ def ping_once(url):
37
+ try:
38
+ start = time.time()
39
+ with httpx.Client(timeout=30.0, follow_redirects=True) as client:
40
+ r = client.get(url)
41
+ latency = int((time.time() - start) * 1000)
42
+ return r.status_code, latency, None
43
+ except Exception as e:
44
+ return None, None, str(e)
45
+
46
+ def main_loop():
47
+ url = get_site_url(site_id)
48
+ if not url:
49
+ print("Site not found; exiting.")
50
+ return
51
+ print(f"Worker {site_id} started for {url}")
52
+ while True:
53
+ try:
54
+ status_code, latency, error = ping_once(url)
55
+ record_ping(site_id, status_code, latency, error)
56
+ except Exception as e:
57
+ print("Worker error:", e)
58
+ traceback.print_exc()
59
+ time.sleep(PING_INTERVAL_SECONDS)
60
+
61
+ if __name__ == "__main__":
62
+ main_loop()