File size: 10,051 Bytes
3d07d57
 
 
 
 
cbe7108
6d97d84
 
cbe7108
 
 
 
 
10f0173
3d07d57
 
 
4bc1bb8
cbe7108
7e70c9c
cbe7108
 
 
 
 
 
 
 
10f0173
cbe7108
10f0173
 
 
 
 
 
 
cbe7108
 
10f0173
 
 
 
 
 
 
 
 
 
 
cbe7108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d97d84
cbe7108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bc1bb8
cbe7108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e02999a
cbe7108
 
 
e02999a
cbe7108
 
e02999a
cbe7108
 
 
1b91366
 
 
cbe7108
 
1b91366
cbe7108
1b91366
cbe7108
1b91366
cbe7108
1b91366
cbe7108
1b91366
cbe7108
 
1b91366
 
 
 
 
 
cbe7108
 
cb429aa
1b91366
cbe7108
 
cb429aa
1b91366
cbe7108
 
 
1b91366
 
cbe7108
 
 
1b91366
 
 
 
cbe7108
1b91366
6d97d84
1b91366
 
 
cb429aa
1b91366
 
3d07d57
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import gradio as gr
import requests
import yaml
import os
import json
from datetime import datetime, timedelta
import threading
import time
import smtplib
from email.message import EmailMessage
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
from string import Template

# Configuration
CONFIG_FILE = "config.yaml"
DATA_FILE = "/data/status.json"
STATUS_HISTORY = 24 * 60 * 60  # 24 hours in seconds

class Monitor:
    def __init__(self):
        self.config = self.load_config()
        self.lock = threading.Lock()
        self.last_status = {}
        self.incidents = defaultdict(list)
        
    def load_config(self):
        # Load and substitute environment variables in the config
        with open(CONFIG_FILE, "r") as f:
            config_content = f.read()
        
        # Replace ${VAR} with environment variables
        config_content = Template(config_content).substitute(os.environ)
        config = yaml.safe_load(config_content)
        
        # Set defaults
        config.setdefault('settings', {})
        config['settings'].setdefault('check_interval_seconds', 300)
        
        # Validate required environment variables
        required_vars = ['SMTP_HOST', 'SMTP_PORT', 'SMTP_USERNAME', 'SMTP_PASSWORD', 'SMTP_FROM']
        for var in required_vars:
            if var not in os.environ:
                raise ValueError(f"Missing required environment variable: {var}")
        
        # Add SMTP credentials from environment
        config['settings']['smtp']['username'] = os.environ['SMTP_USERNAME']
        config['settings']['smtp']['password'] = os.environ['SMTP_PASSWORD']
        
        return config

    def load_data(self):
        try:
            with open(DATA_FILE, "r") as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return {}

    def save_data(self, data):
        with self.lock:
            try:
                with open(DATA_FILE, "w") as f:
                    json.dump(data, f)
            except Exception as e:
                print(f"Error saving data: {e}")

    def check_status(self, endpoint):
        try:
            start = time.time()
            response = requests.get(
                endpoint["url"],
                timeout=10,
                headers={'User-Agent': 'StatusMonitor/1.0'}
            )
            response_time = time.time() - start
            return {
                "status": "UP" if response.ok else "DOWN",
                "response_time": response_time,
                "error": None
            }
        except Exception as e:
            return {"status": "DOWN", "response_time": None, "error": str(e)}

    def send_alert(self, endpoint, result):
        try:
            msg = EmailMessage()
            msg.set_content(
                f"Website {endpoint['name']} is DOWN\n"
                f"URL: {endpoint['url']}\n"
                f"Time: {datetime.now().isoformat()}\n"
                f"Error: {result['error'] or 'Unknown error'}"
            )
            msg['Subject'] = f"ALERT: {endpoint['name']} is DOWN"
            msg['From'] = self.config['settings']['smtp']['from']
            msg['To'] = ", ".join(self.config['settings']['alert_emails'])

            with smtplib.SMTP(
                self.config['settings']['smtp']['host'],
                self.config['settings']['smtp']['port']
            ) as server:
                server.starttls()
                server.login(
                    self.config['settings']['smtp']['username'],
                    self.config['settings']['smtp']['password']
                )
                server.send_message(msg)
        except Exception as e:
            print(f"Failed to send email: {e}")

    def update_status(self):
        endpoints = self.config['endpoints']
        data = self.load_data()
        current_time = datetime.now().isoformat()
        
        for endpoint in endpoints:
            key = endpoint["name"]
            result = self.check_status(endpoint)
            
            # Track incidents
            if result['status'] != self.last_status.get(key, 'UP'):
                if result['status'] == 'DOWN':
                    self.incidents[key].append({
                        'start': current_time,
                        'end': None,
                        'duration': None
                    })
                else:
                    if self.incidents[key] and not self.incidents[key][-1]['end']:
                        self.incidents[key][-1]['end'] = current_time
                        start_time = datetime.fromisoformat(self.incidents[key][-1]['start'])
                        end_time = datetime.fromisoformat(current_time)
                        self.incidents[key][-1]['duration'] = (end_time - start_time).total_seconds()
            
            # Update last status and check if need to send alert
            if self.last_status.get(key) == 'UP' and result['status'] == 'DOWN':
                self.send_alert(endpoint, result)
            self.last_status[key] = result['status']
            
            # Update data
            if key not in data:
                data[key] = []
            data[key].append({
                "timestamp": current_time,
                **result
            })
            
            # Trim old data
            cutoff = datetime.now() - timedelta(seconds=STATUS_HISTORY)
            data[key] = [entry for entry in data[key] 
                        if datetime.fromisoformat(entry['timestamp']) > cutoff]

        self.save_data(data)
        return data

    def get_metrics(self, data):
        metrics = {}
        for name, history in data.items():
            if not history:
                continue
                
            uptime = sum(1 for h in history if h["status"] == "UP") / len(history)
            response_times = [h["response_time"] for h in history if h["response_time"] is not None]
            
            metrics[name] = {
                "uptime": uptime,
                "response_times": response_times,
                "current_status": history[-1]["status"],
                "incidents": self.incidents.get(name, [])
            }
        return metrics

    def create_plots(self, metrics):
        plots = {}
        for name, metric in metrics.items():
            # Response time plot
            plt.figure(figsize=(8, 3))
            plt.plot(metric['response_times'])
            plt.title(f"{name} Response Times")
            plt.ylabel("Seconds")
            plt.xlabel("Last 24h checks")
            plt.tight_layout()
            plots[f"{name}_response"] = plt.gcf()
            plt.close()

            # Uptime plot
            plt.figure(figsize=(3, 3))
            plt.pie([metric['uptime'], 1-metric['uptime']],
                    labels=['Uptime', 'Downtime'],
                    autopct='%1.1f%%',
                    colors=['#4CAF50', '#F44336'])
            plt.title(f"{name} Uptime")
            plots[f"{name}_uptime"] = plt.gcf()
            plt.close()
            
        return plots

