wol-gate: 로그인 흔적(홈클로 세션 쿠키·Bearer·깨우기 버튼 쿠키) 있는 요청만 자동 기상, 나머지는 '서버 깨우기' 버튼(POST) — 국내 IP 스캐너(PHP-Inventory-Audit, /phpinfo.php)가 새벽 2:20에 깨움. 홈클로 대상만 기본 켬(지서버 Ollama는 그대로). wake-watch 파서에 'wake held' 추가. 온실 백필: HA DB가 root 소유라 쓰기를 docker exec로 컨테이너 안에서 실행(10-22 11시부터 readonly 실패)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8664834000
commit
df80789830
3 files changed
+92
-14
No files matched your search
@@ -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()))
|
||||
|
||||
@@ -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):
|
||||
|
||||
+58
-6
@@ -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 `<!doctype html>
|
||||
<html lang="ko"><head><meta charset="utf-8">
|
||||
<meta http-equiv="refresh" content="${REFRESH_SECONDS}">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>서버가 자는 중</title>
|
||||
<style>
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#111;color:#eee;
|
||||
display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0;gap:16px}
|
||||
button{font-size:16px;padding:12px 28px;border-radius:8px;border:0;background:#7c5c2e;color:#fff;cursor:pointer}
|
||||
p{color:#999;font-size:14px}
|
||||
</style></head>
|
||||
<body>
|
||||
<div>서버가 절전 중입니다</div>
|
||||
<form method="post" action="${WAKE_PATH}"><button type="submit">서버 깨우기</button></form>
|
||||
<p>한 번 누르면 이 브라우저는 다음부터 접속만으로 깨어납니다</p>
|
||||
</body></html>`;
|
||||
}
|
||||
|
||||
function renderWakingPage(toRoot) {
|
||||
return `<!doctype html>
|
||||
<html lang="ko"><head><meta charset="utf-8">
|
||||
<meta http-equiv="refresh" content="${REFRESH_SECONDS}${toRoot ? ';url=/' : ''}">
|
||||
<title>서버 깨우는 중...</title>
|
||||
<style>
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#111;color:#eee;
|
||||
@@ -247,19 +282,36 @@ function proxyRequest(req, res) {
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const isWakeButton = req.method === 'POST' && (req.url || '').split('?')[0] === WAKE_PATH;
|
||||
if (await checkTargetAlive()) {
|
||||
if (isWakeButton) { // 깨어난 뒤 버튼 POST가 늦게 도착 — 백엔드로 넘기지 않고 첫 화면으로
|
||||
res.writeHead(303, { Location: '/' });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
proxyRequest(req, res);
|
||||
return;
|
||||
}
|
||||
if (REQUIRE_HUMAN && !isWakeButton && !hasHumanCredential(req)) {
|
||||
console.log(`[wol-gate] ${kst()} wake held (no login, button shown) - triggered by ${describeRequester(req)}`);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
|
||||
res.end(renderAskPage());
|
||||
return;
|
||||
}
|
||||
maybeWake(req);
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
res.end(renderWakingPage());
|
||||
const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' };
|
||||
if (isWakeButton) {
|
||||
// 버튼을 누른 브라우저는 1년간 사람으로 기억 — 다음부터 접속만으로 깨운다
|
||||
headers['Set-Cookie'] = `${HUMAN_COOKIE}=1; Path=/; Max-Age=31536000; HttpOnly; SameSite=Lax; Secure`;
|
||||
}
|
||||
res.writeHead(200, headers);
|
||||
res.end(renderWakingPage(isWakeButton));
|
||||
});
|
||||
|
||||
// Forward WebSocket upgrades too, once awake (homeclaw uses WS heavily).
|
||||
server.on('upgrade', async (req, socket, head) => {
|
||||
if (!(await checkTargetAlive())) {
|
||||
maybeWake(req);
|
||||
if (!REQUIRE_HUMAN || hasHumanCredential(req)) maybeWake(req);
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
@@ -278,5 +330,5 @@ server.on('upgrade', async (req, socket, head) => {
|
||||
});
|
||||
|
||||
server.listen(LISTEN_PORT, () => {
|
||||
console.log(`[wol-gate] ${kst()} listening on :${LISTEN_PORT} -> ${TARGET_HOST}:${TARGET_PORT}, WOL target ${TARGET_MAC} via ${BROADCAST_ADDR}:${WOL_PORT}`);
|
||||
console.log(`[wol-gate] ${kst()} listening on :${LISTEN_PORT} -> ${TARGET_HOST}:${TARGET_PORT}, WOL target ${TARGET_MAC} via ${BROADCAST_ADDR}:${WOL_PORT}, require-human=${REQUIRE_HUMAN}`);
|
||||
});
|
||||
Reference in new issue
Block a user