Q5: Answer
هذا الالتزام موجود في:
13
q5-mithal-monitor/Dockerfile
Normal file
13
q5-mithal-monitor/Dockerfile
Normal file
@@ -0,0 +1,13 @@
|
||||
FROM python:3.9-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN pip install requests
|
||||
|
||||
COPY monitor.py dashboard.html ./
|
||||
|
||||
RUN echo "[]" > metrics.json
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD nohup python monitor.py & python -m http.server 80
|
||||
184
q5-mithal-monitor/dashboard.html
Normal file
184
q5-mithal-monitor/dashboard.html
Normal file
@@ -0,0 +1,184 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>mithal.space - Status Dashboard</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background-color: #f4f7f6;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
color: #333;
|
||||
}
|
||||
.container {
|
||||
max-width: 1000px;
|
||||
margin: auto;
|
||||
}
|
||||
h1 {
|
||||
text-align: center;
|
||||
color: #2c3e50;
|
||||
}
|
||||
.cards {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.card {
|
||||
background: #fff;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
width: 48%;
|
||||
text-align: center;
|
||||
}
|
||||
.card h2 {
|
||||
margin: 0;
|
||||
font-size: 1.2rem;
|
||||
color: #7f8c8d;
|
||||
}
|
||||
.card .value {
|
||||
font-size: 2.5rem;
|
||||
font-weight: bold;
|
||||
color: #27ae60;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.chart-container {
|
||||
background: #fff;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
background: #fff;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
th, td {
|
||||
padding: 12px 15px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #ddd;
|
||||
}
|
||||
th {
|
||||
background-color: #2c3e50;
|
||||
color: #fff;
|
||||
}
|
||||
tr:hover {
|
||||
background-color: #f1f1f1;
|
||||
}
|
||||
.status-up { color: #27ae60; font-weight: bold; }
|
||||
.status-down { color: #e74c3c; font-weight: bold; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="container">
|
||||
<h1>mithal.space Monitoring Dashboard</h1>
|
||||
|
||||
<div class="cards">
|
||||
<div class="card">
|
||||
<h2>Uptime (Last 24h)</h2>
|
||||
<div class="value" id="uptime-val">--%</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>SSL Certificate Expiry</h2>
|
||||
<div class="value" id="ssl-val" style="color: #2980b9;">-- Days</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
<h2>Latency (Last Hour)</h2>
|
||||
<canvas id="latencyChart"></canvas>
|
||||
</div>
|
||||
|
||||
<h2>Recent Checks (Last 10)</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Timestamp</th>
|
||||
<th>Status</th>
|
||||
<th>HTTP Latency</th>
|
||||
<th>Search Latency</th>
|
||||
<th>DNS Latency</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="log-body">
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
async function loadDashboard() {
|
||||
try {
|
||||
const response = await fetch('metrics.json');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.length === 0) return;
|
||||
|
||||
const upCount = data.filter(d => d.uptime_status === 'Up').length;
|
||||
const uptimePct = ((upCount / data.length) * 100).toFixed(2);
|
||||
document.getElementById('uptime-val').innerText = uptimePct + '%';
|
||||
|
||||
const latestRecord = data[data.length - 1];
|
||||
document.getElementById('ssl-val').innerText = latestRecord.ssl_days_left + ' Days';
|
||||
|
||||
const lastHourData = data.slice(-60);
|
||||
const labels = lastHourData.map(d => d.timestamp.split(' ')[1]); // Extract time only
|
||||
const latencyData = lastHourData.map(d => d.latency_ms);
|
||||
|
||||
const ctx = document.getElementById('latencyChart').getContext('2d');
|
||||
new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: labels,
|
||||
datasets: [{
|
||||
label: 'Response Time (ms)',
|
||||
data: latencyData,
|
||||
borderColor: '#e67e22',
|
||||
backgroundColor: 'rgba(230, 126, 34, 0.2)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
scales: {
|
||||
y: { beginAtZero: true }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const last10 = data.slice(-10).reverse();
|
||||
let tableRows = '';
|
||||
last10.forEach(row => {
|
||||
const statusClass = row.uptime_status === 'Up' ? 'status-up' : 'status-down';
|
||||
tableRows += `
|
||||
<tr>
|
||||
<td>${row.timestamp}</td>
|
||||
<td class="${statusClass}">${row.uptime_status}</td>
|
||||
<td>${row.latency_ms} ms</td>
|
||||
<td>${row.search_latency_ms} ms</td>
|
||||
<td>${row.dns_latency_ms} ms</td>
|
||||
</tr>
|
||||
`;
|
||||
});
|
||||
document.getElementById('log-body').innerHTML = tableRows;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
document.getElementById('log-body').innerHTML = '<tr><td colspan="5" style="text-align:center; color:red;">No data available yet. Run the Python script first!</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
window.onload = loadDashboard;
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
97
q5-mithal-monitor/monitor.py
Normal file
97
q5-mithal-monitor/monitor.py
Normal file
@@ -0,0 +1,97 @@
|
||||
import requests
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
TARGET_HOST = "mithal.space"
|
||||
TARGET_URL = f"https://{TARGET_HOST}"
|
||||
DATA_FILE = "metrics.json"
|
||||
MAX_RECORDS = 1440
|
||||
|
||||
def get_dns_latency():
|
||||
"""حساب وقت تحليل الـ DNS بالملي ثانية"""
|
||||
start_time = time.time()
|
||||
try:
|
||||
socket.gethostbyname(TARGET_HOST)
|
||||
return round((time.time() - start_time) * 1000, 2)
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def get_ssl_expiry_days():
|
||||
"""التحقق من شهادة SSL وحساب الأيام المتبقية"""
|
||||
try:
|
||||
context = ssl.create_default_context()
|
||||
with socket.create_connection((TARGET_HOST, 443), timeout=5) as sock:
|
||||
with context.wrap_socket(sock, server_hostname=TARGET_HOST) as ssock:
|
||||
ssl_info = ssock.getpeercert()
|
||||
expire_date_str = ssl_info['notAfter']
|
||||
expire_date = datetime.strptime(expire_date_str, "%b %d %H:%M:%S %Y %Z")
|
||||
remaining = expire_date - datetime.utcnow()
|
||||
return remaining.days
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def check_health():
|
||||
"""جمع كل المقاييس المطلوبة"""
|
||||
metrics = {
|
||||
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"uptime_status": "Down",
|
||||
"latency_ms": 0,
|
||||
"ssl_days_left": get_ssl_expiry_days(),
|
||||
"dns_latency_ms": get_dns_latency(),
|
||||
"search_latency_ms": 0
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.get(TARGET_URL, timeout=10)
|
||||
metrics["latency_ms"] = round(response.elapsed.total_seconds() * 1000, 2)
|
||||
if response.status_code == 200:
|
||||
metrics["uptime_status"] = "Up"
|
||||
else:
|
||||
metrics["uptime_status"] = f"Error {response.status_code}"
|
||||
except Exception:
|
||||
metrics["uptime_status"] = "Down"
|
||||
|
||||
try:
|
||||
search_res = requests.get(TARGET_URL, params={"q": "test"}, timeout=10)
|
||||
metrics["search_latency_ms"] = round(search_res.elapsed.total_seconds() * 1000, 2)
|
||||
except Exception:
|
||||
metrics["search_latency_ms"] = 0
|
||||
|
||||
return metrics
|
||||
|
||||
def save_metrics(new_metric):
|
||||
"""حفظ البيانات في ملف JSON"""
|
||||
data = []
|
||||
if os.path.exists(DATA_FILE):
|
||||
try:
|
||||
with open(DATA_FILE, "r") as f:
|
||||
data = json.load(f)
|
||||
except json.JSONDecodeError:
|
||||
data = []
|
||||
|
||||
data.append(new_metric)
|
||||
|
||||
if len(data) > MAX_RECORDS:
|
||||
data = data[-MAX_RECORDS:]
|
||||
|
||||
with open(DATA_FILE, "w") as f:
|
||||
json.dump(data, f, indent=4)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"Starting monitoring for {TARGET_HOST}... (Press Ctrl+C to stop)")
|
||||
while True:
|
||||
try:
|
||||
metrics = check_health()
|
||||
save_metrics(metrics)
|
||||
print(f"[{metrics['timestamp']}] Logged: {metrics['uptime_status']} | Latency: {metrics['latency_ms']}ms | SSL: {metrics['ssl_days_left']} days left")
|
||||
time.sleep(60)
|
||||
except KeyboardInterrupt:
|
||||
print("\nMonitoring stopped by user.")
|
||||
break
|
||||
except Exception as e:
|
||||
print(f"Unexpected error: {e}")
|
||||
time.sleep(60)
|
||||
المرجع في مشكلة جديدة
حظر مستخدم