#!/usr/bin/env python3
"""
panel-usage — how much each site uses: CPU and memory (from the PHP request log), visitors and bots
(from the web server logs), disk and database size. Writes /var/lib/panel/usage.json for the Sites page.
Runs every 10 minutes (panel-usage.timer). Disk and database sizes are refreshed once a day.

  panel-usage            refresh (what the timer runs)
  panel-usage --print    refresh and print a table
"""
import glob, gzip, json, os, re, subprocess, sys, time

SITES = '/var/log/httpd/sites/%s.access.log'
VHOSTS = '/etc/panel/vhosts'
OUT = '/var/lib/panel/usage.json'
DISK = '/var/lib/panel/usage-disk.json'
DAY = 86400
now = time.time(); since = now - DAY
BOT = re.compile(r'bot|crawl|spider|slurp|gpt|claude|perplexity|bytespider|semrush|ahrefs|petal|facebookexternalhit|meta-external|python-requests|curl/|wget', re.I)
STATIC = re.compile(r'\.(css|js|mjs|png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|map|mp4|webm|mp3|txt|xml)$', re.I)
MON = {m: i for i, m in enumerate('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(), 1)}


def sites():
    out = {}
    for f in glob.glob(VHOSTS + '/*.conf'):
        d = os.path.basename(f)[:-5]; root = ''
        for line in open(f, errors='replace'):
            line = line.strip()
            if line.startswith('DocumentRoot '): root = line.split(None, 1)[1]; break
        out[d] = root
    return out


def opener(f): return gzip.open(f, 'rt', errors='replace') if f.endswith('.gz') else open(f, errors='replace')


STATE = '/var/lib/panel/usage-state.json'   # how far each log has been read + hourly totals per site


def read_new(st, f):
    """Lines added to log f since the last run (follows rotation by inode)."""
    try: sb = os.stat(f)
    except OSError: return []
    pos = st['pos'].get(f)
    off = pos[1] if pos and pos[0] == sb.st_ino and sb.st_size >= pos[1] else 0
    if not pos: off = max(0, sb.st_size - 64 * 1024 * 1024)   # first run: at most the last 64 MB of a log
    with open(f, 'rb') as fh:
        fh.seek(off); data = fh.read(); end = fh.tell()
    cut = data.rfind(b'\n') + 1   # leave a half-written last line for the next run
    st['pos'][f] = [sb.st_ino, off + cut]
    return data[:cut].decode('utf-8', 'replace').splitlines()


def bucket(st, kind, site, ts):
    h = str(int(ts // 3600 * 3600))
    return st[kind].setdefault(site, {}).setdefault(h, [0, 0, 0, 0, 0])


def collect(names, st):
    """Add the new lines of the PHP request log and every site's access log to the hourly totals."""
    for f in glob.glob('/var/log/panel/usage/php-*.log'):
        for line in read_new(st, f):
            p = line.split()
            if len(p) < 5: continue
            try: ts = int(p[0]); ms = float(p[2]); cpu = float(p[3].rstrip('%')); kb = int(p[4])
            except ValueError: continue
            h = p[1].lower().split(':')[0]
            if h.startswith('www.'): h = h[4:]
            if h not in names: h = '(other)'
            b = bucket(st, 'php', h, ts)   # requests, cpu ms, busy ms, peak kb, slow
            b[0] += 1; b[1] += ms * cpu / 100; b[2] += ms; b[3] = max(b[3], kb); b[4] += ms > 1000
            st['first'] = min(st.get('first') or ts, ts)
    rx = re.compile(r'\[(\d\d)/(\w{3})/(\d{4}):(\d\d):(\d\d):(\d\d) [^\]]*\] "(?:[A-Z]+) (\S+)[^"]*" \d+ (\S+) "[^"]*" "([^"]*)"')
    for d in names:
        for line in read_new(st, SITES % d):
            m = rx.search(line)
            if not m: continue
            ts = time.mktime((int(m[3]), MON.get(m[2], 1), int(m[1]), int(m[4]), int(m[5]), int(m[6]), 0, 0, 0)) - time.timezone
            b = bucket(st, 'web', d, ts)   # requests, pages, bot pages, bytes
            b[0] += 1
            if m[8].isdigit(): b[3] += int(m[8])
            if not STATIC.search(m[7].split('?')[0]):
                b[1] += 1; b[2] += bool(BOT.search(m[9]))
    # keep 25 hours
    for kind in ('php', 'web'):
        for site in list(st[kind]):
            st[kind][site] = {h: v for h, v in st[kind][site].items() if int(h) >= now - DAY - 3600}
            if not st[kind][site]: del st[kind][site]


def totals(st, kind, site):
    t = [0, 0, 0, 0, 0]
    for h, v in st[kind].get(site, {}).items():
        if int(h) + 3600 <= since: continue
        for i, x in enumerate(v): t[i] = max(t[i], x) if (kind == 'php' and i == 3) else t[i] + x
    return t


def disk_usage(names):
    """Folder size and database size per site, refreshed once a day (it reads the whole disk)."""
    try:
        old = json.load(open(DISK))
        if now - old.get('at', 0) < DAY and set(old.get('sites', {})) >= set(names): return old['sites']
    except (OSError, ValueError): pass
    dbsize = {}
    try:
        r = subprocess.run(['mysql', '-N', '-e', "select table_schema, sum(data_length+index_length) from information_schema.tables "
                            "where table_schema not in ('mysql','sys','information_schema','performance_schema') group by 1"],
                           capture_output=True, text=True, timeout=120).stdout
        for line in r.splitlines():
            k, v = line.split('\t'); dbsize[k] = int(float(v or 0))
    except Exception: pass
    out = {}
    for d, root in names.items():
        e = {'files': 0, 'dbs': [], 'db_bytes': 0}
        if root and os.path.isdir(root) and not root.rstrip('/').endswith('/public_html'):   # the main folder holds every site: skip
            try:
                r = subprocess.run(['ionice', '-c3', 'nice', '-n19', 'du', '-sb', root], capture_output=True, text=True, timeout=600).stdout
                e['files'] = int(r.split()[0])
            except Exception: pass
            if dbsize:   # databases named in the site's own code/config (same rule as panel-move-site)
                try:
                    r = subprocess.run(['ionice', '-c3', 'nice', '-n19', 'grep', '-rhowF', '-f', '/dev/stdin', root, '--include=*.php',
                                        '--include=.env', '--include=*.ini', '--include=*.json'], input='\n'.join(dbsize),
                                       capture_output=True, text=True, timeout=300).stdout
                    found = sorted(set(r.split()))
                    lines = subprocess.run(['grep', '-rhwF', '-f', '/dev/stdin', root, '--include=*.php', '--include=.env', '--include=*.ini'],
                                           input='\n'.join(found), capture_output=True, text=True, timeout=300).stdout.splitlines() if found else []
                    e['dbs'] = [db for db in found if any(db in l and not re.search(r'user|login', l, re.I) for l in lines)]
                    e['db_bytes'] = sum(dbsize.get(db, 0) for db in e['dbs'])
                except Exception: pass
        out[d] = e
    tmp = DISK + '.tmp'; json.dump({'at': now, 'sites': out}, open(tmp, 'w')); os.chmod(tmp, 0o644); os.replace(tmp, DISK)
    return out


def main():
    names = sites()
    try: st = json.load(open(STATE))
    except (OSError, ValueError): st = {}
    st.setdefault('pos', {}); st.setdefault('php', {}); st.setdefault('web', {})
    collect(names, st)
    tmp = STATE + '.tmp'; json.dump(st, open(tmp, 'w')); os.replace(tmp, STATE)
    first = max(st.get('first') or now, since)
    php = {d: dict(zip(('php', 'cpu_s', 'busy_s', 'mem_kb', 'slow'), t)) for d in list(names) + ['(other)'] for t in [totals(st, 'php', d)]}
    for v in php.values(): v['cpu_s'] /= 1000; v['busy_s'] /= 1000
    web = {d: dict(zip(('req', 'pages', 'bot_pages', 'bytes'), totals(st, 'web', d))) for d in names}
    disk = disk_usage(names)
    cores = os.cpu_count() or 1
    window = max(60, now - first)   # the PHP log only covers what has been logged so far (less than 24 h at first)
    res = {}
    for d in names:
        p = php.get(d, {}); w = web.get(d, {}); k = disk.get(d, {})
        res[d] = {'php': p.get('php', 0), 'cpu_s': round(p.get('cpu_s', 0), 3), 'busy_s': round(p.get('busy_s', 0), 1),
                  'cpu_pct': round(100 * p.get('cpu_s', 0) / (cores * window), 3 if 100 * p.get('cpu_s', 0) / (cores * window) < 0.1 else 2), 'mem_mb': round(p.get('mem_kb', 0) / 1024),
                  'slow': p.get('slow', 0), 'req': w.get('req', 0), 'pages': w.get('pages', 0), 'bot_pages': w.get('bot_pages', 0),
                  'bytes': w.get('bytes', 0), 'files': k.get('files', 0), 'dbs': k.get('dbs', []), 'db_bytes': k.get('db_bytes', 0)}
    total_cpu = sum(v['cpu_s'] for v in php.values())
    data = {'at': int(now), 'cores': cores, 'php_window_s': int(window), 'php_cpu_pct': round(100 * total_cpu / (cores * window), 1),
            'disk_at': int(json.load(open(DISK)).get('at', 0)) if os.path.exists(DISK) else 0, 'sites': res}
    tmp = OUT + '.tmp'; json.dump(data, open(tmp, 'w')); os.chmod(tmp, 0o644); os.replace(tmp, OUT)
    if '--print' in sys.argv:
        print('PHP used %.1f%% of %d cores over the last %.1f h' % (data['php_cpu_pct'], cores, window / 3600))
        print('%-24s %6s %8s %7s %8s %6s %8s %8s' % ('site', 'CPU%', 'pages', 'bots%', 'PHP req', 'memMB', 'files', 'db'))
        for d, v in sorted(res.items(), key=lambda x: -x[1]['cpu_s'])[:25]:
            print('%-24s %6.2f %8d %6.0f%% %8d %6d %7.0fM %7.0fM' % (d[:24], v['cpu_pct'], v['pages'], 100 * v['bot_pages'] / max(1, v['pages']),
                  v['php'], v['mem_mb'], v['files'] / 1e6, v['db_bytes'] / 1e6))


if __name__ == '__main__':
    os.nice(10); main()
