rdune71 commited on
Commit
dcaf42a
·
1 Parent(s): 3f5b0f9
modules/visualize_uptime.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # visualize_uptime.py
2
+ #!/usr/bin/env python3
3
+ """
4
+ Script to visualize server uptime from log files
5
+ """
6
+
7
+ import logging
8
+ from modules.visualizer import load_status_log, plot_uptime_trend, plot_uptime_summary, get_uptime_stats
9
+
10
+ # Configure logging
11
+ logging.basicConfig(
12
+ level=logging.INFO,
13
+ format='%(asctime)s - %(levelname)s - %(message)s',
14
+ handlers=[
15
+ logging.FileHandler('visualization.log'),
16
+ logging.StreamHandler()
17
+ ]
18
+ )
19
+
20
+ def main():
21
+ """Main function to generate visualizations"""
22
+ try:
23
+ print("📊 Loading server status log...")
24
+ df = load_status_log()
25
+ print(f"✅ Loaded {len(df)} status records")
26
+
27
+ # Get and display statistics
28
+ stats = get_uptime_stats(df)
29
+ print(f"\n📈 Server Status Statistics:")
30
+ print(f" Total Checks: {stats['total_checks']}")
31
+ print(f" UP Checks: {stats['up_checks']}")
32
+ print(f" DOWN Checks: {stats['down_checks']}")
33
+ print(f" Uptime: {stats['uptime_pct']}%")
34
+ print(f" Downtime: {stats['downtime_pct']}%")
35
+
36
+ # Generate charts
37
+ print("\n🎨 Generating visualizations...")
38
+ trend_chart = plot_uptime_trend(df)
39
+ summary_chart = plot_uptime_summary(df)
40
+
41
+ print(f"\n✅ Visualizations complete!")
42
+ print(f" Trend chart: {trend_chart}")
43
+ print(f" Summary chart: {summary_chart}")
44
+
45
+ except FileNotFoundError:
46
+ print("❌ Log file not found. Run some queries first to generate status logs.")
47
+ logging.warning("Server status log file not found")
48
+ except Exception as e:
49
+ print(f"❌ Error visualizing uptime: {e}")
50
+ logging.error(f"Error in visualization script: {e}", exc_info=True)
51
+
52
+ if __name__ == "__main__":
53
+ main()
modules/visualizer.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modules/visualizer.py
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from datetime import datetime
5
+ import os
6
+ import logging
7
+
8
+ def load_status_log(log_file="server_status_log.csv"):
9
+ """Load server status log from CSV file"""
10
+ if not os.path.exists(log_file):
11
+ raise FileNotFoundError(f"Log file not found: {log_file}")
12
+
13
+ try:
14
+ df = pd.read_csv(log_file, parse_dates=["timestamp"])
15
+ return df
16
+ except Exception as e:
17
+ logging.error(f"Error loading log file: {e}")
18
+ raise
19
+
20
+ def plot_uptime_trend(df, output_file="server_uptime_trend.png"):
21
+ """Plot server uptime trend over time"""
22
+ try:
23
+ # Sort by timestamp
24
+ df = df.sort_values("timestamp")
25
+
26
+ # Convert status to boolean
27
+ df["status_bool"] = df["status"].map({"UP": 1, "DOWN": 0})
28
+
29
+ plt.figure(figsize=(12, 4))
30
+ plt.plot(df["timestamp"], df["status_bool"], drawstyle='steps-post',
31
+ marker='o', linestyle='-', markersize=3, color='#1f77b4')
32
+
33
+ plt.title("Server Uptime Trend", fontsize=14, pad=20)
34
+ plt.xlabel("Time", fontsize=12)
35
+ plt.ylabel("Status", fontsize=12)
36
+ plt.yticks([0, 1], ["DOWN", "UP"])
37
+ plt.grid(True, linestyle='--', alpha=0.5)
38
+ plt.tight_layout()
39
+ plt.savefig(output_file)
40
+ plt.close()
41
+
42
+ print(f"📈 Chart saved to: {output_file}")
43
+ logging.info(f"Uptime trend chart saved to: {output_file}")
44
+ return output_file
45
+ except Exception as e:
46
+ logging.error(f"Error plotting uptime trend: {e}")
47
+ raise
48
+
49
+ def plot_uptime_summary(df, output_file="server_uptime_summary.png"):
50
+ """Plot server uptime summary as pie chart"""
51
+ try:
52
+ # Calculate uptime percentage
53
+ total = len(df)
54
+ up = df[df["status"] == "UP"].shape[0]
55
+ down = df[df["status"] == "DOWN"].shape[0]
56
+
57
+ if total == 0:
58
+ raise ValueError("No data in log file")
59
+
60
+ uptime_pct = (up / total) * 100
61
+ downtime_pct = (down / total) * 100
62
+
63
+ labels = [f'UP ({uptime_pct:.1f}%)', f'DOWN ({downtime_pct:.1f}%)']
64
+ sizes = [up, down]
65
+ colors = ['#28a745', '#dc3545']
66
+
67
+ plt.figure(figsize=(6, 6))
68
+ wedges, texts, autotexts = plt.pie(sizes, labels=labels, autopct='%1.1f%%',
69
+ startangle=140, colors=colors)
70
+
71
+ # Make percentage text white and bold
72
+ for autotext in autotexts:
73
+ autotext.set_color('white')
74
+ autotext.set_fontweight('bold')
75
+
76
+ plt.title("Server Uptime Summary", fontsize=14, pad=20)
77
+ plt.axis('equal')
78
+ plt.tight_layout()
79
+ plt.savefig(output_file)
80
+ plt.close()
81
+
82
+ print(f"📊 Summary chart saved to: {output_file}")
83
+ logging.info(f"Uptime summary chart saved to: {output_file}")
84
+ return output_file
85
+ except Exception as e:
86
+ logging.error(f"Error plotting uptime summary: {e}")
87
+ raise
88
+
89
+ def get_uptime_stats(df):
90
+ """Get uptime statistics"""
91
+ try:
92
+ total = len(df)
93
+ up = df[df["status"] == "UP"].shape[0]
94
+ down = df[df["status"] == "DOWN"].shape[0]
95
+
96
+ if total == 0:
97
+ return {"total_checks": 0, "uptime_pct": 0, "downtime_pct": 0}
98
+
99
+ uptime_pct = (up / total) * 100
100
+ downtime_pct = (down / total) * 100
101
+
102
+ return {
103
+ "total_checks": total,
104
+ "up_checks": up,
105
+ "down_checks": down,
106
+ "uptime_pct": round(uptime_pct, 2),
107
+ "downtime_pct": round(downtime_pct, 2)
108
+ }
109
+ except Exception as e:
110
+ logging.error(f"Error calculating uptime stats: {e}")
111
+ raise
requirements.txt CHANGED
@@ -4,4 +4,6 @@ tavily-python>=0.3.0
4
  openai>=1.0.0
5
  requests>=2.31.0
6
  pytest==8.3.3
7
- redis>=4.0.0
 
 
 
4
  openai>=1.0.0
5
  requests>=2.31.0
6
  pytest==8.3.3
7
+ redis>=4.0.0
8
+ pandas>=1.5.0
9
+ matplotlib>=3.5.0