Files
aaPanel/script/node_requests_compat.py
2026-12-02 16:11:08 +08:00

377 lines
17 KiB
Python

"""Compatibility for Node nginx statistics; never replay logs into site_total."""
import collections
import datetime
import glob
import gzip
import hashlib
import json
import os
import re
import shlex
import subprocess
import tempfile
import time
RECORD = re.compile(
r'^\S+ \S+ \S+ \[(\d{2})/([A-Za-z]{3})/(\d{4}):'
r'\d{2}:\d{2}:\d{2} [+-]\d{4}\] "[^"\r\n]*" [1-5]\d{2} (?:\d+|-)'
r'(?:\s|$)')
MONTHS = dict(zip('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(), range(1, 13)))
def atomic_write(path, content):
os.makedirs(os.path.dirname(path), exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.node-requests-', dir=os.path.dirname(path))
try:
with os.fdopen(fd, 'wb') as stream:
if os.path.exists(path):
os.chmod(temporary, os.stat(path).st_mode & 0o777)
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def log_cut_paths(name):
import public
roots = set()
with public.M('crontab') as database:
tasks = database.where('sType=?', ('logs',)).select()
if not isinstance(tasks, list):
raise RuntimeError('Cannot read log rotation tasks: {}'.format(tasks))
for task in tasks:
target = task.get('sName') or ''
if target != name and not target.startswith('ALL'):
continue
root = task.get('log_cut_path') or ''
# Some versions persist this option only in the generated cron script.
echo = task.get('echo') or ''
if echo and os.path.basename(echo) == echo:
content = public.readFile(public.get_setup_path() + '/cron/' + echo) or ''
for line in content.splitlines():
if '/panel/script/logsBackup ' not in line:
continue
args = shlex.split(line)
command = public.get_panel_path() + '/script/logsBackup'
if command in args:
index = args.index(command)
if len(args) > index + 3 and args[index + 1] == target:
root = args[index + 3]
if os.path.isabs(root):
roots.add(root)
return roots
def log_files(log_path, name, first_date=None, cut_paths=()):
# Both versions of logsBackup are supported. Do not include Node stdout logs.
paths = glob.glob(glob.escape(log_path) + '_*.log*')
paths += [log_path]
for root in {os.path.dirname(log_path)} | set(cut_paths):
history = os.path.join(root, 'history_backups', name)
history = history.replace('history_backups/history_backups/', 'history_backups/')
paths += glob.glob(os.path.join(glob.escape(history), glob.escape(name) + '_access_*.log*'))
unique, inodes = [], set()
available = set(paths)
for path in sorted(available):
# logsBackup names record the rotation date, not the records' date.
# Older archives cannot contain this window; newer ones may span days.
rotated = re.search(r'_(\d{4}-\d{2}-\d{2})_\d{6}\.log(?:\.gz)?$', path)
if path != log_path and not rotated:
continue
if first_date and rotated and rotated.group(1) < first_date.isoformat():
continue
if not os.path.isfile(path) or (path.endswith('.gz') and path[:-3] in available):
continue
st = os.stat(path)
inode = (st.st_dev, st.st_ino)
if inode not in inodes:
unique.append(path)
inodes.add(inode)
return unique
def count_requests(paths, last_date, today, first_date=None):
first_date = first_date or today - datetime.timedelta(days=6)
counts = collections.Counter()
seen = set()
for path in paths:
opener = gzip.open if path.endswith('.gz') else open
file_counts = collections.Counter()
digest = hashlib.sha256()
# A corrupt/missing rotated file aborts this site's pass, rather than
# committing a silently incomplete snapshot. A later pass can retry.
with opener(path, 'rb') as stream:
for raw in stream:
digest.update(raw)
line = raw.decode('utf-8', errors='replace')
match = RECORD.match(line)
if not match:
continue
day, month, year = match.groups()
try:
date = datetime.date(int(year), MONTHS[month], int(day))
except (KeyError, ValueError):
continue
if first_date <= date < today and date <= last_date:
file_counts[date.isoformat()] += 1
# Compare uncompressed contents, including copies with different names.
fingerprint = digest.digest()
if fingerprint not in seen:
counts.update(file_counts)
seen.add(fingerprint)
return counts
def backfill(site_dir, counts):
for day, count in sorted(counts.items()):
path = os.path.join(site_dir, day + '.json')
original = None
if os.path.exists(path):
with open(path, 'rb') as stream:
original = stream.read()
data = json.loads(original)
if not isinstance(data, dict):
raise ValueError('Invalid statistics object: ' + path)
else:
data = {}
existing = data.get('requests', 0)
if not isinstance(existing, (int, float)) or isinstance(existing, bool) or existing < 0:
raise ValueError('Invalid requests: ' + path)
# Rotations can already have expired. The available count is a lower
# bound, not a number to add to an overlapping collector count.
recovered = max(existing, count)
if recovered != existing or original is None:
data['requests'] = recovered
# Detect a concurrent change before replacing this finalized day.
if original is not None:
with open(path, 'rb') as stream:
if stream.read() != original:
raise RuntimeError('Statistics changed during backfill: ' + path)
atomic_write(path, json.dumps(data, ensure_ascii=False).encode('utf-8'))
def sync_site_total(name):
import public
panel = public.get_panel_path()
setup = public.get_setup_path()
binary = setup + '/site_total/site_total'
if (public.GetWebServer() != 'nginx'
or os.path.exists(panel + '/plugin/monitor/info.json')
or os.path.exists(panel + '/data/site_total_uninstall.pl')
or not os.path.isfile(binary)):
return False
path = panel + '/vhost/nginx/extension/' + name + '/site_total.conf'
if os.path.isfile(path):
return False
try:
# Use the collector's own configuration generator, not a second template.
subprocess.run([binary, '--reload'], cwd=os.path.dirname(binary),
check=True, capture_output=True, timeout=30)
deadline = time.monotonic() + 30
while not os.path.isfile(path):
if time.monotonic() >= deadline:
raise RuntimeError('site_total extension was not generated for ' + name)
time.sleep(0.2)
except Exception:
# Reuse discovery retry when creation fails before a site marker exists.
# Generation may have written the extension before reporting failure.
atomic_write(panel + '/data/node_requests_compat/' + name + '.reload', b'1')
atomic_write(panel + '/data/node_requests_compat/retry', b'1')
raise
return True
def repair_config(path, name, panel_path, nginx, extension):
with open(path, 'rb') as stream:
original = stream.read()
config = original.decode('utf-8')
include = panel_path + '/vhost/nginx/extension/' + name + '/*.conf'
pattern = r'^\s*include\s+[\"\']?' + re.escape(include) + r'[\"\']?\s*;'
ext_dir = os.path.dirname(include)
if os.path.exists(ext_dir) and not os.path.isdir(ext_dir):
raise ValueError('Invalid extension directory: ' + ext_dir)
matches = list(re.finditer(pattern, config, re.M))
updated = config
if not matches:
updated = extension.set_extension_by_config(name, config)
else:
for match in reversed(matches[1:]):
updated = updated[:match.start()] + updated[match.end():]
if not re.search(pattern, updated, re.M):
raise ValueError('Cannot locate Node server block: ' + path)
with open(path, 'rb') as stream:
if stream.read() != original:
raise RuntimeError('Node configuration changed during repair: ' + path)
changed = updated != config
if changed:
atomic_write(path, updated.encode('utf-8'))
reload_path = panel_path + '/data/node_requests_compat/' + name + '.reload'
if changed or not os.path.isfile(ext_dir + '/site_total.conf'):
# File existence does not prove a previous nginx reload succeeded.
atomic_write(reload_path, b'1')
reload_started = False
try:
synced = sync_site_total(name)
if not changed and not synced and not os.path.exists(reload_path):
return False
subprocess.run([nginx, '-t'], check=True, capture_output=True, timeout=30)
reload_started = True
subprocess.run([nginx, '-s', 'reload'], check=True, capture_output=True, timeout=30)
if os.path.exists(reload_path):
os.unlink(reload_path)
except Exception as exc:
# Restore only our own edit. Never overwrite an intervening user edit.
with open(path, 'rb') as stream:
unchanged = stream.read() == updated.encode('utf-8')
if changed and unchanged:
atomic_write(path, original)
# A timed-out signal command has an uncertain outcome. Only this
# case needs a tested reload of the restored configuration.
if reload_started and isinstance(exc, subprocess.TimeoutExpired):
subprocess.run([nginx, '-t'], check=True, capture_output=True, timeout=30)
subprocess.run([nginx, '-s', 'reload'], check=True, capture_output=True, timeout=30)
# A failed -t never reloads. A rejected reload leaves the master running
# its previous configuration; do not send another unconditional reload.
raise
return True
def run(pending_only=False):
import fcntl
import public
state_dir = public.get_panel_path() + '/data/node_requests_compat'
os.makedirs(state_dir, exist_ok=True)
# Both startup and the existing periodic task share this process-level lock.
with open(state_dir + '/task.lock', 'a') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return
retry_path = state_dir + '/retry'
running_path = state_dir + '/retry_running'
retry = os.path.exists(retry_path) or os.path.exists(running_path)
if not pending_only or retry:
# Consume only this pass's notification. Concurrent creation/save
# failures write retry, which this pass must never clear.
if os.path.exists(retry_path):
os.replace(retry_path, running_path)
else:
atomic_write(running_path, b'1')
if _run(pending_only=False):
os.unlink(running_path)
else:
_run(pending_only=True)
def _run(pending_only=False):
import public
from mod.base.web_conf.server_extension import NginxExtension
panel = public.get_panel_path()
setup = public.get_setup_path()
nginx = setup + '/nginx/sbin/nginx'
# monitor owns a different statistics source; only migrate free site_total.
if (public.GetWebServer() != 'nginx'
or os.path.exists(panel + '/plugin/monitor/info.json')
or os.path.exists(panel + '/data/site_total_uninstall.pl')):
return True
if not os.path.isfile(nginx) or not os.path.isdir(setup + '/site_total/data/total'):
return False
state_dir = panel + '/data/node_requests_compat'
today = datetime.date.today()
window_start = today - datetime.timedelta(days=6)
if pending_only:
# Only inspect tiny migration markers; never scan logs unless a date is due.
due = False
for marker in glob.glob(state_dir + '/*.json'):
try:
with open(marker, encoding='utf-8') as stream:
state = json.load(stream)
pending = state.get('pending_date') or state.get('completed') or state.get('last_date')
if not state.get('complete') and pending and pending < today.isoformat():
due = True
break
except (OSError, ValueError) as exc:
public.print_log('Node requests compatibility marker [{}]: {}'.format(marker, exc))
continue
if not due:
return True
os.makedirs(state_dir, exist_ok=True)
with public.M('sites') as database:
sites = database.where('project_type=?', ('Node',)).field('id,name,project_type,project_config').select()
if not isinstance(sites, list):
raise RuntimeError('Cannot read Node sites: {}'.format(sites))
succeeded = True
for site in sites:
name = site['name']
try:
if not name or os.path.basename(name) != name or name in ('.', '..'):
continue
config = json.loads(site.get('project_config') or '{}')
if not config.get('bind_extranet') or not config.get('domains'):
continue
path = panel + '/vhost/nginx/node_' + name + '.conf'
if not os.path.isfile(path):
continue
state_path = state_dir + '/' + str(site['id']) + '.json'
state = None
if os.path.exists(state_path):
with open(state_path, encoding='utf-8') as stream:
state = json.load(stream)
if state.get('name') != name:
raise ValueError('Site identity changed')
# The previous implementation prematurely completed this date.
legacy_date = state.get('completed') or state.get('last_date')
if not state.get('complete') and not state.get('pending_date') and legacy_date:
state = {'name': name, 'pending_date': legacy_date, 'complete': False}
atomic_write(state_path, json.dumps(state).encode('utf-8'))
if pending_only and (state is None or state.get('complete')):
continue
if not pending_only:
repair_config(path, name, panel, nginx, NginxExtension)
if state and state.get('complete'):
continue
if state and state['pending_date'] >= today.isoformat():
continue
pending = state['pending_date'] if state else today.isoformat()
if pending < window_start.isoformat():
state['complete'] = True
state['skipped_date'] = pending
atomic_write(state_path, json.dumps(state).encode('utf-8'))
public.print_log('Node requests [{}]: pending date {} outside seven-day window'.format(name, pending))
continue
with open(path, encoding='utf-8') as stream:
conf = stream.read()
logs = re.findall(r'^\s*access_log\s+(?:"([^"\n]+)"|([^\s;]+))', conf, re.M)
paths = {a or b for a, b in logs if (a or b).startswith('/')}
if len(paths) != 1:
raise ValueError('Expected one ordinary Node access log: ' + path)
first_date = datetime.date.fromisoformat(pending) if state else window_start
counts = count_requests(log_files(paths.pop(), name, first_date, log_cut_paths(name)),
datetime.date.fromisoformat(pending), today, first_date)
backfill(setup + '/site_total/data/total/' + name, counts)
finished = pending < today.isoformat()
state = {'name': name, 'pending_date': pending, 'complete': finished}
if finished and pending not in counts:
state['unrecoverable_date'] = pending
public.print_log('Node requests [{}]: no recoverable log records for {}'.format(name, pending))
atomic_write(state_path, json.dumps(state).encode('utf-8'))
except Exception as exc:
succeeded = False
public.print_log('Node requests compatibility [{}]: {}'.format(name, exc))
return succeeded
if __name__ == '__main__':
import sys
sys.path.insert(0, '/www/server/panel')
sys.path.insert(0, '/www/server/panel/class')
run()