Repository navigation
Expand file tree
/
Copy pathcontroller.py
More file actions
251 lines (194 loc) · 6.59 KB
/
Copy pathcontroller.py
File metadata and controls
251 lines (194 loc) · 6.59 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
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
# Written By Paul Onyebuchi
# Title: controller.py
# Description: This program serves as the master controller
# for the hardware logs analyser automation pipeline.
# It looks for the compiled cpp program and automatically runs it,
# then parses the error_report.csv file and prints
# a clean user-friendly summary to the console.
from pathlib import Path
import sys
import subprocess
import csv
# Configuration & Constants
BASE_DIR = Path(__file__).resolve().parent
CPP_BINARY = BASE_DIR / "parser"
INPUT_FILE = BASE_DIR / "system_dump.txt" # This is the path to our system log file
CSV_REPORT = BASE_DIR / "error_report.csv"
CRITICAL_THRESHOLD = 0 # This ensures we get an alert if any critical errors are found
ERROR_THRESHOLD = 4 # We get alerted if total errors exceed this number
# Function to the input log file 'system_dump.txt' exists
# =====================================
def prepare_input() -> bool:
"""
This function verifies that the system log input file exists.
"""
print(f"[Python] Checking input file: {INPUT_FILE.name}")
if not INPUT_FILE.is_file():
print(
f"[Python ERROR] Input file '{INPUT_FILE.name}' "
"was not found."
)
return False
print("[Python] Input log found.")
return True
# C++ Parser Execution
# =====================================
def run_cpp_parser() -> bool:
"""
this function executes the compiled C++ parser and verifies its exit status.
"""
print(f"[Python] Executing C++ parser: {CPP_BINARY.name}")
if not CPP_BINARY.is_file():
print(
f"[Python ERROR] C++ parser '{CPP_BINARY.name}' "
"does not exist."
)
return False
if not CPP_BINARY.stat().st_mode & 0o111:
print(
f"[Python ERROR] C++ parser '{CPP_BINARY.name}' "
"is not executable."
)
return False
try:
result = subprocess.run(
[str(CPP_BINARY)],
cwd=BASE_DIR,
capture_output=True,
text=True,
check=False,
)
except OSError as exc:
print(f"[Python ERROR] Failed to execute C++ parser: {exc}")
return False
if result.stdout:
print(result.stdout.rstrip())
if result.stderr:
print(result.stderr.rstrip(), file=sys.stderr)
if result.returncode != 0:
print(
f"[Python ERROR] C++ parser failed "
f"with exit code {result.returncode}."
)
return False
print("[Python] C++ parser completed successfully.")
return True
# Function definition for analysing generated report from c++
def analyze_results() -> bool:
"""
Read the CSV report generated by C++ and perform diagnostic analysis.
"""
print(f"[Python] Reading report: {CSV_REPORT.name}")
if not CSV_REPORT.is_file():
print(
f"[Python ERROR] Expected report '{CSV_REPORT.name}' "
"was not generated."
)
return False
required_columns = {"Log_Level","Count"}
total_faults = 0
critical_alerts = 0
try:
with CSV_REPORT.open(
mode="r",
encoding="utf-8",
newline=""
) as file:
csv_reader = csv.DictReader(file)
if csv_reader.fieldnames is None:
print("[Python ERROR] CSV report is empty.")
return False
missing_columns = required_columns - set(csv_reader.fieldnames)
if missing_columns:
print(
"[Python ERROR] CSV report is missing required "
f"columns: {', '.join(sorted(missing_columns))}"
)
return False
print("\n" + "=" * 45)
print(" SYSTEM DIAGNOSTIC REPORT")
print("=" * 45)
for line_number, row in enumerate(csv_reader, start=2):
try:
log_level = row["Log_Level"].strip()
count = int(row["Count"])
except (KeyError, TypeError, ValueError) as exc:
print(
f"[Python ERROR] Invalid CSV data on "
f"line {line_number}: {exc}"
)
return False
if count < 0:
print(
f"[Python ERROR] Negative occurrence count "
f"on line {line_number}."
)
return False
total_faults += count
print(
f" -> {log_level:<10}: "
f"{count} occurrences"
)
if (
log_level == "CRITICAL".strip().upper()
and count > CRITICAL_THRESHOLD
):
critical_alerts += count
except OSError as exc:
print(
f"[Python ERROR] Unable to read report "
f"'{CSV_REPORT.name}': {exc}"
)
return False
print("=" * 45)
print(f"Total Logged Faults: {total_faults}")
print("=" * 45)
# Diagnostic evaluation
if critical_alerts > 0:
print(
"[ALERT] CRITICAL system errors detected. "
"Immediate investigation required."
)
elif total_faults > ERROR_THRESHOLD:
print(
"[WARNING] Total system fault threshold exceeded. "
"Review system logs."
)
else:
print(
"[PASS] System diagnostic parameters are "
"within acceptable operational limits."
)
print("=" * 45)
return True
# Main application pipeline
#===========================
def main() -> int:
"""
Main function to complete system log analysis pipeline.
Exit codes:
0 = Pipeline completed successfully.
1 =Input preparation failed.
2 = C++ parser failed
3 = Report Analysis failed.
"""
print("=" * 60)
print("[Python] System log analyser pipeline started.")
print("=" * 60)
# 1.) Verify input
if not prepare_input():
print("[Python] Pipeline aborted.")
return 1
# 2.) Execute c++ parser
if not run_cpp_parser():
print("[Python] Pipeline aborted due to C++ parser failure.")
return 2
# 3.) Analyse the generated report from c++
if not analyze_results():
print("[Python] Pipeline aborted during report analysis.")
return 3
print("[Python] System Log Analyzer pipeline completed successfully.")
return 0
# Application entry point
if __name__ == "__main__":
raise SystemExit(main())