diff --git a/scripts/greenhouse-backfill.py b/scripts/greenhouse-backfill.py index 8c694e2..d4a4ee1 100755 --- a/scripts/greenhouse-backfill.py +++ b/scripts/greenhouse-backfill.py @@ -13,6 +13,9 @@ HA와 MQTT 브로커가 있는 클로서버는 매일 02시에 자서 기상 때 HA는 자고 일어나면 빈 시간의 통계를 '잠들기 직전 값 그대로'(평평한 값)로 만들어 둔다. 채운 시간대를 대기 목록 (~/.cache/greenhouse-backfill.json)에 올려 두고, HA가 그 시간 통계 행을 만든 뒤에 CSV 값으로 덮어쓴다(행 추가는 안 함 — HA가 같은 시간 행을 나중에 넣으려다 충돌하지 않게). 사흘 넘게 행이 안 생긴 시간은 목록에서 뺀다. +- DB 파일 주인이 root(HA 컨테이너)라 이 계정으로는 쓸 수 없다(10-22 11시부터 'readonly database'로 매번 실패). + 읽기는 여기서 하고, 쓰기(INSERT/UPDATE)는 모아 두었다가 `docker exec -i homeassistant python3`로 컨테이너 안에서 + 한 트랜잭션으로 실행한다. sudo·권한 변경 불필요. 사용: greenhouse-backfill.py [--apply] [--days N] (기본 dry-run, 최근 2일) """ import csv, io, json, os, sqlite3, subprocess, sys, time @@ -22,6 +25,27 @@ DB = os.environ.get("HA_DB", "/home/kim/homeassistant/home-assistant_v2.db") PI = os.environ.get("GREENHOUSE_PI", "kim@192.168.0.123") GAP_S = 600 PENDING = os.path.expanduser("~/.cache/greenhouse-backfill.json") +HA_CONTAINER = os.environ.get("HA_CONTAINER", "homeassistant") +HA_DB_IN_CONTAINER = os.environ.get("HA_DB_IN_CONTAINER", "/config/home-assistant_v2.db") +# 컨테이너 안에서 돌릴 적용기: stdin으로 [[sql, params], ...]를 받아 한 트랜잭션으로 실행 +APPLIER = ( + "import json,sqlite3,sys\n" + "ops=json.load(sys.stdin)\n" + "con=sqlite3.connect(sys.argv[1],timeout=30)\n" + "with con:\n" + " for sql,params in ops: con.execute(sql,params)\n" + "print(len(ops))\n" +) + + +def apply_in_container(ops): + if not ops: + return 0 + out = subprocess.run(["docker", "exec", "-i", HA_CONTAINER, "python3", "-c", APPLIER, HA_DB_IN_CONTAINER], + input=json.dumps(ops), capture_output=True, text=True, timeout=120) + if out.returncode != 0: + sys.exit(f"HA 컨테이너에서 DB 쓰기 실패: {out.stderr.strip()[-500:]}") + return int(out.stdout.strip() or 0) ENTITIES = { "air.temperature": "sensor.onsil_onsil_gonggi_temperature", "air.humidity": "sensor.onsil_onsil_gonggi_humidity", @@ -56,7 +80,8 @@ def main(): if not rows: print("파이 기록 없음"); return t0, t1 = rows[0]["ts"], rows[-1]["ts"] - con = sqlite3.connect(DB, timeout=30) + con = sqlite3.connect(DB, timeout=30) # 읽기 전용으로만 쓴다 — 쓰기는 ops에 모아 컨테이너에서 + ops = [] cur = con.cursor() meta = {} for key, ent in ENTITIES.items(): @@ -92,8 +117,8 @@ def main(): continue prev = v if APPLY: - cur.execute("INSERT INTO states (state, attributes_id, last_changed_ts, last_reported_ts, last_updated_ts," - " metadata_id) VALUES (?,?,?,?,?,?)", (v, aid, row["ts"], row["ts"], row["ts"], mid)) + ops.append(["INSERT INTO states (state, attributes_id, last_changed_ts, last_reported_ts, last_updated_ts," + " metadata_id) VALUES (?,?,?,?,?,?)", [v, aid, row["ts"], row["ts"], row["ts"], mid]]) inserted[key] += 1 # 장기 통계: 빈 구간에 걸친 시간(정시 시작)을 대기 목록에 올리고, 행이 있는 시간만 CSV로 덮어쓴다 try: @@ -118,15 +143,16 @@ def main(): done = done and now - h < 3 * 86400 # HA가 아직 안 만듦 → 다음에 다시 continue if APPLY: - cur.execute("UPDATE statistics SET mean=?, min=?, max=? WHERE id=?", - (round(sum(vals) / len(vals), 3), min(vals), max(vals), st[0])) + ops.append(["UPDATE statistics SET mean=?, min=?, max=? WHERE id=?", + [round(sum(vals) / len(vals), 3), min(vals), max(vals), st[0]]]) fixed += 1 if done: pending.discard(h) + con.close() if APPLY: + apply_in_container(ops) # 실패하면 여기서 종료 — 대기 목록은 안 줄인 채로 남는다 os.makedirs(os.path.dirname(PENDING), exist_ok=True) json.dump(sorted(pending), open(PENDING, "w")) - con.commit(); con.close() fmt = lambda t: datetime.fromtimestamp(t).strftime("%m-%d %H:%M") print(f"[{'INSERT' if APPLY else 'DRY-RUN'}] 빈 구간 {len(gaps)}개:", ", ".join(f"{fmt(a)}~{fmt(b)}" for a, b in gaps) or "없음") print(" " + ", ".join(f"{k} {n}건" for k, n in inserted.items())) diff --git a/scripts/wake-watch.py b/scripts/wake-watch.py index b833e4b..c4872d3 100755 --- a/scripts/wake-watch.py +++ b/scripts/wake-watch.py @@ -16,8 +16,8 @@ EVENTS = f"{HOME}/events.jsonl" KNOWN = f"{HOME}/known.json" TRUENAS = "truenas_admin@192.168.0.240" CONTAINER = "ix-wol-gate-wol-gate-1" -LINE = re.compile(r'^(\S+Z) \[wol-gate\] (?:\d{4}-\d\d-\d\d \d\d:\d\d:\d\d KST )?(waking|wake suppressed \(cooldown\)|wake blocked \(non-KR\)|wake denied \(watchlist\)) - triggered by (\S+) "(\w+) ([^"]*)" UA="(.*)"$') -KIND = {"waking": "wake", "wake suppressed (cooldown)": "cooldown", "wake blocked (non-KR)": "non-kr", "wake denied (watchlist)": "denied"} +LINE = re.compile(r'^(\S+Z) \[wol-gate\] (?:\d{4}-\d\d-\d\d \d\d:\d\d:\d\d KST )?(waking|wake suppressed \(cooldown\)|wake blocked \(non-KR\)|wake denied \(watchlist\)|wake held \(no login, button shown\)) - triggered by (\S+) "(\w+) ([^"]*)" UA="(.*)"$') +KIND = {"waking": "wake", "wake suppressed (cooldown)": "cooldown", "wake blocked (non-KR)": "non-kr", "wake denied (watchlist)": "denied", "wake held (no login, button shown)": "held"} def load_known(): if not os.path.exists(KNOWN): diff --git a/wol-gate/server.js b/wol-gate/server.js index e8fe745..107fb00 100644 --- a/wol-gate/server.js +++ b/wol-gate/server.js @@ -18,6 +18,16 @@ const LISTEN_PORT = parseInt(process.env.LISTEN_PORT || '8099', 10); const HEALTH_TIMEOUT_MS = parseInt(process.env.HEALTH_TIMEOUT_MS || '1200', 10); const WAKE_COOLDOWN_MS = parseInt(process.env.WAKE_COOLDOWN_MS || '30000', 10); const REFRESH_SECONDS = parseInt(process.env.REFRESH_SECONDS || '5', 10); +// 사람만 깨우기(2026-10-23): 국내 IP 스캐너(59.14.17.48 "PHP-Inventory-Audit/1.0", /phpinfo.php)가 새벽 2:20에 +// 클로서버를 깨웠다. UA 블랙리스트·국가 필터로는 계속 뚫리므로, 로그인 흔적(홈클로 세션 쿠키·Bearer 토큰· +// 전에 깨우기 버튼을 누른 쿠키)이 있는 요청만 자동으로 깨우고, 나머지는 '깨우기' 버튼(POST)을 눌러야 깨운다. +// 봇은 GET만 두드리고 버튼을 누르지 않는다. 홈클로(18789) 대상은 기본 켬, 지서버 Ollama(게이트웨이가 쿠키 없이 +// 부름)는 기본 끔. REQUIRE_HUMAN=0/1로 강제할 수 있다. +const REQUIRE_HUMAN = process.env.REQUIRE_HUMAN !== undefined + ? process.env.REQUIRE_HUMAN === '1' + : TARGET_PORT === 18789; +const HUMAN_COOKIE = 'wolgate_human'; +const WAKE_PATH = '/__wolgate/wake'; let lastWakeAt = 0; @@ -179,10 +189,35 @@ function checkTargetAlive() { }); } -function renderWakingPage() { +function hasHumanCredential(req) { + const cookie = String(req.headers['cookie'] || ''); + if (/(?:^|;\s*)(?:smallclaw_session|wolgate_human)=[^;\s]+/.test(cookie)) return true; + return /^Bearer\s+\S+/i.test(String(req.headers['authorization'] || '')); +} + +function renderAskPage() { return ` - + + +서버가 자는 중 + + +
서버가 절전 중입니다
+
+

한 번 누르면 이 브라우저는 다음부터 접속만으로 깨어납니다

+`; +} + +function renderWakingPage(toRoot) { + return ` + + 서버 깨우는 중...