-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdpla.py
1828 lines (1587 loc) · 67.1 KB
/
dpla.py
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
"""
Script Name: dpla.py
Description: Data Pump Log Analyzer
Parse and analyze Oracle Data Pump log files
Requires Python 3.6
Copyright (c) 2024 Marcus Doeringer / macsdata
Licensed under the Universal Permissive License v 1.0
Usage: Run this script from the command line
python3 dpla.py or ./dpla.py
Use -h or --help to show all options
Author: Marcus Doeringer
"""
__version__ = "0.9.2"
import re
import argparse
import os
import sys
from collections import defaultdict
from datetime import datetime
# Defaults
defaults = {
'oramsg': {'sort': 'count', 'top': None},
'object': {'sort': 'seconds', 'top': None},
'worker': {'sort': 'seconds', 'top': None},
'schema': {'sort': 'seconds', 'top': None},
'table': {'sort': 'seconds', 'top': 30},
'instance': {'sort': 'seconds', 'top': None}
}
indent = " "
# Define aggregation methods
aggr_methods = {
'count': sum,
'instance': max,
'workers': max
}
aggr_default = sum
# Initialize dictionaries
oramsg_stats = defaultdict(lambda: {'count': 0})
worker_stats = defaultdict(lambda: {'instance': 0, 'objects': 0, 'size': 0.0, 'seconds': 0})
schema_stats = defaultdict(lambda: {'objects': 0, 'size': 0.0, 'seconds': 0})
table_stats = defaultdict(lambda: {'rows': 0, 'size': 0.0, 'seconds': 0, 'part': set(), 'subpart': 0})
object_stats = defaultdict(lambda: {'count': 0, 'seconds': 0, 'workers': set(), 'duration': 0})
instance_stats = defaultdict(lambda: {'workers': set(), 'objects': 0, 'size': 0.0, 'seconds': 0})
# Global regex patterns
operation_re = re.compile(r'(?P<operation>Import|Export): .+ on (?P<starttime>.+)$')
starttime_re = re.compile(r'(?P<starttime>^.+?)\.?\d{3}?:')
jobname_re = re.compile(r'Starting .+"\."(?P<jobname>[\w_]+)":')
dpversion_re = re.compile(r'^Version\s+(?P<dpversion>.+)$')
dbinfo_re = re.compile(r'Connected to: (?P<dbinfo>.+) -.+$')
endtime_re = re.compile(r'Job.+ completed(?: with (?P<errors>\d+) error\(s\))? at (?P<endtime>[\w\s:]+) elapsed .+$')
worker_re = re.compile(r'W-(?P<worker>\d+).*?Startup(?: on instance (?P<instance>\d+))? took')
oramsg_re = re.compile(r'(?P<errid>ORA-\d{5}): (?P<errmsg>.+)$')
oramsg_delpattern = [
re.compile(r'[:\.]?["\'][^"\']*["\']') # Matches anyhting within single or double quotes with : and .
]
data_re = re.compile(
r'W-(?P<worker>\d+)?\s*\.\s*\.\s*'
r'(?P<operation>imported|exported)\s+"'
r'(?P<schema>[^"]+)"\."(?P<table>[^"]+)"'
r'(?:\:"(?P<partition>[^"]+)"(?:\."(?P<subpartition>[^"]*)")?)?'
r'\s+(?P<size>\d+(?:\.\d*)?)\s+'
r'(?P<unit>KB|MB|GB|TB)\s+'
r'(?P<rows>\d+) rows'
r'(?: in (?P<seconds>\d+) seconds?)?'
r'(.*)$'
)
object_re = re.compile(
r'Completed(?: by worker (?P<worker>\d+))? '
r'(?P<ocount>\d+) '
r'(?P<otype>[A-Z_/]+) '
r'objects in '
r'(?P<seconds>\d+) seconds'
)
otype_re = re.compile(r"Processing object type (?P<otype>.+)$")
# Classes
class OutputRedirector:
# Used to redirect output to file
def __init__(self, filename=None):
self.filename = filename
self.original_stdout = sys.stdout
self.file = None
def __enter__(self):
if self.filename:
if os.path.exists(self.filename):
overwrite = input(f"File '{self.filename}' already exists. Overwrite? (y/n): ").strip().lower()
if overwrite != 'y':
pmesg("Operation aborted. Output will not be redirected.", 'info', 1)
try:
self.file = open(self.filename, 'w')
sys.stdout = self.file
except IOError as e:
pmesg(f"Unable to write to file '{self.filename}':\n {str(e)}", 'error', 1)
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.close()
sys.stdout = self.original_stdout
class Colors:
BLUE = '\033[94m' # BLUE
GREEN = '\033[92m' # GREEN
YELLOW = '\033[93m' # YELLOW
RED = '\033[91m' # RED
RESET = '\033[0m' # Reset
def pmesg(message, level="info", exitcode=None):
"""
Prints a message based on the level and handles program exit if needed.
:param message: message to print
:param level: severity level ('info', 'warning', 'error').
:param exit_code: If provided, exits the program with this code.
"""
prog = os.path.basename(sys.argv[0])
if level == "error":
print(f"{prog}: error: {message}", file=sys.stderr)
elif level == "warning":
print(f"{prog}: warning: {message}", file=sys.stderr)
else:
print(f"{prog}: info: {message}")
if exitcode is not None:
sys.exit(exitcode)
def parse_arguments():
# Parse command-line arguments
parser = argparse.ArgumentParser(description="Data Pump Log Analyzer")
# positional arguments
# parser.add_argument('files', nargs='+', help="specify one or two Data Pump logfiles")
parser.add_argument('file', nargs=1, type=str, help="specify a Data Pump logfile")
# Optional mode options
parser.add_argument('-v', '--version', action='version', version=f'%(prog)s {__version__}')
parser.add_argument('-e', '--error', metavar='MESSAGE', nargs='*', help="show error details (optionally specify error(s) as a filter")
parser.add_argument('-o', '--object', action='store_true', help="show object type details")
parser.add_argument('-w', '--worker', action='store_true', help="show worker details")
parser.add_argument('-s', '--schema', metavar='SCHEMA', nargs='*', help="show schema details (optionally specify schema(s) as a filter")
parser.add_argument('-t', '--table', metavar='TABLE', nargs='*', help="show table details (optionally specify table(s) as a filter")
parser.add_argument('-i', '--instance', action='store_true', help="show instance details (starting 21c)")
parser.add_argument('-a', '--all', action='store_true', help="show complete output")
# Optional additional options
parser.add_argument('--sort', metavar='<column>', type=str, help="specify column name to sort the tables by")
parser.add_argument('--top', metavar='<N|all>', type=str, help="specify number of top rows to display (use 'all' for no limit)")
parser.add_argument('--output', metavar='<filename>', type=str, help="specify output file. For HTML output, use .htm or .html extension")
args = parser.parse_args()
toprows = None
if args.top == 'all':
# Interpret 'all' as no limit
toprows = None
elif args.top is not None:
# Convert to integer if top argument was specified
try:
toprows = int(args.top)
except ValueError:
parser.error("--top argument must be a number or 'all'.")
return args, toprows
def get_extension(filename):
"""
Gets and returns the file extension for a given file
:param filename: file
"""
_, ext = os.path.splitext(filename.lower())
return 'html' if ext in ('.htm', '.html') else 'text'
def format_size(size_mb):
"""
Converts and formats a size in megabytes (MB) to the appropriate unit (KB, MB, GB, TB).
:param size_mb: Size in MB
"""
if size_mb < 1:
return f"{size_mb * 1024:.2f} KB"
elif size_mb < 1024:
return f"{size_mb:.2f} MB"
elif size_mb < 1024 * 1024:
return f"{size_mb / 1024:.2f} GB"
else:
return f"{size_mb / 1024 / 1024:.2f} TB"
def format_time(seconds):
"""
Converts seconds into readable time format with hours, minutes and seconds
Currently no in use
:param seconds: Seconds
"""
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f"{hours}h {minutes}m {seconds}s" if hours else f"{minutes}m {seconds}s" if minutes else f"{seconds}s"
def is_defaultdict_empty(d):
"""Check if a defaultdict is effectively empty (contains only default values)."""
if not isinstance(d, defaultdict):
return not bool(d)
return all(
(isinstance(v, dict) and not v) or
(isinstance(v, set) and not v) or
(isinstance(v, (int, float)) and v == 0)
for v in d.values()
)
def file_valid(report):
"""
Checks if some variable that are reported are found in the specified logfile
:param report: Displayed report information
"""
# List of variables to check in the report
vars_check = ['operation', 'starttime', 'jobname']
# Check specific variables in the report
vars_unset = [var for var in vars_check if not report.get(var)]
is_valid = len(vars_unset) == 0
return {
'valid': is_valid,
'vars_unset': vars_unset
}
def file_metrics(dict_list):
"""
Checks if additional information is found in logfile when METRICS is specified
:param dict_list: List of dictionaries
"""
# Check if specific dictionaries are effectively empty
empty_dicts = [dict_name for dict_name in dict_list
if is_defaultdict_empty(globals().get(dict_name, {}))]
is_valid = len(empty_dicts) == 0
return {
'valid': is_valid,
'empty_dicts': empty_dicts
}
def clean_error_messages(error, patterns):
"""
Remove schema and object names from ORA messages
:param error: error message
:param patterns: regex pattern how to remove the info
"""
cleaned_error = error
for pattern in patterns:
cleaned_error = re.sub(pattern, '', cleaned_error)
# Remove extra spaces
cleaned_error = re.sub(r'\s+', ' ', cleaned_error).strip()
return cleaned_error
def validate_files(files):
"""
Check if the files are valid and readable, and return their filenames along with modification timestamps
"""
files_valid = []
for file in files:
if os.path.isfile(file) and os.access(file, os.R_OK):
timestamp = datetime.fromtimestamp(os.path.getmtime(file)).strftime("%a %b %d %H:%M:%S %Y")
files_valid.append((file, timestamp))
else:
pmesg(f"file '{file}' is not valid or not readable", 'error', 1)
return files_valid
def safe_get(record, key, default=0):
"""Safely get a value from a dictionary with a default if the key is not found."""
return record.get(key, default) if isinstance(record, dict) else default
def print_report_header(title):
"""Prints report header"""
print(f"\n{'=' * (len(title)+2)}\n {title}\n{'=' * (len(title)+2)}\n")
def print_section_header(title):
"""Prints section header"""
print(f"\n{title}\n{'~' * len(title)}")
def print_aligned(label, value, width=20, color=Colors.RESET):
"""Formatted print output with fixed width"""
if sys.stdout.isatty():
print(f"{indent}{label:<{width}}{color}{value}{Colors.RESET}")
else:
print(f"{indent}{label:<{width}}{value}")
def print_report(report, files_info):
"""
Print the text report
:param report: report dict
:param files_info: files information
"""
max_label_length = 28
print_report_header("Data Pump Log Analyzer")
# print_section_header("DPLA Details")
print_aligned("Version:", report['version'], max_label_length)
print_aligned("Arguments:", report['argslist'], max_label_length)
print_aligned("Generated:", report['generated'], max_label_length)
print_section_header("Logfile Details")
for file, timestamp, metrics, mtext, mcolor, mclass in files_info:
print_aligned("Analyzed File:", os.path.basename(file), max_label_length)
print_aligned("File Timestamp:", timestamp, max_label_length)
print_aligned("Metrics:", mtext, max_label_length, mcolor)
print_section_header("Operation Details")
print_aligned("Operation:", report['operation'] or "Not found", max_label_length)
print_aligned("Data Pump Version:", report['dpversion'] or "Not found", max_label_length)
print_aligned("DB Info:", report['dbinfo'] or "Not found", max_label_length)
print_aligned("Job Name:", report['jobname'] or "Not found", max_label_length)
print_aligned("Status:", report['opstatus'] or "Not found", max_label_length, report['opcolor'])
print_aligned(" Processing:", report['processing'], max_label_length)
print_aligned("Errors:", report['errors'], max_label_length, report['errcolor'])
print_aligned(" ORA- Messages:", report['oramsgs'], max_label_length, report['oracolor'])
print_aligned("Start Time:", report['starttime'] or "Not found", max_label_length)
print_aligned("End Time:", report['endtime'] or "Not found", max_label_length)
print_aligned("Runtime:", report['runtime'] or "Not found", max_label_length)
max_label_length = 28
print_section_header("Data Processing")
print_aligned("Parallel Workers:", report['workers'] or "Not found", max_label_length)
print_aligned("Schemas:", report['schemas'] or "Not found", max_label_length)
print_aligned("Objects:", report['objects'] or "Not found", max_label_length)
print_aligned("Data Objects:", report['dobjects'] or "Not found", max_label_length)
print_aligned("Overall Size:", report['totalsize'] or "Not found", max_label_length)
def print_table(headers, rows, alignments, summary=None):
"""
Print a table with dynamic column widths, headers, rows, and alignments.
:param headers: List of header titles
:param rows: List of row data (each row is a list of values)
:param alignments: List of alignments for each column ('<' for left, '>' for right)
:param summary: List of summary
"""
# Calculate column widths
col_widths = [
max(len(str(item)) for item in [header] + [row[idx] for row in rows]) + 4
for idx, header in enumerate(headers)
]
# Header and separator
header_row = " ".join(f"{headers[idx]:{alignments[idx]}{col_widths[idx]}}" for idx in range(len(headers)))
separator_segments = [
"-" * (width) + " " for width in col_widths[:-1]
] # Create segments for all but the last column
separator_segments.append("-" * col_widths[-1]) # Handle the last column without the trailing space
separator = "".join(separator_segments) # Join all segments together
# Print the header and separator
ptable = f"{indent}{header_row}\n"
ptable += f"{indent}{separator}\n"
# Print rows
for row in rows:
ptable += f"{indent}{' '.join(f'{str(row[idx]):{alignments[idx]}{col_widths[idx]}}' for idx in range(len(row)))}\n"
# Print final separator before summary if summary is provided
if summary:
ptable += f"{indent}{separator}\n" # Separator before summary
ptable += f"{indent}{' '.join(f'{str(summary[idx]):{alignments[idx]}{col_widths[idx]}}' for idx in range(len(summary)))}\n"
# Print final separator
ptable += f"{indent}{separator}"
return ptable
def section_description(sort, top, filter):
"""Formats the output if filter, sort or top are set"""
desc = [f"sorted by {sort}"]
if top is not None:
desc.append(f"top {top}")
if isinstance(filter, list) and len(filter) > 0:
formatted_filters = ', '.join(filter)
desc.append(f"filtered by {formatted_filters}")
# Join all parts with commas and close with a parenthesis
return f"({', '.join(desc)}):\n"
def find_matching_column(sort_key, sample_dict, header):
"""Find matching column for sort operation"""
lowercase_sort_key = sort_key.lower()
# Check if the sort key matches the header (dictionary key)
if lowercase_sort_key == header.lower() or header.lower().startswith(lowercase_sort_key):
return header
# Check other dictionary values
for key in sample_dict.keys():
if key.lower().startswith(lowercase_sort_key):
return key
return None
def safe_sort(items, sort_key, header, section, reverse=True):
"""Sort items based on argument or default value"""
if not items:
return [], None
sample_dict = next(iter(items.values()))
matching_column = find_matching_column(sort_key, sample_dict, header)
if matching_column is None:
# If no matching column is found, use the default value for that section
matching_column = defaults[section]['sort']
if matching_column == header:
# Sort by the dictionary key (first column)
sorted_items = sorted(
items.items(),
key=lambda x: x[0],
reverse=False
)
else:
# Sort by the matching column in the dictionary values
sorted_items = sorted(
items.items(),
key=lambda x: safe_get(x[1], matching_column),
reverse=reverse
)
return sorted_items, matching_column
def print_section(args, toprows, section, sectitle, colname, stats, filter=None):
"""
Print a section of output based on the stats data structure.
:param args: script arguments
:param toprows: top rows to display
:param section: the name of the section (e.g., 'worker', 'object').
:param colname: the name of the first column in the table
:param stats: stats data for the section
:param filter: argument specified filter
"""
sort = args.sort if args.sort else defaults[section]['sort']
top = toprows if args.top else defaults[section]['top']
# Applying filter
if isinstance(filter, list) and len(filter) > 0:
filtered_stats = {k: v for k, v in stats.items() if any(f.upper() in k.upper() for f in filter)}
else:
filtered_stats = stats
# Sort rows
sorted_rows, actual_sort = safe_sort(filtered_stats, sort, colname, section)
# Apply top
final_rows = sorted_rows[:top]
print_section_header(f"{sectitle.upper()}")
print(section_description(actual_sort, top, filter))
# Assume all items have the same keys, use the first item to determine fields
if final_rows:
fields = list(final_rows[0][1].keys()) # Dynamically get fields from the stats dictionary
headers = [colname.title()] + [field.capitalize() for field in fields]
alignments = ['<'] + ['>' for _ in fields]
# Calculate totals
# Initialize totals with appropriate starting values
totals = {field: 0 if aggr_methods.get(field, aggr_default) == sum else float('-inf') for field in fields}
for _, stat in final_rows:
for field in totals:
value = stat.get(field, 0) # Get the value safely
if isinstance(value, (int, float)): # Check if the value is numeric
agg_func = aggr_methods.get(field, aggr_default) # Get the appropriate aggregation function
if agg_func == sum:
totals[field] += value
elif agg_func == max:
totals[field] = max(totals[field], value)
elif value == 'N/A':
totals[field] = ''
# Prepare rows for table
rows = [
[row[0]] + [format_size(row[1][field]) if field == 'size' else row[1][field] for field in fields]
for row in final_rows
]
# Prepare summary
summary = ["Total"] + [
format_size(totals[field]) if field == 'size' else totals[field] for field in fields
]
print(print_table(headers, rows, alignments, summary))
else:
print('No data available.')
def html_head():
"""Head code for the html report"""
return f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex">
<title>Data Pump Log Analyzer</title>
{html_css()}
<noscript>
<style>
.collapse-toggle {{ display: none !important; }}
#scrollToTop {{ display: none !important; }}
.sticky-header {{ position: static !important; }}
#toc-toggle {{ display: none !important; }}
#toc-sidebar {{ display: none !important; }}
.sort-icons {{ display: none !important; }}
.search-container {{ display: none !important; }}
</style>
</noscript>
</head>
"""
def html_css():
"""CSS code for the html report"""
return """
<style>
:root {
--color-primary: #086c91;
--bg-color: #EDEFF1;
--text-color: #2c3e50;
--header-bg-color: var(--color-primary);
--header-text-color: #fff;
--header-shadow: 0px 0px 0px var(--color-primary);
--border-color: #ccd0d5;
--arrow-color: rgba(255, 255, 255, 0.5);
--arrow-color-active: #fff;
--icon-color-light: #3498db;
--icon-color-dark: #f39c12;
--input-bg-color: #fff;
--input-border-color: var(--border-color);
--input-focus-border-color: var(--color-primary);
--card-header-text-color: var(--color-primary);
--card-bg-color: #fff;
--card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
--table-bg-color: var(--color-primary);
--row-odd-color: #f5f6f7;
--row-even-color: #ffffff;
--row-hover-color: #dadde1;
--total-row-bg-color: var(--card-bg-color);
--total-row-text-color: var(--text-color);
--toc-bg-color: var(--card-bg-color);
--totop-color: 8,108,145;
--status-red-color: #d32f2f;
--status-yellow-color: #f57f17;
--status-green-color: #2e7d32;
--collicon: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24'><path fill='rgba(189, 195, 199, 1)' d='M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z'></path></svg>");
}
[data-theme='dark'] {
--color-primary: #1cbff8;
--bg-color: #21232A;
--text-color: #f0f0f0;
--header-bg-color: #0F1318;
--header-text-color: #fff;
--header-shadow: 0px 0px 7px var(--color-primary);
--border-color: #606770;
--arrow-color: rgba(236, 240, 241, 0.5);
--arrow-color-active: #fff;
--input-bg-color: #2D3039;
--input-border-color: var(--border-color);
--input-focus-border-color: var(--color-primary);
--card-header-text-color: var(--color-primary);
--card-bg-color: #2D3039;
--card-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
--table-bg-color: var(--bg-color);
--row-odd-color: #383C44;
--row-even-color: #2D3039;
--row-hover-color: #4A4F5A;
--total-row-bg-color: var(--card-bg-color);
--total-row-text-color: var(--header-text-color);
--toc-bg-color: var(--header-bg-color);
--totop-color: 28,191,248;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 0;
background-color: var(--bg-color);
color: var(--text-color);
transition: all 0.3s ease;
}
.no-js {
color: red;
font-weight: bold;
}
.container {
max-width: 1200px;
margin: 10px auto;
padding: 20px;
}
.sticky-header {
position: sticky;
top: 0;
background-color: var(--header-bg-color);
color: var(--header-text-color);
padding: 12px 20px;
z-index: 1001;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
display: flex;
align-items: center;
box-shadow: var(--header-shadow);
}
h1 {
margin: 0;
}
.info-section {
background-color: var(--card-bg-color);
border-radius: 10px;
padding: 20px;
margin-bottom: 30px;
margin-top: 20px;
box-shadow: var(--card-shadow);
}
.info-section h2 {
color: var(--card-header-text-color);
font-size: 24px;
margin: 0px;
border-bottom: 1px solid var(--border-color);
padding-bottom: 10px;
cursor: pointer;
display: flex;
align-items: center;
}
.section-content {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.section-contenttab {
}
.label {
font-weight: bold;
}
.value {
}
.highlight {
display: inline-block;
width: fit-content;
padding: 2px 8px;
margin-left: -8px;
border-radius: 12px;
color: var(--header-text-color);
font-size: 0.95rem;
}
.highlight.warn {
background-color: var(--status-yellow-color);
}
.highlight.ok {
background-color: var(--status-green-color);
}
.highlight.fail {
background-color: var(--status-red-color);
}
.collapse-toggle {
background: var(--collicon) 50% / 1.4rem 1.4rem;
height: 1.4rem;
width: 1.4rem;
transform: rotate(180deg);
margin-right: 6px;
}
.collapse-toggle.collapsed {
transform: rotate(90deg);
}
.section-content,
.section-contenttab{
overflow: hidden;
margin-top: 20px;
}
.section-content.collapsed,
.section-contenttab.collapsed {
max-height: 0;
margin-top: 0px;
}
.sort-icons {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-direction: column;
line-height: 0.5;
}
.sort-icons::before,
.sort-icons::after {
content: '';
display: block;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
}
.sort-icons::before {
border-bottom: 5px solid var(--arrow-color);
margin-bottom: 3px;
}
.sort-icons::after {
border-top: 5px solid var(--arrow-color);
}
th.asc .sort-icons::before {
border-bottom-color: var(--arrow-color-active);
}
th.desc .sort-icons::after {
border-top-color: var(--arrow-color-active);
}
#theme-toggle {
background: none;
border: none;
cursor: pointer;
font-size: 24px;
color: var(--header-text-color);
transition: color 0.3s ease;
}
#theme-toggle:hover {
color: var(--bg-color);
}
.search-container {
margin-bottom: 20px;
}
.searchInput {
width: 100%;
padding: 12px;
border: 1px solid var(--input-border-color);
border-radius: 25px;
background-color: var(--input-bg-color);
color: var(--text-color);
font-size: 16px;
transition: all 0.3s ease;
box-sizing: border-box;
}
.searchInput:focus {
border-color: var(--input-focus-border-color);
outline: none;
}
.noResults {
display: none;
color: var(--text-color);
text-align: center;
padding: 20px;
}
table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
border: 1px solid var(--border-color);
background-color: var(--card-bg-color);
border-radius: 8px;
overflow: hidden;
}
th, td {
padding: 12px 15px;
text-align: left;
}
table th:not(.text-column),
table td:not(.text-column) {
text-align: right;
}
table th.text-column,
table td.text-column {
text-align: left;
}
th {
background-color: var(--table-bg-color);
color: var(--header-text-color);
cursor: pointer;
position: relative;
user-select: none;
white-space: nowrap;
font-weight: 600;
padding-right: 30px;
}
tbody tr.odd-row {
background-color: var(--row-odd-color);
}
tbody tr.even-row {
background-color: var(--row-even-color);
}
tbody tr:hover {
background-color: var(--row-hover-color);
}
tfoot {
font-weight: bold;
background-color: var(--total-row-bg-color);
color: var(--total-row-text-color);
}
tfoot .total-row {
display: table-row;
}
tfoot .filtered-total-row {
display: none;
}
tfoot td {
border-top: 1px solid var(--border-color);
}
#scrollToTop {
position: fixed;
bottom: 20px;
right: 20px;
background-color: rgba(var(--totop-color),0.7);
color: white;
border: none;
border-radius: 50%;
width: 48px;
height: 48px;
text-align: center;
cursor: pointer;
display: none;
z-index: 1000;
transition: all 0.3s ease;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
#scrollToTop .arrow {
display: block;
width: 8px;
height: 8px;
border-top: 2px solid white;
border-left: 2px solid white;
transform: rotate(45deg);
margin: 6px auto 0;
transition: all 0.3s ease;
}
#scrollToTop:hover {
background-color: rgba(var(--totop-color),0.9);
}
#toc-sidebar {
position: fixed;
left: -250px;
margin-top: 40px;
top: 0px;
width: 250px;
height: 100%;
background-color: var(--toc-bg-color);
transition: left 0.3s ease;
z-index: 1000;
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}
#toc-sidebar.open {
left: 0;
}
.toc-toggle {
background-color: transparent;
color: var(--header-text-color);
border: none;
font-size: 24px;
cursor: pointer;
margin-right: 10px;
}
.toc-content {
padding: 20px;
overflow-y: auto;
height: 100%;
}
.toc-content ul {
list-style-type: none;
padding-left: 0;
}
.toc-content li {
margin-bottom: 10px;
}
.toc-content a {
color: var(--text-color);
text-decoration: none;
transition: color 0.3s ease;
}
.toc-content a:hover {
color: var(--color-primary);
}
@media (max-width: 768px) {
.container {
padding: 10px;
}
th, td {
padding: 8px 10px;
}
}
footer {
background-color: var(--card-bg-color);
color: var(--text-color);
padding: 20px 0;
border-top: 1px solid var(--border-color);
}
.footer-content {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
text-align: center;
}
.footer-content p {
margin: 5px 0;
}
.footer-content a {
color: var(--color-primary);
}
</style>
"""
def html_js():
"""Java Script code for the html report"""
return """
<script>
// Event listener for DOM content loaded
document.addEventListener('DOMContentLoaded', () => {
initializeTheme();
setupCollapsibleSections();
setupScrollToTop();
setupContentMenuClose();
setupEventListeners();
initializeTables();
});
function initializeTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
document.body.setAttribute('data-theme', savedTheme);
updateThemeToggleIcon(savedTheme);
}
function setupEventListeners() {
document.getElementById('theme-toggle').addEventListener('click', toggleTheme);
document.getElementById("scrollToTop").addEventListener("click", scrollToTop);
document.getElementById('toc-toggle').addEventListener('click', toggleTOC);
document.querySelectorAll('#toc-sidebar a, #theme-toggle').forEach(element => {
element.addEventListener('click', handleSidebarLinkClick);
});
}
function initializeTables() {
document.querySelectorAll('table').forEach(table => {
updateRowStyles(table);
updateFooter(table, '**', '');
// Set up click listeners for all th elements
table.querySelectorAll('th').forEach(th => {
th.addEventListener('click', function() {
const columnIndex = this.cellIndex;
const type = this.getAttribute('data-type') || 'str'; // Get type from data attribute
sortTable(table, columnIndex, type);
});
});
});
// Set up search input listeners
document.querySelectorAll('.searchInput').forEach(input => {
input.addEventListener('input', handleSearchInput);
});
}
function toggleTheme() {
const body = document.body;