-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcli_pretty.py
More file actions
executable file
·5820 lines (4758 loc) · 202 KB
/
cli_pretty.py
File metadata and controls
executable file
·5820 lines (4758 loc) · 202 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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import base64
import json
import argparse
import sys
import re
import textwrap
import ipaddress
from collections import deque
from datetime import datetime, timezone
UNIT_TEST = False
def compress_interface_list(interfaces):
"""Converts interface list to compact range notation.
Args:
interfaces: List of interface names
Returns:
str: Compressed representation using ranges
Algorithm:
1. Extract prefix+number pairs via regex
2. Group by prefix, sort numerically
3. Find consecutive sequences
4. Format as ranges (e1-e4) or singles (e1)
5. Combine with non-numeric interfaces
Examples:
['e1', 'e2', 'e3', 'e4'] -> 'e1-e4'
['e1', 'e2', 'e4', 'e5'] -> 'e1-e2, e4-e5'
['eth0', 'eth1', 'br0'] -> 'eth0-eth1, br0'
"""
if not interfaces:
return ""
if len(interfaces) == 1:
return interfaces[0]
# Group interfaces by their prefix (e.g., 'e', 'eth', 'br')
groups = {}
standalone = []
for iface in interfaces:
# Extract prefix and number using regex
match = re.match(r'^([a-zA-Z]+)(\d+)$', iface)
if match:
prefix = match.group(1)
number = int(match.group(2))
if prefix not in groups:
groups[prefix] = []
groups[prefix].append((number, iface))
else:
# Interface doesn't follow prefix+number pattern
standalone.append(iface)
# Process each group to find ranges
result_parts = []
for prefix in sorted(groups.keys()):
# Sort by number
numbers_and_ifaces = sorted(groups[prefix])
ranges = []
start = None
end = None
for number, iface in numbers_and_ifaces:
if start is None:
# Start new range
start = number
end = number
elif number == end + 1:
# Extend current range
end = number
else:
# End current range and start new one
if start == end:
ranges.append(f"{prefix}{start}")
else:
ranges.append(f"{prefix}{start}-{prefix}{end}")
start = number
end = number
# Add the final range
if start is not None:
if start == end:
ranges.append(f"{prefix}{start}")
else:
ranges.append(f"{prefix}{start}-{prefix}{end}")
result_parts.extend(ranges)
# Add standalone interfaces
result_parts.extend(sorted(standalone))
return ", ".join(result_parts)
class Pad:
flags = 2
iface = 16
proto = 11
state = 12
data = 41
class PadMdb:
bridge = 7
vlan = 6
group = 20
ports = 45
class PadStpPort:
port = 12
id = 7
state = 12
role = 12
edge = 6
designated = 31
total = 12 + 7 + 12 + 12 + 6 + 31
class PadRoute:
dest = 30
pref = 8
next_hop = 30
protocol = 6
uptime = 9
@staticmethod
def set(ipv):
"""Set default padding based on the IP version ('ipv4' or 'ipv6')."""
if ipv == 'ipv4':
PadRoute.dest = 18
PadRoute.next_hop = 15
elif ipv == 'ipv6':
PadRoute.dest = 43
PadRoute.next_hop = 39
else:
raise ValueError(f"unknown IP version: {ipv}")
class PadSoftware:
name = 11
date = 25
hash = 64
state = 10
version = 23
class PadDhcpServer:
ip = 17
mac = 19
host = 21
cid = 22
exp = 10
class PadSensor:
name = 30
value = 22
status = 10
@classmethod
def table_width(cls):
"""Total width of sensor table (matches show system width)"""
return cls.name + cls.value + cls.status
class PadLldp:
interface = 16
rem_idx = 10
time = 12
chassis_id = 20
port_id = 20
def format_memory_bytes(bytes_val):
"""Convert bytes to human-readable format"""
if bytes_val == 0:
return " "
elif bytes_val < 1024:
return f"{bytes_val}B"
elif bytes_val < 1024 * 1024:
return f"{bytes_val // 1024}K"
elif bytes_val < 1024 * 1024 * 1024:
return f"{bytes_val // (1024 * 1024):.1f}M"
else:
return f"{bytes_val // (1024 * 1024 * 1024):.1f}G"
def format_uptime_seconds(seconds):
"""Convert seconds to compact time format"""
if seconds == 0:
return " "
elif seconds < 60:
return f"{seconds}s"
elif seconds < 3600:
return f"{seconds // 60}m"
elif seconds < 86400:
return f"{seconds // 3600}h"
else:
return f"{seconds // 86400}d"
class Column:
"""Column definition for SimpleTable"""
def __init__(self, name, align='left', formatter=None, flexible=False, min_width=None):
self.name = name
self.align = align
self.formatter = formatter
self.flexible = flexible
self.min_width = min_width
class SimpleTable:
"""Simple table formatter that handles ANSI colors correctly and calculates dynamic column widths"""
def __init__(self, columns, min_width=None):
self.columns = columns
self.rows = []
self.min_width = min_width
self._column_widths = None # Cache calculated widths
@staticmethod
def visible_width(text):
"""Return visible character count, excluding ANSI escape sequences"""
ansi_pattern = r'\x1b\[[0-9;]*m'
clean_text = re.sub(ansi_pattern, '', str(text))
return len(clean_text)
def row(self, *values):
"""Store row data for later formatting"""
if len(values) != len(self.columns):
raise ValueError(f"Expected {len(self.columns)} values, got {len(values)}")
self.rows.append(values)
def width(self):
"""Calculate and return total table width"""
if self._column_widths is None:
self._column_widths = self._calculate_column_widths()
# Sum column widths + 2-char separator between columns
total = sum(self._column_widths)
if self._column_widths:
# Separators only between columns, not after the last one
total += (len(self._column_widths) - 1) * 2
return total
def adjust_padding(self, width):
"""Distribute padding to width evenly across flexible columns"""
if self._column_widths is None:
self._column_widths = self._calculate_column_widths()
current_width = self.width()
extra_width = width - current_width
if extra_width <= 0:
return # Already at or above target
# Find flexible columns
flex_indices = [i for i, col in enumerate(self.columns) if col.flexible]
if not flex_indices:
return # No flexible columns to expand
# Distribute evenly
per_column = extra_width // len(flex_indices)
remainder = extra_width % len(flex_indices)
for i, idx in enumerate(flex_indices):
self._column_widths[idx] += per_column
# Give remainder to first columns
if i < remainder:
self._column_widths[idx] += 1
def print(self, styled=True):
"""Calculate widths and print complete table"""
if self._column_widths is None:
self._column_widths = self._calculate_column_widths()
# Apply minimum width if specified
if self.min_width:
self.adjust_padding(self.min_width)
print(self._format_header(self._column_widths, styled))
for row_data in self.rows:
print(self._format_row(row_data, self._column_widths))
def _calculate_column_widths(self):
"""Calculate maximum width needed for each column"""
widths = [self.visible_width(col.name) for col in self.columns]
for row_data in self.rows:
for i, (value, column) in enumerate(zip(row_data, self.columns)):
formatted_value = column.formatter(value) if column.formatter else value
value_width = self.visible_width(str(formatted_value))
widths[i] = max(widths[i], value_width)
# Apply column minimum widths
for i, column in enumerate(self.columns):
if column.min_width:
widths[i] = max(widths[i], column.min_width)
return widths
def _format_header(self, column_widths, styled=True):
"""Generate formatted header row"""
header_parts = []
for i, column in enumerate(self.columns):
width = column_widths[i]
# Add separator " " only between columns, not after the last one
is_last = (i == len(self.columns) - 1)
separator = "" if is_last else " "
if column.align == 'right':
header_parts.append(f"{column.name:>{width}}{separator}")
else:
header_parts.append(f"{column.name:{width}}{separator}")
header_str = ''.join(header_parts)
return Decore.invert(header_str) if styled else header_str
def _format_row(self, row_data, column_widths):
"""Format a single data row"""
row_parts = []
for i, (value, column) in enumerate(zip(row_data, self.columns)):
is_last = (i == len(self.columns) - 1)
formatted_value = self._format_column_value(value, column, column_widths[i], is_last)
row_parts.append(formatted_value)
return ''.join(row_parts)
def _format_column_value(self, value, column, width, is_last=False):
"""Format a single column value with proper alignment"""
if column.formatter:
value = column.formatter(value)
value_str = str(value)
visible_len = self.visible_width(value_str)
# Add separator " " only between columns, not after the last one
separator = "" if is_last else " "
# Don't add trailing spaces to the last column
if is_last:
if column.align == 'right':
padding = width - visible_len
return ' ' * max(0, padding) + value_str
return value_str
elif column.align == 'right':
padding = width - visible_len
return ' ' * max(0, padding) + value_str + separator
else:
padding = width - visible_len
return value_str + ' ' * max(0, padding) + separator
class Canvas:
"""Multi-item rendering canvas for unified width alignment across tables and content.
Canvas coordinates the display of multiple SimpleTable instances and other content
types (text, titles, spacing, pre-rendered content) with consistent width alignment.
This creates professional-looking output where all table headers and content align
to the same width, with flexible columns distributing extra space evenly.
Purpose:
- Achieve visual alignment across heterogeneous content
- Minimize performance overhead with single-pass data traversal
- Support mixed content: tables, text, titles, matrices, spacing
How it works:
1. Buffer items in sequence (add_text, add_table, add_title, etc.)
2. Calculate maximum width from all SimpleTable instances
3. Apply flex padding to narrower tables via SimpleTable.adjust_padding()
4. Render all items sequentially with unified width
Interaction with SimpleTable:
- Calls SimpleTable.width() to determine natural table width
- Calls SimpleTable.adjust_padding(max_width) to expand flexible columns
- SimpleTable columns marked with flexible=True distribute extra width evenly
- Preserves table alignment (left/right) and formatting
Performance:
- Single data traversal: tables built once, widths calculated once
- Memory over CPU: buffers all items before rendering
- Optimized for embedded systems (ARM Cortex-A7)
Example:
See show_firewall() for a complete usage example demonstrating:
- Mixed content types (status text, matrix, tables)
- Multiple tables with different flexible columns
- Centered matrix using get_max_width()
- Proper spacing and titles
Args:
min_width: Optional minimum width for all tables (default: None)
"""
def __init__(self, min_width=None):
self.min_width = min_width
self.items = [] # List of (type, content) tuples
def add_text(self, text):
"""Add a plain text line"""
self.items.append(('text', text))
def add_title(self, text):
"""Add a section title (will be centered to canvas width)"""
self.items.append(('title', text))
def add_raw(self, text):
"""Add pre-rendered multi-line text (like zone matrix)"""
self.items.append(('raw', text))
def add_spacing(self, lines=1):
"""Add blank lines for spacing"""
self.items.append(('spacing', lines))
def add_table(self, table):
"""Add a SimpleTable instance"""
if not isinstance(table, SimpleTable):
raise ValueError("Expected SimpleTable instance")
self.items.append(('table', table))
def insert(self, index, item_type, content):
"""Insert an item at a specific position"""
self.items.insert(index, (item_type, content))
def insert_text(self, index, text):
"""Insert a plain text line at position"""
self.insert(index, 'text', text)
def insert_title(self, index, text):
"""Insert a section title at position"""
self.insert(index, 'title', text)
def insert_raw(self, index, text):
"""Insert pre-rendered text at position"""
self.insert(index, 'raw', text)
def insert_spacing(self, index, lines=1):
"""Insert blank lines at position"""
self.insert(index, 'spacing', lines)
def insert_table(self, index, table):
"""Insert a SimpleTable at position"""
if not isinstance(table, SimpleTable):
raise ValueError("Expected SimpleTable instance")
self.insert(index, 'table', table)
def get_max_width(self):
"""Calculate and return the maximum width from all tables"""
max_width = self.min_width or 0
for item_type, content in self.items:
if item_type == 'table':
max_width = max(max_width, content.width())
return max_width
def render(self):
"""Calculate widths, apply padding, and output all items"""
# First pass: find maximum width from all tables
max_width = self.get_max_width()
# Second pass: apply padding to all tables with flexible columns
for item_type, content in self.items:
if item_type == 'table':
content.adjust_padding(max_width)
# Third pass: render each item
for i, (item_type, content) in enumerate(self.items):
if item_type == 'text':
print(content)
elif item_type == 'title':
# Title with underline matching canvas width
underline = "─" * max_width
print(underline)
print(Decore.bold(content))
elif item_type == 'raw':
# Pre-rendered content (like matrix)
print(content)
elif item_type == 'spacing':
for _ in range(content):
print()
elif item_type == 'table':
content.print()
class Decore():
@staticmethod
def decorate(sgr, txt, restore="0"):
return f"\033[{sgr}m{txt}\033[{restore}m"
@staticmethod
def invert(txt):
return Decore.decorate("7", txt)
@staticmethod
def bold(txt):
return Decore.decorate("1", txt)
@staticmethod
def red(txt):
return Decore.decorate("31", txt, "39")
@staticmethod
def green(txt):
return Decore.decorate("32", txt, "39")
@staticmethod
def bright_green(txt):
return Decore.decorate("1;32", txt, "0")
@staticmethod
def yellow(txt):
return Decore.decorate("33", txt, "39")
@staticmethod
def bold_yellow(txt):
return Decore.decorate("1;33", txt, "0")
@staticmethod
def flashing_red(txt):
return Decore.decorate("5;31", txt, "0")
@staticmethod
def underline(txt):
return Decore.decorate("4", txt, "24")
@staticmethod
def gray_bg(txt):
return Decore.decorate("100", txt)
@staticmethod
def red_bg(txt):
return Decore.decorate("41", txt, "49")
@staticmethod
def green_bg(txt):
return Decore.decorate("42", txt, "49")
@staticmethod
def yellow_bg(txt):
return Decore.decorate("43", txt, "49")
@staticmethod
def title(txt, width=None, bold=True):
"""Print section header with horizontal bar line above it
Args:
txt: The header text to display
width: Length of horizontal bar line (defaults to len(txt))
bold: Whether to make the text bold
"""
length = width if width is not None else len(txt)
underline = "─" * length
print(underline)
if bold:
print(Decore.bold(txt))
else:
print(txt)
def signal_to_status(signal):
if signal >= -50:
status = Decore.bright_green("excellent")
elif signal >= -60:
status = Decore.green("good")
elif signal >= -70:
status = Decore.yellow("poor")
else:
status = Decore.red("bad")
return status
def datetime_now():
if UNIT_TEST:
return datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
return datetime.now(timezone.utc)
def get_json_data(default, indata, *args):
data = indata
for arg in args:
if arg in data:
data = data.get(arg)
else:
return default
return data
def remove_yang_prefix(key):
parts = key.split(":", 1)
if len(parts) > 1:
return parts[1]
return key
def format_description(label, description, width=60):
"""Format description text with proper line wrapping"""
if not description:
return f"{label:<20}:"
lines = textwrap.wrap(description, width=width)
if not lines:
return f"{label:<20}:"
# First line with label
result = f"{label:<20}: {lines[0]}"
# Subsequent lines indented
for line in lines[1:]:
result += f"\n{'':<20} {line}"
return result
class Date(datetime):
def _pretty_delta(delta):
assert(delta.total_seconds() > 0)
days = delta.days
seconds = delta.seconds
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
segments = (
("day", days),
("hour", hours),
("minute", minutes),
("second", seconds),
)
for i, seg in enumerate(segments):
if not seg[1]:
continue
out = f"{seg[1]} {seg[0]}{'s' if seg[1] != 1 else ''}"
if seg[0] == "second":
return out
seg = segments[i+1]
out += f" and {seg[1]} {seg[0]}{'s' if seg[1] != 1 else ''}"
return out
def pretty(self):
now = datetime_now()
if self < now:
delta = Date._pretty_delta(now - self)
return f"{delta} ago"
elif self > now:
delta = Date._pretty_delta(self - now)
return f"in {delta}"
return "now"
@classmethod
def from_yang(cls, ydate):
"""Conver a YANG formatted date string into a Python datetime"""
if not ydate:
return None
date, tz = ydate.split("+")
tz = tz.replace(":", "")
return cls.strptime(f"{date}+{tz}", "%Y-%m-%dT%H:%M:%S%z")
class Route:
def __init__(self, data, ip):
self.data = data
self.ip = ip
self.prefix = data.get(f'ietf-{ip}-unicast-routing:destination-prefix', '')
self.protocol = data.get('source-protocol', '').split(':')[-1]
self.last_updated = data.get('last-updated', '')
self.active = data.get('active', False)
self.pref = data.get('route-preference', '')
self.metric = data.get('ietf-ospf:metric', 0)
self.next_hop = []
next_hop_list = get_json_data(None, self.data, 'next-hop', 'next-hop-list')
if next_hop_list:
for nh in next_hop_list["next-hop"]:
if nh.get(f"ietf-{ip}-unicast-routing:address"):
hop = nh[f"ietf-{ip}-unicast-routing:address"]
elif nh.get("outgoing-interface"):
hop = nh["outgoing-interface"]
else:
hop = "unspecified"
fib = nh.get('infix-routing:installed', False)
self.next_hop.append((hop, fib))
else:
interface = get_json_data(None, self.data, 'next-hop', 'outgoing-interface')
address = get_json_data(None, self.data, 'next-hop', f'ietf-{ip}-unicast-routing:next-hop-address')
special = get_json_data(None, self.data, 'next-hop', 'special-next-hop')
if address:
self.next_hop.append(address)
elif interface:
self.next_hop.append(interface)
elif special:
self.next_hop.append(special)
else:
self.next_hop.append("unspecified")
def get_distance_and_metric(self):
if isinstance(self.pref, int):
distance = self.pref
metric = self.metric
else:
distance, metric = 0, 0
return distance, metric
def datetime2uptime(self):
"""Convert 'last-updated' string to uptime in AAhBBmCCs format."""
ONE_DAY_SECOND = 60 * 60 * 24
ONE_WEEK_SECOND = ONE_DAY_SECOND * 7
if not self.last_updated:
return "0h0m0s"
# Replace the colon in the timezone offset (e.g., +00:00 -> +0000)
pos = self.last_updated.rfind('+')
if pos != -1:
adjusted = self.last_updated[:pos] + self.last_updated[pos:].replace(':', '')
else:
adjusted = self.last_updated
last_updated = datetime.strptime(adjusted, '%Y-%m-%dT%H:%M:%S%z')
current_time = datetime_now()
uptime_delta = current_time - last_updated
total_seconds = int(uptime_delta.total_seconds())
total_days = total_seconds // ONE_DAY_SECOND
total_weeks = total_days // 7
hours = (total_seconds % ONE_DAY_SECOND) // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
if total_seconds < ONE_DAY_SECOND:
return f"{hours:02}:{minutes:02}:{seconds:02}"
elif total_seconds < ONE_WEEK_SECOND:
return f"{total_days}d{hours:02}h{minutes:02}m"
else:
days_remaining = total_days % 7
return f"{total_weeks:02}w{days_remaining}d{hours:02}h"
def print(self):
PadRoute.set(self.ip)
distance, metric = self.get_distance_and_metric()
uptime = self.datetime2uptime()
pref = f"{distance}/{metric}"
hop, fib = self.next_hop[0]
row = ">" if self.active else " "
row += "*" if fib else " "
row += " "
row += f"{self.prefix:<{PadRoute.dest}} "
row += f"{pref:>{PadRoute.pref}} "
row += f"{hop:<{PadRoute.next_hop}} "
row += f"{self.protocol:<{PadRoute.protocol}} "
row += f"{uptime:>{PadRoute.uptime}}"
print(row)
for nh in self.next_hop[1:]:
hop, fib = nh
row = " "
row += "*" if fib else " "
row += " "
row += f"{'':<{PadRoute.dest}} "
row += f"{'':>{PadRoute.pref}} "
row += f"{hop:<{PadRoute.next_hop}} "
print(row)
class Software:
"""Software bundle class """
def __init__(self, data):
self.data = data
self.name = data.get('bootname', '')
self.size = data.get('size', '')
self.type = data.get('class', '')
self.hash = data.get('sha256', '')
self.state = data.get('state', '')
self.version = get_json_data('', self.data, 'bundle', 'version')
self.date = get_json_data('', self.data, 'installed', 'datetime')
def is_rootfs(self):
"""True if bundle type is 'rootfs'"""
return self.type == "rootfs"
def print(self):
"""Brief information about one bundle"""
row = f"{self.name:<{PadSoftware.name}}"
row += f"{self.state:<{PadSoftware.state}}"
row += f"{self.version:<{PadSoftware.version}}"
row += f"{self.date:<{PadSoftware.date}}"
print(row)
def detail(self):
"""Detailed information about one bundle"""
print(f"Name : {self.name}")
print(f"State : {self.state}")
print(f"Version : {self.version}")
print(f"Size : {self.size}")
print(f"SHA-256 : {self.hash}")
print(f"Installed : {self.date}")
class USBport:
def __init__(self, data):
self.data = data
self.name = data.get('name', '')
self.state = get_json_data('', self.data, 'state', 'admin-state')
self.oper = get_json_data('', self.data, 'state', 'oper-state')
class Sensor:
def __init__(self, data):
self.data = data
self.name = data.get('name', 'unknown')
self.description = data.get('description') # Human-readable description
self.parent = data.get('parent') # Parent component name
sensor_data = data.get('sensor-data', {})
self.value_type = sensor_data.get('value-type', 'unknown')
self.value = sensor_data.get('value', 0)
self.value_scale = sensor_data.get('value-scale', 'units')
self.oper_status = sensor_data.get('oper-status', 'unknown')
def get_formatted_value(self):
"""Convert sensor value based on scale and type"""
# Handle temperature sensors
if self.value_type == 'celsius':
if self.value_scale == 'milli':
temp_celsius = self.value / 1000.0
# Color code based on temperature thresholds
if temp_celsius < 60:
return Decore.green(f"{temp_celsius:.1f} °C")
elif temp_celsius < 75:
return Decore.yellow(f"{temp_celsius:.1f} °C")
else:
return Decore.red(f"{temp_celsius:.1f} °C")
else:
return f"{self.value} °C"
# Handle fan speed sensors
elif self.value_type == 'rpm':
return f"{self.value} RPM"
# Handle voltage sensors
elif self.value_type == 'volts-DC':
if self.value_scale == 'milli':
volts = self.value / 1000.0
return f"{volts:.2f} VDC"
else:
return f"{self.value} VDC"
# Handle current sensors
elif self.value_type == 'amperes':
if self.value_scale == 'milli':
amps = self.value / 1000.0
return f"{amps:.3f} A"
else:
return f"{self.value} A"
# Handle power sensors
elif self.value_type == 'watts':
if self.value_scale == 'micro':
watts = self.value / 1000000.0
return f"{watts:.3f} W"
elif self.value_scale == 'milli':
watts = self.value / 1000.0
return f"{watts:.2f} W"
else:
return f"{self.value} W"
# Handle PWM fan sensors (reported as "other" type with milli scale)
# PWM duty cycle is reported as percentage (0-100)
elif self.value_type == 'other' and self.value_scale == 'milli':
# Check if this is likely a PWM sensor based on description or name
name_lower = self.name.lower()
desc_lower = (self.description or "").lower()
if 'pwm' in desc_lower or 'fan' in name_lower or 'fan' in desc_lower:
percent = self.value / 1000.0
return f"{percent:.1f}%"
# Fall through for other "other" type sensors
# For unknown sensor types, show raw value
if self.value_type in ['other', 'unknown']:
return f"{self.value}"
else:
return f"{self.value} {self.value_type}"
def print(self, indent=0):
import re
# Add indentation for child sensors
indent_str = " " * indent
# Determine display name: prefer description, fallback to name
if self.description:
# Use description if available (e.g., "WiFi Radio wlan0 (2.4 GHz)")
display_name = self.description
elif indent > 0 and self.parent:
# Child sensor: strip parent prefix from name
# "sfp1-RX_power" -> "RX_power" -> "Rx Power"
display_name = self.name
if display_name.startswith(self.parent + "-"):
display_name = display_name[len(self.parent) + 1:]
# Format: "RX_power" -> "Rx Power"
display_name = display_name.replace('_', ' ').replace('-', ' ').title()
else:
# Standalone sensor without description: use name as-is
display_name = self.name
row = f"{indent_str}{display_name:<{PadSensor.name - len(indent_str)}}"
# For colored value, pad manually to account for ANSI codes
value_str = self.get_formatted_value()
# Count visible characters (strip ANSI codes for length calculation)
visible_len = len(re.sub(r'\x1b\[[0-9;]*m', '', value_str))
padding = PadSensor.value - visible_len
row += value_str + (' ' * padding)
row += f"{self.oper_status:<{PadSensor.status}}"
print(row)
class STPBridgeID:
def __init__(self, id):
self.id = id
def __str__(self):
prio, sysid, addr = (
self.id["priority"],
self.id["system-id"],
self.id["address"]
)
return f"{prio:1x}.{sysid:03x}.{addr}"
class STPPortID:
def __init__(self, id):
self.id = id
def __str__(self):
prio, pid = (
self.id["priority"],
self.id["port-id"],
)
return f"{prio:1x}.{pid:03x}"
class DhcpServer:
def __init__(self, data):
self.data = data
self.leases = []
now = datetime.now(timezone.utc)
for lease in get_json_data([], self.data, 'leases', 'lease'):
if lease["expires"] == "never":
exp = "never"
else:
dt = datetime.strptime(lease['expires'], '%Y-%m-%dT%H:%M:%S%z')
seconds = int((dt - now).total_seconds())
exp = self.format_duration(seconds)
self.leases.append({
"ip": lease["address"],
"mac": lease["phys-address"],
"cid": lease["client-id"],
"host": lease["hostname"],
"exp": exp
})
stats = get_json_data([], self.data, 'statistics')
self.out_offers = stats["out-offers"]
self.out_acks = stats["out-acks"]
self.out_naks = stats["out-naks"]
self.in_declines = stats["in-declines"]
self.in_discovers = stats["in-discovers"]
self.in_requests = stats["in-requests"]
self.in_releases = stats["in-releases"]
self.in_informs = stats["in-informs"]
def format_duration(self, seconds):
"""Convert seconds to DDdHHhMMmSSs format, omitting zero values"""
if seconds < 0:
return "expired"
days, remainder = divmod(seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
parts = []
if days:
parts.append(f"{days}d")
if hours:
parts.append(f"{hours}h")
if minutes:
parts.append(f"{minutes}m")