#!/usr/bin/env python3
"""
panel-site-cpu — notes in /var/log/panel/busy.log when one site uses a large share of the server's CPU.
Run every 5 minutes (by panel-metrics). Looks at the PHP requests of the last 5 minutes (/var/log/panel/usage/php-*.log)
and writes one line per site that used 20% or more of all CPU cores, with its request count, CPU per request and who the
visitors were (crawlers / browsers, from the site's access log). Shown in the panel under Logs → Busy sites.
"""
import collections, glob, os, re, subprocess, sys, time

WINDOW = 300; SHARE = 20.0
LOG = '/var/log/panel/busy.log'
BOTS = re.compile(r'(GPTBot|OAI-SearchBot|ChatGPT-User|ClaudeBot|Claude-SearchBot|Applebot|Amazonbot|Bytespider|meta-externalagent|CCBot|PerplexityBot|'
                  r'ElevenlabsCrawler|PetalBot|SemrushBot|AhrefsBot|DotBot|MJ12bot|YandexBot|Googlebot|bingbot|DuckDuckBot|Baiduspider|facebookexternalhit|'
                  r'DataForSeoBot|GoogleOther|python-requests|Go-http-client|curl)', re.I)

def tail(path, n):
    try: return subprocess.run(['tail', '-n', str(n), path], capture_output=True, text=True, errors='replace').stdout.splitlines()
    except Exception: return []

def main():
    now = time.time(); cores = os.cpu_count() or 1
    req = collections.Counter(); cpu = collections.Counter(); wall = collections.Counter()
    for f in glob.glob('/var/log/panel/usage/php-*.log'):
        for line in tail(f, 60000):
            p = line.split()
            if len(p) < 4: continue
            try: ts = int(p[0]); ms = float(p[2]); pc = float(p[3])
            except ValueError: continue
            if ts < now - WINDOW: continue
            h = p[1].lower(); h = h[4:] if h.startswith('www.') else h
            req[h] += 1; cpu[h] += ms * pc / 100000.0; wall[h] += ms / 1000.0
    out = []
    for h, c in cpu.most_common(5):
        share = 100.0 * c / (cores * WINDOW)
        if share < SHARE: break
        who = collections.Counter(); n = 0
        t0 = time.strftime('%d/%b/%Y:%H:%M', time.gmtime(now - WINDOW))
        for line in tail('/var/log/httpd/sites/%s.access.log' % h, 20000):
            m = re.search(r'\[(\d\d/\w{3}/\d{4}:\d\d:\d\d)', line)
            if not m or time.strptime(m.group(1), '%d/%b/%Y:%H:%M') < time.strptime(t0, '%d/%b/%Y:%H:%M'): continue
            ua = line.rsplit('"', 2)[-2] if line.count('"') >= 6 else ''
            b = BOTS.search(ua); who[b.group(1) if b else 'browsers / other'] += 1; n += 1
        top = ', '.join('%s %d%%' % (k, round(100.0 * v / n)) for k, v in who.most_common(4)) if n else 'no access log lines'
        out.append('%s  %s used %.0f%% of the CPU for 5 minutes: %d PHP requests, %.2f s CPU and %.1f s waiting each. Visitors: %s'
                   % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(now)), h, share, req[h], c / req[h], wall[h] / req[h], top))
    if out:
        with open(LOG, 'a') as fh: fh.write('\n'.join(out) + '\n')
        os.chmod(LOG, 0o640)
    if '--print' in sys.argv:
        for h, c in cpu.most_common(8): print('%5.1f%%  %6d req  %s' % (100.0 * c / (cores * WINDOW), req[h], h))
        print('\n'.join(out) or '(no site at or above %d%%)' % SHARE)

if __name__ == '__main__':
    main()
