File size: 3,236 Bytes
67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 3da7fc2 67a97b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import requests
import time
import socket
class SystemMonitor:
_region_cache = None
_engine_version = "AutoAlt Neural v2"
@staticmethod
def get_region():
"""
Fetches the server's current region/city using a GeoIP service.
Cached for the lifetime of the application to avoid rate limits.
"""
if SystemMonitor._region_cache:
return SystemMonitor._region_cache
try:
# high-performance, free GeoIP API
response = requests.get("http://ip-api.com/json", timeout=3)
if response.status_code == 200:
data = response.json()
# User example showed "Frankfurt", which is a city.
# We can combine City, Country for clarity or just City.
city = data.get("city", "Unknown")
country = data.get("countryCode", "")
# Check for cloud provider hints in ISP if needed, but City is usually what people mean by 'Region' in this context
region = f"{city}, {country}" if country else city
SystemMonitor._region_cache = region
return region
except Exception as e:
print(f"Region detection failed: {e}")
return "Unknown (Network Restricted)"
return "Unknown"
@staticmethod
def get_latency(target_url=None):
"""
Calculates the system's network latency by timing a request to a reliable backbone or specific target.
Returns latency in milliseconds (int).
"""
# Default to the user's preferred check URL if no specific domain is given
url_to_check = target_url if target_url else "https://dev.autoalt.ai/"
try:
# Measure reliable external connection time
start = time.time()
# Fast HEAD request
requests.head(url_to_check, timeout=3)
end = time.time()
# Convert to ms and round
latency_ms = int((end - start) * 1000)
return latency_ms
except Exception:
# Retry with a socket method if HTTP fails (only for default check)
if not target_url:
try:
start = time.time()
socket.create_connection(("8.8.8.8", 53), timeout=2)
end = time.time()
return int((end - start) * 1000)
except:
return 999
return 999 # High latency/timeout indicator
@staticmethod
def get_status(target_url=None):
"""
Simple self-diagnostic status.
"""
# If we can reach external network, we are operational.
latency = SystemMonitor.get_latency(target_url)
if latency < 999:
return "operational"
return "degraded_connectivity"
@staticmethod
def get_system_stats(target_url=None):
return {
"region": SystemMonitor.get_region(),
"latency": SystemMonitor.get_latency(target_url),
"status": SystemMonitor.get_status(target_url),
"engine": SystemMonitor._engine_version
}
|