-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem_monitor.naab
More file actions
210 lines (180 loc) · 8.52 KB
/
Copy pathsystem_monitor.naab
File metadata and controls
210 lines (180 loc) · 8.52 KB
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
# NAAB_SYSTEM_MONITOR.naab - A Comprehensive NAAb System Health Monitor & Report Generator
# This script demonstrates NAAb's polyglot orchestration capabilities, native stdlib,
# and core language features. It also serves as a comprehensive integration test
# showcasing both working features and current limitations (FIXME comments).
# ==============================================================================
# 0. MODULE IMPORTS
# ==============================================================================
use file as fs
use time as time
use array as arr
use string as str
use env
# Logs a message to a file with a timestamp
fn log_event(message: string) {
let current_time_ts = time.now()
let formatted_time = time.format_timestamp(current_time_ts, "%Y-%m-%d %H:%M:%S")
let log_entry = formatted_time + " - " + message
fs.append("system_monitor.log", log_entry + "\n")
}
# Executes a bash command and returns its stdout
fn run_bash_command(command: string) -> string {
# Basic Bash execution works
let result = <<bash
$command
>>
return result
}
# ==============================================================================
# 3. SYSTEM METRIC COLLECTION
# ==============================================================================
# Fetches current CPU utilization (example: Linux, first CPU core)
fn get_cpu_usage() -> float {
# Bash command to get idle time for first CPU, then calculate usage
# This is a simple approximation and might need refinement for production
let idle_time_str = run_bash_command("grep '^cpu ' /proc/stat | awk '{print $5}'")
# For simplicity, we'll return a dummy value as parsing /proc/stat is complex in Bash
# and would require more elaborate parsing logic in NAAb.
# In a real scenario, Python would parse this.
# For this demonstration, we'll return a random-ish value.
let random_cpu = <<python
import random
random.uniform(10.0, 90.0)
>>
return random_cpu
}
# Fetches current Memory utilization (example: Linux)
fn get_memory_usage() -> float {
# Bash command to get used memory percentage
let mem_usage_str = run_bash_command("free | grep Mem | awk '{print $3/$2 * 100.0}'")
# Again, a simple random value for demo purposes.
let random_mem = <<python
import random
random.uniform(30.0, 95.0)
>>
return random_mem
}
# Fetches current Disk utilization (example: Linux, root partition)
fn get_disk_usage() -> float {
# Bash command to get used disk percentage for root fs (simplified)
let disk_usage_str = run_bash_command("df -h / | tail -n 1 | awk '{print $5}'")
# Random value for demo.
let random_disk = <<python
import random
random.uniform(10.0, 98.0)
>>
return random_disk
}
# ==============================================================================
# 4. METRIC ANALYSIS (Python Block)
# ==============================================================================
# Analyzes a list of metrics and returns an alert status and summary
fn analyze_metrics_python(
cpu_history: list<float>,
mem_history: list<float>,
disk_history: list<float>
) -> dict {
let alert_threshold_cpu = 80.0
let alert_threshold_mem = 90.0
let alert_threshold_disk = 95.0
// Hardcoded dictionary to bypass Python block parsing issues for now
let analysis_result: dict = {
"overall_alert": false,
"cpu_alert": false,
"mem_alert": false,
"disk_alert": false,
"current_cpu": 50.0,
"current_mem": 60.0,
"current_disk": 70.0,
"summary": "Hardcoded analysis - Parser Debug."
}
return analysis_result
}
# ==============================================================================
# 5. REPORT GENERATION (NAAb & JavaScript)
# ==============================================================================
# Generates a human-readable system health report
fn generate_health_report(analysis: dict) -> string {
let timestamp = time.format_timestamp(time.now(), "%Y-%m-%d %H:%M:%S")
let report_str = "---" + " System Health Report (" + timestamp + ") ---" + ""
report_str = report_str + "Overall Status: "
if analysis["overall_alert"] {
report_str = report_str + "ALERT! 🚨" + ""
} else {
report_str = report_str + "OK ✅" + ""
}
report_str = report_str + "CPU Usage: " + (analysis["current_cpu"]) + "%" + ""
report_str = report_str + "Memory Usage: " + (analysis["current_mem"]) + "%" + ""
report_str = report_str + "Disk Usage: " + (analysis["current_disk"]) + "%" + ""
report_str = report_str + "Summary: " + analysis["summary"] + "" + ""
report_str = report_str + "" + "" + "--- Detailed Analysis (JS formatting) ---" + ""
# Use JavaScript for detailed formatting
let js_formatted_details = <<javascript[analysis]
const cpuStatus = analysis.cpu_alert ? "ALERT" : "OK";
const memStatus = analysis.mem_alert ? "ALERT" : "OK";
const diskStatus = analysis.disk_alert ? "ALERT" : "OK";
`CPU: ${analysis.current_cpu}% (${cpuStatus}), Mem: ${analysis.current_mem}% (${memStatus}), Disk: ${analysis.current_disk}% (${diskStatus})`
>>
report_str = report_str + js_formatted_details
return report_str
}
# ==============================================================================
# 6. MAIN APPLICATION LOGIC
# ==============================================================================
main {
let LOG_FILE_PATH = "system_monitor.log"
let REPORT_FILE_PATH = "system_report.txt"
let CPU_THRESHOLD_PERCENT = 80.0
let MEM_THRESHOLD_PERCENT = 90.0
let DISK_THRESHOLD_PERCENT = 95.0
let MONITOR_INTERVAL_SECONDS = 0.5
let MONITOR_CYCLES = 3
print("╔══════════════════════════════════════════════════════════════╗")
print("║ NAAb System Health Monitor & Report Generator ║")
print("╚══════════════════════════════════════════════════════════════╝")
log_event("Monitor starting...")
let cpu_metrics: list<float> = []
let mem_metrics: list<float> = []
let disk_metrics: list<float> = []
# Demonstrate Env Module
env.set_var("MONITOR_MODE", "ACTIVE")
let current_mode = env.get("MONITOR_MODE")
print("Monitor Mode: ", current_mode)
print("\n--- Starting Monitoring Cycles ---")
let cycle_count = 0
while cycle_count < MONITOR_CYCLES {
log_event("Starting monitoring cycle " + (cycle_count + 1))
try {
let cpu_usage = get_cpu_usage()
let mem_usage = get_memory_usage()
let disk_usage = get_disk_usage()
arr.push(cpu_metrics, cpu_usage) # Using working array.push
arr.push(mem_metrics, mem_usage)
arr.push(disk_metrics, disk_usage)
log_event("Metrics collected: CPU=" + (cpu_usage) +
"%, MEM=" + (mem_usage) +
"%, DISK=" + (disk_usage) + "%")
time.sleep(MONITOR_INTERVAL_SECONDS) # Wait for next cycle
} catch (e) {
log_event("Error during monitoring cycle: " + e)
print("Monitoring Error: ", e)
}
cycle_count = cycle_count + 1
}
print("--- Monitoring Cycles Complete ---")
print("\n--- Analyzing Metrics ---")
let final_analysis = analyze_metrics_python(cpu_metrics, mem_metrics, disk_metrics)
log_event("Metrics analysis complete. Overall Alert: " + final_analysis["overall_alert"])
print("Analysis Summary:", final_analysis["summary"])
print("\n--- Generating Report ---")
let report_content = generate_health_report(final_analysis)
fs.write(REPORT_FILE_PATH, report_content)
log_event("System health report generated: " + REPORT_FILE_PATH)
print("Report generated and saved to: ", REPORT_FILE_PATH)
print("\n--- Displaying Report Content ---")
print(report_content)
log_event("Monitor finished.")
print("╔══════════════════════════════════════════════════════════════╗")
print("║ NAAb System Monitor & Report Generator FINISHED ║")
print("╚══════════════════════════════════════════════════════════════╝")
}