import requests
import time
import datetime
import subprocess

# CONFIGURA TU URL
URL = "https://backtestingmarket.com"
LOG_FILE = "/var/www/html/process/logs/apache_watchdog.log"
CHECK_INTERVAL = 60  # cada 1 minuto
COOLDOWN_SECONDS = 60  # tiempo mínimo entre reinicios

last_restart = 0  # timestamp del último reinicio

def log(msg):
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(LOG_FILE, "a") as f:
        f.write(f"[{timestamp}] {msg}\n")
    print(f"[{timestamp}] {msg}")

def is_site_up():
    try:
        response = requests.get(URL, timeout=15)  # ⬅ Timeout extendido
        if response.status_code == 200:
            log("STATUS: OK")
            return True
        else:
            log(f"STATUS: ERROR - HTTP {response.status_code}")
            return False
    except Exception as e:
        log(f"STATUS: ERROR - {e}")
        return False

def capture_system_snapshot():
    log("INFO: Capturing system snapshot...")

    try:
        # 1. Top CPU processes
        top_cpu = subprocess.check_output(
            ["ps", "-eo", "pid,ppid,cmd,%mem,%cpu,stat", "--sort=-%cpu"], text=True
        )
        log("TOP PROCESSES:\n" + "\n".join(top_cpu.splitlines()[:15]))

        # 2. Apache error log (últimas 20 líneas)
        apache_log = subprocess.run(
            "tail -n 20 /var/log/apache2/error.log",
            shell=True, text=True, capture_output=True
        )
        log("APACHE ERROR LOG:\n" + apache_log.stdout.strip())

        # 3. Free memory
        mem = subprocess.run("free -m", shell=True, text=True, capture_output=True)
        log("MEMORY USAGE:\n" + mem.stdout.strip())

        # 4. Disk usage
        disk = subprocess.run("df -h", shell=True, text=True, capture_output=True)
        log("DISK USAGE:\n" + disk.stdout.strip())

        # 5. Load average
        load = subprocess.run("uptime", shell=True, text=True, capture_output=True)
        log("LOAD AVERAGE:\n" + load.stdout.strip())

        # 6. Últimos eventos del sistema
        journal = subprocess.run(
            "journalctl -xe -n 20",
            shell=True, text=True, capture_output=True
        )
        log("JOURNAL (últimos eventos):\n" + journal.stdout.strip())

        # 7. lsof - apache2
        lsof_apache = subprocess.run(
            "lsof -c apache2 | head -n 20",
            shell=True, text=True, capture_output=True
        )
        log("OPEN FILES (apache2):\n" + lsof_apache.stdout.strip())

        # 8. lsof - python3
        lsof_python = subprocess.run(
            "lsof -c python3 | head -n 20",
            shell=True, text=True, capture_output=True
        )
        log("OPEN FILES (python3):\n" + lsof_python.stdout.strip())

    except Exception as e:
        log(f"ERROR while capturing snapshot: {e}")


def restart_apache():
    global last_restart
    now = time.time()
    if now - last_restart < COOLDOWN_SECONDS:
        log("ACTION: Skipping restart (cooldown in effect).")
        return

    log("ACTION: Apache appears down. Restarting Apache...")
    try:
        subprocess.run(["sudo", "service", "apache2", "restart"], check=True)
        log("ACTION: Apache restarted successfully.")
        last_restart = now
    except subprocess.CalledProcessError as e:
        log(f"ACTION: Failed to restart Apache - {e}")

if __name__ == "__main__":
    while True:
        if not is_site_up():
            capture_system_snapshot()
            restart_apache()
        time.sleep(CHECK_INTERVAL)

#nohup /bin/python3 -u /var/www/html/process/monitor_apache.py > /var/www/html/process/logs/apache_watchdog.log 2>&1 &