monitor = Monitor()

def background_updates():
    while True:
        print("Updating status...")
        monitor.update_status()
        time.sleep(monitor.config['settings']['check_interval_seconds'])

# Start the background thread
threading.Thread(target=background_updates, daemon=True).start()

# Gradio UI
with gr.Blocks(title="Website Status Monitor") as demo:
    gr.Markdown("# 🚦 Website Status Monitor")
    
    # Placeholder for dynamic components
    status_components = []

    def update_ui():
        data = monitor.load_data()
        print("Loaded data:", data)
        metrics = monitor.get_metrics(data)
        print("Metrics:", metrics)
        plots = monitor.create_plots(metrics)
        print("Plots created.")
        
        elements = []
        for name, metric in metrics.items():
            with gr.Row():
                with gr.Column(scale=1):
                    status_color = "#4CAF50" if metric['current_status'] == 'UP' else "#F44336"
                    status_markdown = gr.Markdown(f"### {name}\n"
                               f"**Status:** <span style='color: {status_color}'>"
                               f"{metric['current_status']}</span>\n"
                               f"**Last Response:** {np.mean(metric['response_times'][-5:]):.2f}s\n"
                               f"**24h Uptime:** {metric['uptime']*100:.1f}%")
                    elements.append(status_markdown)
                
                with gr.Column(scale=2):
                    response_plot = gr.Plot(plots[f"{name}_response"], label="Response Times")
                    elements.append(response_plot)
                
                with gr.Column(scale=1):
                    uptime_plot = gr.Plot(plots[f"{name}_uptime"], label="Uptime")
                    elements.append(uptime_plot)
            
            with gr.Accordion("Incident History", open=False):
                if not metric['incidents']:
                    incident_markdown = gr.Markdown("No incidents in past 24 hours")
                    elements.append(incident_markdown)
                else:
                    for incident in metric['incidents'][-5:]:
                        duration = incident['duration'] or "Ongoing"
                        incident_markdown = gr.Markdown(f"**Start:** {incident['start']}\n"
                                    f"**End:** {incident['end'] or 'Still down'}\n"
                                    f"**Duration:** {duration}s\n")
                        elements.append(incident_markdown)
        
        return elements
    
    # Initialize the UI with placeholders
    initial_elements = update_ui()
    status_components.extend(initial_elements)
    
    # Load the UI with the specified components
    demo.load(update_ui, outputs=status_components)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", 7860)))