linuxrouter/docker/routlin-dash/app/config_utils.py

460 lines
15 KiB
Python
Raw Normal View History

2026-05-25 16:07:21 -04:00
import copy, json, subprocess, hashlib, os, uuid
2026-05-20 04:06:50 -04:00
from datetime import datetime, timezone
from flask import session
2026-05-17 03:26:01 -04:00
2026-05-22 02:54:56 -04:00
CONFIGS_DIR = '/routlin_location'
2026-05-24 00:47:43 -04:00
DATA_DIR = '/data'
ACCOUNTS_FILE = f'{DATA_DIR}/authorized_accounts.json'
2026-05-25 19:59:42 -04:00
CONFIG_FILE = f'{CONFIGS_DIR}/config.json'
2026-05-20 04:06:50 -04:00
DASHBOARD_QUEUE = f'{CONFIGS_DIR}/.dashboard-queue'
DASHBOARD_DONE = f'{CONFIGS_DIR}/.dashboard-done'
DASHBOARD_LAST_RUN = f'{CONFIGS_DIR}/.dashboard-last-run'
DASHBOARD_LOCK = f'{CONFIGS_DIR}/.dashboard-lock'
2026-05-22 01:09:23 -04:00
DASHBOARD_PENDING = f'{CONFIGS_DIR}/.dashboard-pending'
2026-05-25 16:07:21 -04:00
SNAPSHOTS_DIR = f'{CONFIGS_DIR}/.snapshots'
2026-05-25 01:04:47 -04:00
HEALTH_FILE = f'{CONFIGS_DIR}/.health'
2026-05-25 16:07:21 -04:00
PRODUCT_NAME = os.environ.get('PRODUCT_NAME', 'routlin')
DASHB_TIMER_NAME = f'{PRODUCT_NAME}-dashboard-queue'
DDNS_TIMER_NAME = f'{PRODUCT_NAME}-ddns-update'
WEB_APP_DISPLAY_NAME = os.environ.get('WEB_APP_DISPLAY_NAME', f'{PRODUCT_NAME.capitalize()} Dashboard')
DASHB_INTERVAL_SECS = 60
QUEUE_MAX_LINES = 50
2026-05-17 03:26:01 -04:00
2026-05-25 19:59:42 -04:00
def load_config():
2026-05-17 03:26:01 -04:00
try:
2026-05-25 19:59:42 -04:00
with open(CONFIG_FILE) as f:
2026-05-17 03:26:01 -04:00
return json.load(f)
except Exception:
return {}
2026-05-25 19:59:42 -04:00
def save_config(data):
with open(CONFIG_FILE, 'w') as f:
2026-05-17 03:26:01 -04:00
json.dump(data, f, indent=2)
2026-05-25 19:59:42 -04:00
def config_hash():
2026-05-17 03:26:01 -04:00
try:
2026-05-25 19:59:42 -04:00
with open(CONFIG_FILE, 'rb') as f:
2026-05-17 03:26:01 -04:00
return hashlib.md5(f.read()).hexdigest()
except Exception:
return ''
2026-05-25 19:59:42 -04:00
def verify_config_hash(submitted):
2026-05-17 03:26:01 -04:00
if not submitted:
return True
2026-05-25 19:59:42 -04:00
return submitted == config_hash()
2026-05-17 03:26:01 -04:00
2026-05-20 04:06:50 -04:00
def _load_done_set():
try:
done = set()
for line in open(DASHBOARD_DONE).read().splitlines():
parts = line.split()
if parts:
done.add(parts[0])
return done
except Exception:
return set()
def _read_pending(done_set):
pending = []
try:
lines = open(DASHBOARD_QUEUE).read().splitlines()
except Exception:
return pending
for line in lines:
try:
2026-05-25 14:50:03 -04:00
parts = line.split(None, 2)
if len(parts) == 3:
entry_uuid, entry_ts, rest = parts
2026-05-25 16:07:21 -04:00
cmd_user = rest.rsplit(' (', 1)
2026-05-20 04:06:50 -04:00
entry_cmd = cmd_user[0].strip('[]')
entry_user = cmd_user[1].rstrip(')') if len(cmd_user) == 2 else ''
if entry_uuid not in done_set:
pending.append((entry_uuid, int(entry_ts), entry_cmd, entry_user))
except Exception:
pass
return pending
def get_pending_entries():
return _read_pending(_load_done_set())
def _format_timing(secs):
if secs is None:
return None
if secs <= 5:
return 'momentarily'
if secs < 60:
return f'in about {secs} seconds'
mins = round(secs / 60)
return f'in about {mins} minute{"s" if mins != 1 else ""}'
def _trim_if_needed():
try:
lines = [l for l in open(DASHBOARD_QUEUE).read().splitlines() if l]
if len(lines) <= QUEUE_MAX_LINES:
return
done_set = _load_done_set()
pending = [l for l in lines if l.split()[0] not in done_set]
with open(DASHBOARD_QUEUE, 'w') as f:
f.write('\n'.join(pending) + ('\n' if pending else ''))
open(DASHBOARD_DONE, 'w').close()
except Exception:
pass
2026-05-25 14:12:52 -04:00
def _apply_changes_immediately():
2026-05-22 01:09:23 -04:00
try:
2026-05-25 13:49:23 -04:00
return session.get('apply_changes_immediately', False)
2026-05-22 01:09:23 -04:00
except Exception:
2026-05-25 13:49:23 -04:00
return False
2026-05-22 01:09:23 -04:00
def _read_dashboard_pending():
2026-05-25 16:07:21 -04:00
"""Return list of (uuid, ts, cmd, user) from .dashboard-pending."""
2026-05-22 01:09:23 -04:00
items = []
try:
lines = open(DASHBOARD_PENDING).read().splitlines()
except Exception:
return items
for line in lines:
if not line.strip():
continue
try:
2026-05-25 16:07:21 -04:00
parts = line.split(None, 2)
2026-05-25 14:50:03 -04:00
if len(parts) == 3:
entry_uuid, entry_ts, rest = parts
2026-05-22 01:09:23 -04:00
cmd_user = rest.rsplit(' (', 1)
entry_cmd = cmd_user[0].strip('[]')
entry_user = cmd_user[1].rstrip(')') if len(cmd_user) == 2 else ''
2026-05-25 16:07:21 -04:00
items.append((entry_uuid, int(entry_ts), entry_cmd, entry_user))
2026-05-22 01:09:23 -04:00
except Exception:
pass
return items
def get_dashboard_pending():
return _read_dashboard_pending()
2026-05-25 16:38:08 -04:00
def get_dashboard_done():
"""Return list of (uuid, applied_ts) from .dashboard-done, newest first."""
items = []
try:
lines = open(DASHBOARD_DONE).read().splitlines()
except Exception:
return items
for line in lines:
if not line.strip():
continue
try:
parts = line.split(None, 1)
if len(parts) >= 2:
items.append((parts[0], int(parts[1])))
elif len(parts) == 1:
items.append((parts[0], None))
except Exception:
pass
items.reverse()
return items
2026-05-22 01:09:23 -04:00
def flush_pending_to_queue():
"""Move all entries from .dashboard-pending to .dashboard-queue and clear pending."""
items = _read_dashboard_pending()
if not items:
return
done_set = _load_done_set()
existing_ids = {uu for uu, *_ in _read_pending(done_set)}
with open(DASHBOARD_QUEUE, 'a') as f:
2026-05-25 16:07:21 -04:00
for entry_uuid, entry_ts, entry_cmd, entry_user in items:
2026-05-22 01:09:23 -04:00
if entry_uuid not in existing_ids:
2026-05-25 14:50:03 -04:00
f.write(f'{entry_uuid} {entry_ts} [{entry_cmd}] ({entry_user})\n')
2026-05-22 01:09:23 -04:00
open(DASHBOARD_PENDING, 'w').close()
_trim_if_needed()
2026-05-25 14:50:03 -04:00
2026-05-25 16:07:21 -04:00
def _queue_pending_command(cmd):
2026-05-22 01:09:23 -04:00
"""Append cmd to .dashboard-pending if not already present for this cmd+user."""
existing = _read_dashboard_pending()
current_user = session.get('email_address', 'unknown')
2026-05-25 16:07:21 -04:00
for entry_uuid, entry_ts, entry_cmd, entry_user in existing:
2026-05-22 01:09:23 -04:00
if entry_cmd == cmd and entry_user == current_user:
return entry_uuid, entry_ts
entry_uuid = str(uuid.uuid4())
2026-05-25 16:07:21 -04:00
entry_ts = int(datetime.now().timestamp())
2026-05-22 01:09:23 -04:00
with open(DASHBOARD_PENDING, 'a') as f:
2026-05-25 16:07:21 -04:00
f.write(f'{entry_uuid} {entry_ts} [{cmd}] ({current_user})\n')
2026-05-22 01:09:23 -04:00
return entry_uuid, entry_ts
2026-05-25 16:07:21 -04:00
def _queue_pending_presigned(cmd, entry_uuid, entry_ts):
"""Write a pre-generated entry to .dashboard-pending without dedup."""
current_user = session.get('email_address', 'unknown')
with open(DASHBOARD_PENDING, 'a') as f:
f.write(f'{entry_uuid} {entry_ts} [{cmd}] ({current_user})\n')
def _queue_command(cmd):
2026-05-25 14:12:52 -04:00
if not _apply_changes_immediately():
2026-05-25 16:07:21 -04:00
return _queue_pending_command(cmd)
2026-05-20 04:06:50 -04:00
done_set = _load_done_set()
2026-05-25 16:07:21 -04:00
pending = _read_pending(done_set)
2026-05-20 04:06:50 -04:00
current_user = session.get('email_address', 'unknown')
for entry_uuid, entry_ts, entry_cmd, entry_user in pending:
if entry_cmd == cmd and entry_user == current_user:
return entry_uuid, entry_ts
entry_uuid = str(uuid.uuid4())
2026-05-25 16:07:21 -04:00
entry_ts = int(datetime.now().timestamp())
2026-05-20 04:06:50 -04:00
with open(DASHBOARD_QUEUE, 'a') as f:
2026-05-25 16:07:21 -04:00
f.write(f'{entry_uuid} {entry_ts} [{cmd}] ({current_user})\n')
2026-05-20 04:06:50 -04:00
_trim_if_needed()
return entry_uuid, entry_ts
def _entry_ts_from_queue(entry_uuid):
try:
for line in open(DASHBOARD_QUEUE).read().splitlines():
parts = line.split(None, 2)
if len(parts) >= 2 and parts[0] == entry_uuid:
return int(parts[1])
except Exception:
pass
return None
def _seconds_until_next_run():
try:
last_run = float(open(DASHBOARD_LAST_RUN).read().strip())
2026-05-25 16:07:21 -04:00
elapsed = datetime.now(timezone.utc).timestamp() - last_run
2026-05-20 04:06:50 -04:00
return int(max(0, DASHB_INTERVAL_SECS - elapsed))
except Exception:
return None
def _is_locked():
try:
return os.path.getsize(DASHBOARD_LOCK) > 0
except Exception:
return False
def _lock_mtime():
try:
return os.path.getmtime(DASHBOARD_LOCK)
except Exception:
return None
2026-05-25 16:07:21 -04:00
def _build_timing_msg(entry_ts, cmd, action_label='Configuration saved'):
2026-05-25 14:12:52 -04:00
if not _apply_changes_immediately():
2026-05-23 04:14:58 -04:00
return f'{action_label}. Click Apply Now on the Configuration Changes card to apply.'
2026-05-20 04:06:50 -04:00
if _is_locked():
mtime = _lock_mtime()
if entry_ts is not None and mtime and entry_ts < mtime:
2026-05-23 04:14:58 -04:00
return f'{action_label}. Changes are being applied now.'
return f'{action_label}. Changes will be applied on the next run.'
2026-05-20 04:06:50 -04:00
timing = _format_timing(_seconds_until_next_run())
if timing:
2026-05-23 04:14:58 -04:00
return f'{action_label}. Changes will be applied {timing}.'
2026-05-20 04:06:50 -04:00
if cmd is None:
2026-05-23 04:14:58 -04:00
return f'{action_label}. The processing service is not running.'
2026-05-25 16:07:21 -04:00
parts = cmd.split()
2026-05-20 04:06:50 -04:00
cli_cmd = f'sudo python3 {parts[0]}.py --{parts[1]}' if len(parts) == 2 else cmd
2026-05-25 16:07:21 -04:00
install_cmd = 'sudo python3 install.py'
2026-05-20 04:06:50 -04:00
from markupsafe import Markup
2026-05-23 04:14:58 -04:00
return Markup(f'{action_label}. The command processing service is not installed. '
2026-05-20 04:06:50 -04:00
f'Run <strong>{install_cmd}</strong> to enable it, '
f'or <strong>{cli_cmd}</strong> to apply manually.')
2026-05-25 16:07:21 -04:00
def queue_command(cmd, description=''):
"""Queue a command without generating a flash message. description is ignored (kept for compat)."""
return _queue_command(cmd)
def queued_msg(cmd=None, description='', action_label='Configuration saved'):
"""Queue cmd if given, then return a timing message. description is ignored."""
entry_ts = None
if cmd is not None:
_entry_uuid, entry_ts = queue_command(cmd)
return _build_timing_msg(entry_ts, cmd, action_label)
2026-05-25 21:49:47 -04:00
# Snapshot system ===================================================
2026-05-25 16:07:21 -04:00
def _pending_uuid_set():
return {item[0] for item in _read_dashboard_pending()}
def _find_snapshot_dependencies(path, key):
"""Return UUIDs of still-pending snapshots that modified the same path+key."""
try:
pending = _pending_uuid_set()
deps = []
for fname in sorted(os.listdir(SNAPSHOTS_DIR)):
if not fname.endswith('.json'):
continue
try:
with open(os.path.join(SNAPSHOTS_DIR, fname)) as f:
snap = json.load(f)
if (snap.get('path') == path
and snap.get('key') == str(key)
and snap.get('uuid') in pending):
deps.append(snap['uuid'])
except Exception:
pass
return deps
except Exception:
return []
2026-05-25 16:38:08 -04:00
def _items_match(item, ref):
"""Return True if item and ref refer to the same entity by a common identifier field."""
if not isinstance(item, dict) or not isinstance(ref, dict):
return item == ref
for field in ('ip', 'name', 'mac_address', 'host', 'id', 'address'):
if field in ref and field in item:
return item[field] == ref[field]
return item == ref
2026-05-25 22:44:37 -04:00
def revert_snapshot_to_config(entry_uuid):
2026-05-25 19:59:42 -04:00
"""Apply the inverse of a snapshot to config.json and queue a new pending change.
2026-05-25 16:38:08 -04:00
Returns (flash_message, success_bool).
"""
snap = load_snapshot_for_uuid(entry_uuid)
if not snap:
return f'Snapshot not found for {entry_uuid[:8]}.', False
path = snap['path']
key = snap['key']
before = snap['before'] # original state to restore
after = snap['after'] # applied state to undo
operation = snap['operation']
if operation == 'revert':
return 'This change is already a revert; cannot revert again.', False
2026-05-25 19:59:42 -04:00
core = load_config()
2026-05-25 16:38:08 -04:00
if key == 'global':
if before is None:
core.pop(path, None)
else:
core[path] = before
else:
items = core.setdefault(path, [])
if operation == 'add':
core[path] = [x for x in items if not _items_match(x, after)]
elif operation == 'delete':
if before:
core[path].append(before)
else:
if before and after:
for i, item in enumerate(items):
if _items_match(item, after):
items[i] = before
break
2026-05-25 19:59:42 -04:00
msg = save_config_with_snapshot(
2026-05-25 16:38:08 -04:00
core, path=path, key=key, operation='revert',
before=after, after=before,
description=f"Reverted: {snap.get('description', '')}",
cmd=snap.get('cmd', 'core apply'),
)
return msg or 'Reverted.', True
2026-05-25 16:07:21 -04:00
def load_snapshot_for_uuid(entry_uuid):
"""Return the snapshot dict for the given UUID, or None if not found."""
try:
for fname in os.listdir(SNAPSHOTS_DIR):
if fname.endswith(f'-{entry_uuid}.json'):
with open(os.path.join(SNAPSHOTS_DIR, fname)) as f:
return json.load(f)
except Exception:
pass
return None
2026-05-25 22:44:37 -04:00
def save_config_with_snapshot(new_config, path, key, operation, before, after,
2026-05-25 16:07:21 -04:00
description='', cmd='core apply', queue=True):
"""
2026-05-25 22:44:37 -04:00
Write a .snapshots/{ts}-{uuid}.json file, save new_config to disk, and
2026-05-25 20:46:17 -04:00
optionally create a pending queue entry. Returns a flash message string.
queue=False: skips queueing and records the change directly in
.dashboard-done so it appears in Change History without a pending step.
2026-05-25 16:07:21 -04:00
"""
entry_uuid = str(uuid.uuid4())
entry_ts = int(datetime.now().timestamp())
current_user = session.get('email_address', 'unknown')
depends_on = _find_snapshot_dependencies(path, key)
os.makedirs(SNAPSHOTS_DIR, exist_ok=True)
snapshot = {
'uuid': entry_uuid,
'ts': entry_ts,
'cmd': cmd,
'user': current_user,
'operation': operation,
'description': description,
'path': path,
'key': str(key),
'before': before,
'after': after,
'depends_on': depends_on,
}
with open(os.path.join(SNAPSHOTS_DIR, f'{entry_ts}-{entry_uuid}.json'), 'w') as f:
json.dump(snapshot, f, indent=2)
2026-05-25 22:44:37 -04:00
save_config(new_config)
2026-05-25 16:07:21 -04:00
if not queue:
2026-05-25 20:46:17 -04:00
with open(DASHBOARD_DONE, 'a') as f:
f.write(f'{entry_uuid} {entry_ts}\n')
return 'Saved.'
2026-05-25 16:07:21 -04:00
if _apply_changes_immediately():
with open(DASHBOARD_QUEUE, 'a') as f:
f.write(f'{entry_uuid} {entry_ts} [{cmd}] ({current_user})\n')
_trim_if_needed()
else:
_queue_pending_presigned(cmd, entry_uuid, entry_ts)
return _build_timing_msg(entry_ts, cmd)
2026-05-25 21:49:47 -04:00
# Misc ==============================================================
2026-05-25 16:07:21 -04:00
2026-05-17 03:26:01 -04:00
def run_apply():
try:
subprocess.run(
['python3', f'{CONFIGS_DIR}/core.py', '--apply'],
capture_output=True, timeout=30
)
except Exception:
pass
def run_update_blocklists():
try:
subprocess.run(
['python3', f'{CONFIGS_DIR}/core.py', '--update-blocklists'],
capture_output=True, timeout=120
)
except Exception:
pass