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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
| #!/usr/bin/env python3
import paramiko
import time
import sys
import re
from datetime import datetime
from typing import Dict, List, Tuple, Optional
import io
# Connection credentials
ROUTER_IP = "172.16.1.1"
SSH_USERNAME = "username"
SSH_PASSWORD = "password"
ROUTER_CLI_IP = "192.168.100.2/24"
ROUTER_INTERFACE = "ethX"
SFP_IP = "192.168.100.1"
SFP_USERNAME = "username"
SFP_PASSWORD = "password"
class ONULogAnalyzer:
def __init__(self):
self.pon_link_events = [] # Events from PMR log
self.net_link_events = [] # Events from NET log
self.state_transitions = [] # PON state machine transitions
self.error_events = [] # Critical error events
self.trans_state = {} # Current transceiver state
self.current_link_state = "" # Current PON link state
self.initialization_events = []
self.link_events = []
self.gem_port_stats = [] # List to store GEM port statistics
self.alu_stats = {} # Dictionary for ALU specific statistics
self.log_data = {} # Dictionary to store collected log data
def _is_valid_hex(self, value: str) -> bool:
"""Check if a string is a valid hexadecimal number"""
try:
clean_value = value.replace('x', '')
return all(c in '0123456789abcdefABCDEF' for c in clean_value)
except:
return False
def _convert_tick_to_ms(self, tick: str) -> int:
"""Convert hexadecimal tick to milliseconds with validation"""
try:
if not self._is_valid_hex(tick):
return 0
return int(tick.replace('x', ''), 16)
except ValueError:
return 0
def collect_sfp_data(self) -> None:
"""Connect to router, configure CLI IP, connect to SFP, and execute commands"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Connect to router via SSH
print(f"Connecting to router {ROUTER_IP}...")
ssh.connect(ROUTER_IP,
username=SSH_USERNAME,
password=SSH_PASSWORD,
look_for_keys=False,
allow_agent=False)
print("SSH connection established")
# Configure CLI IP on router
print(f"Configuring CLI IP {ROUTER_CLI_IP} on {ROUTER_INTERFACE}")
cli_command = f"ip addr add {ROUTER_CLI_IP} dev {ROUTER_INTERFACE}"
stdin, stdout, stderr = ssh.exec_command(cli_command)
time.sleep(2) # Wait for IP configuration to take effect
# Connect to SFP via Telnet from the router
print(f"Connecting to SFP {SFP_IP} via Telnet...")
channel = ssh.invoke_shell()
# Send telnet command and credentials
channel.send(f'telnet {SFP_IP}\n')
time.sleep(2)
channel.send(f'{SFP_USERNAME}\n')
time.sleep(1)
channel.send(f'{SFP_PASSWORD}\n')
time.sleep(1)
channel.send('enable\n')
time.sleep(1)
# Commands to execute
commands = {
"/system/log/show pmr": "pmr_log",
"/system/log/show net": "net_log",
"/traffic/omci/show pm gem": "gem_log",
"/traffic/omci/show pm eth": "eth_log",
"/traffic/pon/show link": "pon_link_log",
"/system/misc/show trans state": "trans_state_log"
}
# Execute each command and store output
for cmd, log_key in commands.items():
print(f"Executing: {cmd}")
channel.send(cmd + '\n')
time.sleep(3)
output = ""
max_attempts = 10
attempts = 0
while attempts < max_attempts:
if channel.recv_ready():
chunk = channel.recv(4096).decode('ascii')
output += chunk
if not chunk:
break
else:
time.sleep(0.5)
attempts += 1
self.log_data[log_key] = output
print(f"Collected {log_key}")
# Exit telnet
channel.send('exit\n')
time.sleep(1)
except Exception as e:
print(f"Error in data collection: {str(e)}")
raise
finally:
# Clean up CLI IP
try:
cli_cleanup = f"ip addr del {ROUTER_CLI_IP} dev {ROUTER_INTERFACE}"
ssh.exec_command(cli_cleanup)
print("Cleaned up CLI IP configuration")
except:
pass
ssh.close()
print("All connections closed")
def get_latest_uptime(self, content: str) -> int:
"""Extract the latest uptime value from logs"""
latest_uptime = 0
for line in content.split('\n'):
parts = line.strip().split()
if len(parts) >= 2:
try:
uptime_hex = parts[1]
if not self._is_valid_hex(uptime_hex):
continue
uptime_seconds = int(uptime_hex.replace('x', ''), 16)
latest_uptime = max(latest_uptime, uptime_seconds)
except (ValueError, IndexError):
continue
return latest_uptime
def analyze_pon_link_status(self, content: str):
"""Analyze PON link status log"""
state_match = re.search(r'Operation State Machine:\s*(.+)', content)
if state_match:
self.current_link_state = state_match.group(1)
def analyze_pmr_log(self, content: str):
"""Analyze PMR log for state transitions and initializations"""
for line in content.split('\n'):
parts = line.strip().split()
if len(parts) >= 4:
try:
tick = parts[0]
uptime = parts[1]
if not self._is_valid_hex(tick) or not self._is_valid_hex(uptime):
continue
ms = self._convert_tick_to_ms(tick)
if "state transtion:" in line:
states = re.findall(r'state transtion: (.*?) -->', line) + re.findall(r'--> (.*?)(?:\s|$)', line)
if len(states) == 2:
self.initialization_events.append((ms, f"{states[0]} -> {states[1]}"))
self.state_transitions.append((ms, uptime, states[0], states[1]))
if 'MEC_MSG_PON_LINK' in line:
event_type = "PON Link UP" if "LINK_UP" in line else "PON Link DOWN"
self.pon_link_events.append((ms, uptime, event_type))
self.link_events.append((ms, event_type))
except Exception:
continue
def analyze_net_log(self, content: str):
"""Analyze network log for PON link events only"""
for line in content.split('\n'):
if 'MEC_MSG_PON_LINK' in line:
parts = line.strip().split()
if len(parts) >= 2:
try:
tick = parts[0]
uptime = parts[1]
if not self._is_valid_hex(tick) or not self._is_valid_hex(uptime):
continue
ms = self._convert_tick_to_ms(tick)
event_type = "Network Link UP" if "LINK_UP" in line else "Network Link DOWN"
self.net_link_events.append((ms, uptime, event_type))
self.link_events.append((ms, event_type))
except Exception:
continue
def analyze_eth_log(self, content: str):
"""Analyze ethernet log for errors"""
current_section = ""
for line in content.split('\n'):
line = line.strip()
if line.startswith('pm1 me id:'):
current_section = "pm1"
continue
elif line.startswith('---------------'):
continue
if current_section == "pm1":
if ':' in line:
try:
key, value = line.split(':', 1)
key = key.strip()
value_str = value.strip()
try:
value = int(value_str)
if value > 0:
self.error_events.append((key, value))
except ValueError:
continue
except Exception:
continue
def analyze_gem_log(self, content: str):
"""Analyze GEM port performance monitoring data"""
current_port = {}
in_alu_section = False
in_alu47_section = False
for line in content.split('\n'):
line = line.strip()
if 'gem port id' in line:
if current_port and current_port.get('gem_port_id') != 'ffff':
self.gem_port_stats.append(current_port.copy())
current_port = {}
try:
port_id = line.split(':')[1].strip()
current_port['gem_port_id'] = port_id
except Exception:
continue
if line.startswith('enable'):
try:
current_port['enabled'] = line.split(':')[1].strip() == '1'
except Exception:
continue
for metric in ['lost packets', 'misinsert packets', 'rx packets',
'tx packets', 'rx blocks', 'tx blocks', 'impaired blocks',
'tx gem frames', 'rx gem frames', 'rx payload bytes',
'tx payload bytes']:
if line.startswith(metric):
try:
value_str = line.split(':')[1].strip()
if self._is_valid_hex(value_str):
value = int(value_str, 16)
current_port[metric.replace(' ', '_')] = value
except Exception:
continue
if 'ALU pm data me id' in line:
in_alu_section = True
in_alu47_section = False
continue
if 'ALU47 pm data me id' in line:
in_alu_section = False
in_alu47_section = True
continue
if in_alu_section or in_alu47_section:
for metric in ['lost DS packets', 'lost US packets', 'rx bad headers',
'rx blocks 64bit', 'tx blocks 64bit']:
if line.startswith(metric):
try:
value_str = line.split(':')[1].strip()
if self._is_valid_hex(value_str):
value = int(value_str, 16)
prefix = 'alu_' if in_alu_section else 'alu47_'
self.alu_stats[f'{prefix}{metric.replace(" ", "_")}'] = value
except Exception:
continue
if current_port and current_port.get('gem_port_id') != 'ffff':
self.gem_port_stats.append(current_port.copy())
def analyze_trans_state(self, content: str):
"""Analyze transceiver state"""
for line in content.split('\n'):
if ':' in line:
try:
key, value = line.split(':', 1)
self.trans_state[key.strip()] = value.strip()
except Exception:
continue
def format_time_diff(self, ms: int) -> str:
"""Format milliseconds into a human readable duration"""
try:
parts = []
total_seconds = ms // 1000
days = total_seconds // 86400
hours = (total_seconds % 86400) // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
milliseconds = ms % 1000
if days > 0:
parts.append(f"{days}d")
if hours > 0:
parts.append(f"{hours}h")
if minutes > 0:
parts.append(f"{minutes}m")
if seconds > 0 or milliseconds > 0:
if milliseconds > 0:
parts.append(f"{seconds}.{milliseconds:03d}s")
else:
parts.append(f"{seconds}s")
elif not parts:
parts.append("0s")
return " ".join(parts)
except Exception:
return "0s"
def analyze_all_logs(self) -> None:
"""Analyze all collected logs"""
try:
self.analyze_net_log(self.log_data.get('net_log', ''))
self.analyze_eth_log(self.log_data.get('eth_log', ''))
self.analyze_pmr_log(self.log_data.get('pmr_log', ''))
self.analyze_trans_state(self.log_data.get('trans_state_log', ''))
self.analyze_pon_link_status(self.log_data.get('pon_link_log', ''))
self.analyze_gem_log(self.log_data.get('gem_log', ''))
except Exception as e:
print(f"Error in log analysis: {str(e)}")
raise
def generate_report(self) -> str:
"""Generate a comprehensive report of the analysis"""
try:
report = []
report.append("=== XGS-PON ONU SFP Analysis Report ===\n")
# Calculate SFP uptime
latest_uptime = self.get_latest_uptime(self.log_data.get('pmr_log', ''))
uptime_str = self.format_time_diff(latest_uptime * 1000)
report.append(f"SFP Uptime: {uptime_str}\n")
# Transceiver State
report.append("Current Transceiver State:")
if self.trans_state:
for key, value in self.trans_state.items():
report.append(f" {key}: {value}")
else:
report.append(" Status not available")
report.append("")
# Current Link Status
report.append("Current Link Status:")
if self.current_link_state:
report.append(f" {self.current_link_state}")
else:
report.append(" Status not available")
report.append("")
# Link Events
report.append("Link Events (all timestamps are relative to SFP boot time):")
all_events = [(ms, uptime, event) for ms, uptime, event in self.pon_link_events]
all_events.extend(self.net_link_events)
sorted_events = sorted(all_events)
if sorted_events:
base_time = sorted_events[0][0]
last_event_time = None
last_event_type = None
for ms, uptime, event in sorted_events:
relative_time = self.format_time_diff(ms - base_time)
report.append(f" [{relative_time}] {event} (System Uptime: {uptime})")
if last_event_time is not None:
time_diff = ms - last_event_time
if ("DOWN" in last_event_type and "UP" in event and
("PON" in last_event_type) == ("PON" in event)):
report.append(f" Link outage duration: {self.format_time_diff(time_diff)}")
last_event_time = ms
last_event_type = event
else:
report.append(" No link events detected")
report.append("")
# State Transitions
report.append("State Transitions:")
if self.initialization_events:
sorted_events = sorted(self.initialization_events)
base_time = sorted_events[0][0]
for ms, event in sorted_events:
relative_time = self.format_time_diff(ms - base_time)
report.append(f" [{relative_time}] {event}")
else:
report.append(" No state transitions detected")
report.append("")
# Error Events
if self.error_events:
report.append("Detected Errors:")
for error_type, count in self.error_events:
report.append(f" {error_type}: {count}")
else:
report.append("No ethernet errors detected")
report.append("")
# GEM Port Statistics
report.append("GEM Port Statistics:")
active_ports = sum(1 for port in self.gem_port_stats
if port.get('enabled', False) and
port.get('gem_port_id') not in ['fffe', 'fffd', 'ffff'])
report.append(f" Active GEM Ports: {active_ports}")
# Report on ports with non-zero traffic
active_traffic_ports = [port for port in self.gem_port_stats
if (port.get('rx_packets', 0) > 0 or
port.get('tx_packets', 0) > 0)]
if active_traffic_ports:
report.append("\n Ports with Traffic:")
for port in active_traffic_ports:
port_id = port.get('gem_port_id', 'Unknown')
report.append(f"\n GEM Port ID: 0x{port_id}")
report.append(f" RX Packets: {port.get('rx_packets', 0)}")
report.append(f" TX Packets: {port.get('tx_packets', 0)}")
report.append(f" Lost Packets: {port.get('lost_packets', 0)}")
report.append(f" Misinserted Packets: {port.get('misinsert_packets', 0)}")
# Add ALU specific statistics if present
if self.alu_stats:
report.append("\n ALU Statistics:")
for metric, value in self.alu_stats.items():
if value > 0: # Only show non-zero values
report.append(f" {metric.replace('_', ' ').title()}: {value}")
# Summary statistics
report.append("\nSummary:")
link_ups = sum(1 for _, event in self.link_events if "UP" in event)
link_downs = sum(1 for _, event in self.link_events if "DOWN" in event)
report.append(f" Total Link Flaps: {link_downs}")
report.append(f" Link State Changes: {link_ups + link_downs}")
report.append(f" State Transitions: {len(self.initialization_events)}")
return "\n".join(report)
except Exception as e:
return f"Error generating report: {str(e)}"
def main():
"""Main function to run the SFP log collection and analysis"""
try:
# Create analyzer instance
analyzer = ONULogAnalyzer()
# Collect data from SFP
print("Starting SFP data collection...")
analyzer.collect_sfp_data()
print("Data collection completed")
# Analyze the collected logs
print("Analyzing logs...")
analyzer.analyze_all_logs()
# Generate and print report
print("\nGenerating report...\n")
report = analyzer.generate_report()
print(report)
# Save report to file with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_filename = f"sfp_analysis_report_{timestamp}.txt"
with open(report_filename, 'w') as f:
f.write(report)
print(f"\nReport saved to {report_filename}")
return 0
except Exception as e:
print(f"Error: {str(e)}")
return 1
if __name__ == "__main__":
sys.exit(main()) |