import os import json import socket import ssl import time import requests from datetime import datetime, timezone TARGET_HOST = "mithal.space" TARGET_URL = f"https://{TARGET_HOST}" SEARCH_URL = f"{TARGET_URL}/search?q=test" METRICS_FILE = os.path.join(os.path.dirname(__file__), "metrics.json") def check_dns(host): start = time.time() try: socket.gethostbyname(host) dns_time = round((time.time() - start) * 1000, 2) return dns_time except Exception: return -1 def check_ssl(host): try: context = ssl.create_default_context() with socket.create_connection((host, 443), timeout=5) as sock: with context.wrap_socket(sock, server_hostname=host) as ssock: cert = ssock.getpeercert() not_after_str = cert['notAfter'] # Parsing SSL expiration date not_after = datetime.strptime(not_after_str, '%b %d %H:%M:%S %Y %Z').replace(tzinfo=timezone.utc) days_left = (not_after - datetime.now(timezone.utc)).days return days_left except Exception: return -1 def check_http(): try: start = time.time() res = requests.get(TARGET_URL, timeout=5) latency = round((time.time() - start) * 1000, 2) return res.status_code, latency, True except Exception: return 0, -1, False def check_search(): try: start = time.time() res = requests.get(SEARCH_URL, timeout=5) search_latency = round((time.time() - start) * 1000, 2) return search_latency except Exception: return -1 def run_monitoring(): dns_time = check_dns(TARGET_HOST) ssl_days = check_ssl(TARGET_HOST) status_code, latency, is_up = check_http() search_time = check_search() metric_entry = { "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"), "uptime": is_up, "status_code": status_code, "latency_ms": latency, "dns_time_ms": dns_time, "ssl_days_left": ssl_days, "search_response_ms": search_time } metrics = [] if os.path.exists(METRICS_FILE): try: with open(METRICS_FILE, "r") as f: metrics = json.load(f) except Exception: metrics = [] metrics.append(metric_entry) metrics = metrics[-100:] # Keep last 100 checks with open(METRICS_FILE, "w") as f: json.dump(metrics, f, indent=2) return metric_entry if __name__ == "__main__": result = run_monitoring() print("Monitoring check complete:", json.dumps(result, indent=2))