forked from Mellanox/linux-sysinfo-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysinfo-snapshot.py
More file actions
executable file
·6722 lines (6143 loc) · 306 KB
/
sysinfo-snapshot.py
File metadata and controls
executable file
·6722 lines (6143 loc) · 306 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/python3
# -*- python -*-
#
# Author: Nizar Swidan nizars@mellanox.com -- Created: 2015
# Modified: Anan Fakheraldin ananf@mellanox.com -- Modified: 2018
# Jeries Haddad jeriesh@mellanox.com -- Modified: 2019
# Ahmad Awwad ahmadaw@nvidia.com -- Modified: 2025
__author__ = 'nizars'
import warnings
import subprocess
import sys
import re
import os
import time
import signal
import shutil
import platform
import csv
from optparse import OptionParser
from itertools import chain
import hashlib
import datetime
import inspect
import threading
import shutil
try:
import json
json_found = True
except ImportError:
json_found = False
warnings.filterwarnings('ignore')
COMMAND_CSV_HEADER = 'Command'
INVOKED_CSV_HEADER = 'Approved'
FLAG_RELATED_HEADER = "related flag"
DEFAULT_CONFIG_PATH = './config.csv'
DEFAULT_PATH = '/tmp/'
SUCCESS_STATUS = 0
FAILED_STATUS = 1
HIDE_STATUS = 2
######################################################################################################
# no_log_status_output
# get_status_output but without logging to the command log
# Only used in few instances where logging is not mandatory
def standarize_str(tmp):
''' if python version major is 3, then tmp is unicode (utf-8) byte string
and need to be converted to regular string
'''
if sys.version_info[0] == 2:
return tmp.strip()
elif sys.version_info[0] == 3:
return tmp.decode("utf-8", 'ignore').strip()
else:
return tmp.strip()
def no_log_status_output(command, timeout='10s'):
command = 'timeout '+ timeout + ' ' + command
try:
p = subprocess.Popen([command], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1024*1024)
stdout, stderr = p.communicate()
return p.returncode, standarize_str(stdout)
except:
error = "\nError while reading output from command - " + command + "\n"
return 1, error
###############################################################################
## function-based wrapper using a custom class to implement this behavior without requiring external packages
class LooseVersion:
def __init__(self, version):
self.version = version
self.parts = self._parse_version(version)
def _parse_version(self, version):
"""
Normalize a version string into components (numeric and non-numeric parts).
"""
return [int(part) if part.isdigit() else part for part in re.split(r'(\d+)', version) if part]
def _compare(self, other):
"""
Compare the version with another version.
"""
for self_part, other_part in zip(self.parts, other.parts):
if self_part < other_part:
return -1
elif self_part > other_part:
return 1
# Handle cases where versions have different lengths
if len(self.parts) < len(other.parts):
return -1
elif len(self.parts) > len(other.parts):
return 1
return 0
def __lt__(self, other):
return self._compare(other) < 0
def __le__(self, other):
return self._compare(other) <= 0
def __eq__(self, other):
return self._compare(other) == 0
def __ne__(self, other):
return self._compare(other) != 0
def __gt__(self, other):
return self._compare(other) > 0
def __ge__(self, other):
return self._compare(other) >= 0
######################################################################################################
# GLOBAL GENERAL VARIABLES
version = "3.7.9.6"
sys_argv = sys.argv
len_argv = len(sys.argv)
driver_required_loading = False
is_MST_installed = False
is_MFT_installed = False
MFT_INSTALLED_MESSAGE = ""
are_inband_cables_loaded = False # If in-band cables were loaded before user runs snapshot
mst_devices_exist = False
all_sm_on_fabric = []
is_command_string = False
#active_subnets --> device_name
# --> port
active_subnets = {}
#installed_cards_ports --> device_name
# --> port
installed_cards_ports = {}
pf_devices = []
asap_devices = []
mtusb_devices = []
vf_pf_devices = []
mft_tools_pci_devices = []
config_dict = {}
local_mst_devices = []
json_flag = False
verbose_flag = False
verbose_count = 0
mlnx_cards_status = -1
ethtool_command = ""
path_is_generated = 0
path = "/tmp/"
config_path = ""
parser = ""
section_count=1
ibdiagnet_res = ""
file_name = ""
ibdiagnet_is_invoked = False
st_saquery = 1
sys_class_net_exists = False
blueos_flag = False
missing_critical_info = False # True --> Sysinfo-snapshot is missing some critical debugging information
non_root = False
nvsm_dump_flag = False
CANCELED_STATUS = 4
######################################################################################################
# Initialize Environment Variables
is_ib, ib_res = no_log_status_output("which ibnetdiscover 2>/dev/null")
date_file = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
sta, date_cmd = no_log_status_output("date")
st_infiniband_devices, infiniband_devices = no_log_status_output('ls /sys/class/infiniband')
######################################################################################################
# SR-IOV Global Variables
sriov_version = "1.0.0"
sriov_exists = False
sriov_commands_collection = ["bridge fdb show dev p3p1", "ip link", "ip_link_show_devices", "lspci_vf"]
available_sriov_commands_collection = []
sriov_internal_files_collection = ["/etc/infiniband/openib.conf.rpmsave", "/etc/modprobe.d/mlnx.conf"]
available_sriov_internal_files_collection = []
sriov_commands_dict = {}
sriov_internal_files_dict = {}
######################################################################################################
# Performance Tunning Analyze Global Variables
perf_version = "1.0.1"
perf_setting_collection = ["IRQ Affinity", "Core Frequency", "Hyper Threading", "IP Forwarding", "AMD", "Memory Allocation", "PCI Configurations", "Perf Samples", "Bandwidth", "Latency"]
eth_setting_collection = ["IP Forwarding"]
ib_setting_collection = ["Bandwidth", "Latency", "Perf Samples"]
setting_without_status = ["IP Forwarding", "Bandwidth", "Latency", "Perf Samples"]
not_available = "N/A"
not_present = "Not Present"
present = "Present"
perf_status_dict = {}
perf_val_dict = {}
perf_external_files_collection = [["mlnx_tune -r -i ", "mlnx_tune_r"]]
perf_samples = {}
bandwidth = {}
latency = {}
######################################################################################################
# FLAGS
# ibdiagnet_flag = False, means --ibdiagnet was not provided
# ibdiagnet_flag = True, means --ibdiagnet was provided
ibdiagnet_flag = False
# ibdiagnet_ext_flag = True, means use replacment ibdiagent command
ibdiagnet_ext_flag = False
ibdiagnet_error = False
openstack_flag = False
asap_flag = False
asap_tc_flag = False
rdma_debug_flag = False
gpu_flag = False
# no_fw_flag = True, means not to add fw_collection commands to the out file
# no_fw_flag = False, means to add fw_collection commands to the out file
# no_fw_flag can be converted to True by running the tool with --no_fw flag
no_fw_flag = False
# pcie_flag = False, means not to add pcie_collection commands to the out file
# pcie_flag = True, means to add pcie_collection commands to the out file
# pcie_flag can be converted to True by running the tool with --pcie flag
pcie_flag = False
# mtusb_flag = False, means not to add I2C dump files
# mtusb_flag = True, means to add I2C dump files
# mtusb_flag can be converted to True by running the tool with --mtusb flag
# If mtusb flag is true it runs "mst start" and then return it to the old status
mtusb_flag = False
# check_fw_flag = False, means not to add any check to adapter firmware if latest
# check_fw_flag = True, means to add any check to adapter firmware if latest
# check_fw_flag can be converted to True by running the tool with --check_fw
# If check_fw flag is true it runs online check for the latest fw for this psid
check_fw_flag = False
# generate_config_flag = False, means not to generate a new config file
# generate_config_flag = True, means to generate a new config file
# this should be invoked with before any release with --ibdiagnet -fw -p --pcie --check_fw
generate_config_flag = False
# config_file_flag = False, means not to use default configuration all commands should be invoked
# config_file_flag = True, means to add any check to adapter firmware if latest
config_file_flag= False
#no_ib_flag = False, means to add ib commands to the out file
#no_ib_flag = True, means not to add ib commands to the out file
#no_ib_flag can be converted to True by running the tool with --no_ib
pcie_debug_flag = False
#pcie_debug_flag = False, means to run the tool normally and not PCIE_Debug run
#pcie_debug_flag = True, means to run the tool only for collecting PCIE_Debug info
no_ib_flag = False
keep_info_flag = False
trace_flag = False
interfaces_flag = False
#--with_inband_flag = False, means not to add in-band cable information
#--with_inband = True, means to add in-band cable information
#--with_inband can be converted to True by running the tool with --with_inband flag
with_inband_flag = False
# fsdump_flag = False, means not to add fsdump from firmware
# fsdump_flag = True, means to add fsdump from firmware
# fsdump_flag can be converted to True by running the tool with --fsdump_flag
# If check_fw flag is true it runs online check for the latest fw for this psid
fsdump_flag = False
no_fw_regdumps_flag = False
no_mstconfig_flag = False
no_cables_flag = False
all_var_log_flag = False
if "--no_ib" in sys.argv:
no_ib_flag = True
#perf_flag = False, means not to include more performance commands/function like ib_write_bw and ib_write_lat
#no_ib_flag = True, means include more performance commands/functions to the out file
#perf_flag can be converted to True by running the tool with -p|--perf
perf_flag = False
#ufm_flag = False, means not to include ufm logs to the out file
#ufm_flag = True, means to include ufm logs to the out file
#ufm_flag can be converted to True by running the tool with --ufm
ufm_flag = False
######################################################################################################
# GLOBAL LISTS
fw_collection = ["fwtrace", "mlxmcg -d", "mlxdump", "mst_commands_query_output"]
pcie_collection = ["lspci -vvvxxxxx",]
ufm_collection = ["ufm_logs"]
fsdump_collection = ["mlxdump"]
asap_collection = ["asap_parameters"]
asap_tc_collection = ["asap_tc_information"]
rdma_debug_collection = ["rdma_tool"]
gpu_command_collection = ["nvidia-smi topo -m","nvidia-smi","lspci -tv |grep 'NVIDIA' -A7","nvidia-smi -q -d clock","nvidia-smi --format=csv --query-supported-clocks=gr,mem","ib_write_bw -h | grep -i cuda","modinfo nv_peer_mem"\
,"/usr/local/cuda/extras/demo_suite/deviceQuery","/etc/init.d/nv_peer_mem status"\
,"bandwidthTest","hwloc-ls"]
PCIE_debugging_collection = ["dmidecode", "performance_lspci", "lscpu", "mlxlink / mstlink","mst_commands_query_output","dmesg" ]
ib_collection = []
commands_collection = ["ip -s -s link show", "ip -s -s addr show", "ovs-vsctl --version", "ovs-vsctl show", "ovs-dpctl show", "brctl --version", "brctl show", "arp -an", "free", "blkid -c /dev/null | sort", "date", "time", \
"df -lh", "mlnx_ethtool_version", "ethtool_version", "ethtool_all_interfaces", "fdisk -l", "hostname", "ibdev2netdev", "ibdev2pcidev", "ibv_devinfo -v", "ifconfig -a", \
"initctl list", "ip m s", "ip n s", "iscsiadm --version", "iscsiadm -m host", "iscsiadm -m iface", "iscsiadm -m node", "iscsiadm -m session", "lscpu", "lsmod", "lspci -tv", \
"mount", "asap_parameters", "asap_tc_information","rdma_tool", "netstat -i", "netstat -nlp", "netstat -nr", "netstat -s", "numactl --hardware", "ofed_info", "ofed_info -s", "ompi_info", "ip route show table all", "service --status-all", \
"service cpuspeed status", "service iptables status", "service irqbalance status", "show_irq_affinity_all", "tgtadm --mode target --op show", "tgtadm --version", "tuned-adm active", "ulimit -a", "uname", \
"yy_MLX_modules_parameters", "sysclass_IB_modules_parameters", "proc_net_bonding_files","Mellanox_Nvidia_pci_buses" ,"sys_class_net_files", "teamdctl_state", "teamdctl_state_view", "teamdctl_config_dump", "teamdctl_config_dump_actual", "teamdctl_config_dump_noports", \
"ip -6 addr show", "ip -6 route show", "modinfo", "show_pretty_gids", "dkms status",\
"gcc --version", "python_used_version", "cma_roce_mode", "cma_roce_tos", "service firewalld status", "mlnx_qos_handler", "devlink_handler", "switchdev_legacy_mode","se_linux_status", \
"ufm_logs", "virsh version","virsh list --all", "virsh vcpupin", "sys_class_infiniband_ib_paameters", "sys_class_net_ecn_ib","roce counters","route -n","numastat -n","NetworkManager --print-config","networkManager_system_connections","USER",\
"congestion_control_parameters","doca_pcc_counter","ecn_configuration","lsblk", "journalctl -u mlnx_snap","flint -d xx q","virtnet query --all","journalctl -u virtio-net-controller","/etc/mlnx_snap","snap_rpc.py emulation_functions_list","snap_rpc.py controller_list"\
,"nvidia-smi topo -m", "nvidia-smi", "lspci -tv |grep 'NVIDIA' -A7", "nvidia-smi -q -d clock", "nvidia-smi --format=csv --query-supported-clocks=gr,mem", "ib_write_bw -h | grep -i cuda", "modinfo nv_peer_mem",\
"bandwidthTest"\
, "/etc/init.d/nv_peer_mem status","cuda_deviceQuery","ibstatus","ibstat","ucx_info -v", "dpkg -l net-tools | cat", "mdadm -D /dev/md*","hwloc-ls -v","systemctl list-units","nvsm dump health","lspci -nnPP -d 15b3:","lspci -nnPP -d ::0302"\
,"lldptool -ti eth$i","lldptool -tin eth$i","lldptool -t -i eth$i -V APP -c","lldptool -t -i eth$i -V PFC","ip route show","ip -6 -s -s addr show"]
mft_commands_collection = ["mst_commands_query_output", "mst status", "mst status -v", "mlxcables", "mlxdump", "mlxlink / mstlink", "mget_temp_query",
"mlxreg -d -y --get --op 'cmd_type' --reg_name PPCC", "mlxmcg -d", "mlxreg -d --reg_name ROCE_ACCL --get",
"flint -v", "mstflint -v"]
commands_collection.extend(mft_commands_collection)
available_commands_collection = [[],[]]
available_PCIE_debugging_collection_dict = {}
# old/new kernel tracer file path
OLD_KERNEL_TRACER_FILE = "/sys/kernel/debug/tracing/trace"
NEW_KERNEL_TRACER_FILE = "/sys/kernel/tracing/trace"
# Command groups for organized display
available_mft_commands = []
available_network_commands = []
available_system_commands = []
available_gpu_commands = []
available_rdma_commands = []
available_service_commands = []
available_storage_commands = []
available_performance_commands = []
fabric_commands_collection = [ "ib_mc_info_show", "sm_version", "Multicast_Information", "perfquery_cards_ports"]
fabric_multi_sub_commands_collection = ["ibdiagnet", "ib_find_bad_ports", "ib_find_disabled_ports", "ib_topology_viewer", "ibhosts", "ibswitches", "sminfo", "sm_status", "sm_master_is", "ib_switches_FW_scan"]
available_fabric_commands_collection = []
internal_files_collection = ["/sys/devices/system/clocksource/clocksource0/current_clocksource", "/sys/fs/cgroup/net_prio/net_prio.ifpriomap", "/etc/opensm/partitions.conf","/etc/opensm/opensm.conf", "/etc/default/mlnx_snap","/etc/modprobe.d/vxlan.conf", "/etc/security/limits.conf", "/boot/grub/grub.cfg","/boot/grub2/grub.cfg","/boot/grub/grub.conf","/boot/grub2/grub.conf", "/boot/grub/menu.lst","/boot/grub2/menu.lst","/etc/default/grub", "/etc/host.conf", "/etc/hosts", "/etc/hosts.allow", "/etc/hosts.deny", "/etc/issue", "/etc/modprobe.conf","/etc/udev/udev.conf" ,"/etc/ntp.conf", "/etc/resolv.conf", "/etc/sysctl.conf", "/etc/tuned.conf","/etc/dhcp/dhclient.conf","/etc/yum.conf","/etc/bluefield_version", "/proc/cmdline", "/proc/cpuinfo", "/proc/devices", "/proc/diskstats", "/proc/dma", "/proc/meminfo", "/proc/modules", "/proc/mounts", "/proc/net/dev_mcast", "/proc/net/igmp", "/proc/partitions", "/proc/stat", "/proc/sys/net/ipv4/igmp_max_memberships", "/proc/sys/net/ipv4/igmp_max_msf","/proc/uptime", "/proc/version", "/etc/rdma/rdma.conf","/etc/systemd/system/mlnx_interface_mgr@.service","/etc/systemd/system/sysinit.target.wants/openibd.service", "/proc/net/softnet_stat", "/proc/buddyinfo", "/proc/slabinfo", "/proc/pagetypeinfo","/etc/iproute2/rt_tables"]
available_internal_files_collection = []
# [field_name, file_name to cat]
external_files_collection = [["kernel config", "/boot/config-$(uname -r)"],["mlxcables --DDM/--dump","cables/mlxcables_options_output"] ,["config.gz", "/proc/config.gz"],["zoneinfo","/proc/zoneinfo"],[ "interrupts","/proc/interrupts"],["lstopo-no-graphics","lstopo-no-graphics"] ,["lstopo-no-graphics -v -c","lstopo-no-graphics -v -c"],["lspci","lspci"],["lshw","lshw"],["lspci -vvvxxxxx","lspci -vvvxxxxx"],["ps -eLo","ps -eLo"],["ucx_info -c", "ucx_info -c"],["ucx_info -f","ucx_info -f"],["sysctl -a","sysctl -a"], ["netstat -anp","netstat -anp"] ,["dmesg -T", "dmesg"], ["biosdecode", "biosdecode"], ["dmidecode", "dmidecode"], ["libvma.conf", "/etc/libvma.conf"], ["ibnetdiscover", ""], ["Installed packages", ""], ["Performance tuning analyze", ""], ["SR_IOV", ""],["other_system_files",""],["numa_node",""],["trace","/sys/kernel/debug/tracing/trace"],["lspci -nnvvvxxxx","lspci_nnvvvxxx"],["journalctl -k -o short-monotonic","journal"],["lspci -vv", "lspci_vv"]]
available_external_files_collection = []
copy_under_files = [["etc_udev_rulesd", "/etc/udev/rules.d/"], ["lib_udev_rulesd", "/lib/udev/rules.d/"]]
copy_openstack_dirs = [["conf_nova", "/var/lib/config-data/puppet-generated/nova_libvirt"], ["conf_nuetron", "/var/lib/config-data/puppet-generated/neutron/"]]
copy_openstack_files = [["logs_nova", "/var/log/containers/nova/nova-compute.log"], ["logs_neutron", "/var/log/containers/neutron/openvswitch-agent.log"]]
critical_failed_commands = [] # Critical commands that failed
running_warnings = []
#command not found
command_exists_dict = {}
#commands that are part of higher chain commands ,used when generating config file
sub_chain_commands = ["file: var/log/syslog", "file: var/log/messages", "file: var/log/boot.log", "mlnx_tune -i " , "ib_write_bw_test", "latency", "perf_samples", "mlxfwmanager --online-query-psid", "file: /sys/class/infiniband/*/iov", "file: /sys/class/infiniband/*/device/"]
critical_collection = PCIE_debugging_collection # List of all critical commands
critical_collection.append("general_fw_command_output")
critical_collection.append("mstcommand_d_handler")
critical_collection.append("load_modules")
supported_os_collection = ["redhat", "suse", "debian"]
###########################################################
# Get Status Ouptut
# (replacement old the depreciated call st, res = get_status_output("..")
#*****************************************************************************************************
# log_command_status
# A function to log every command invoked on the host: command, passed/filed, time taken
# A critical command is a command which is used for PCIE debugging. Found in PCIE_debugging_collection
def log_command_status(parent, command, status, res, time_taken, invoke_time):
global missing_critical_info
log_file = "/tmp/status-log-" + file_name
with open(log_file, 'a') as log:
status_message = "PASSED, time taken: {}".format(time_taken)
if status != 0:
failed_reason = "NOT FOUND" if "not found" in res.lower() or "no such file or directory" in res.lower() or "not invoked" in res.lower() else "FAILED"
status_message = "{}, time taken: {}".format(failed_reason, time_taken)
if parent in critical_collection:
missing_critical_info = True
critical_failed_commands.append("{} ---- {}".format(command, failed_reason))
log.write("{}:{} ---- {}\n".format(invoke_time, command, status_message))
#*****************************************************************************************************
# arrange_command_status_log
# A function to arrange the command log
# If one of the critical commads failed --> display failed critical commands in the first section of the file + a proper warning
# display running warnings
def arrange_command_status_log():
temp_log_path = "/tmp/status-log-" + file_name
with open(temp_log_path, 'r') as temp_log:
log_content = temp_log.read()
with open(path + file_name + "/status-log-" + file_name, 'w') as log:
#write invoked command
log.write("invoked command:\n")
log.write(' '.join(sys.argv))
log.write('\n')
if missing_critical_info:
log.write("\n\nWarning! The sysinfo-snapshot output failed to collect all essential information from the server.\n")
log.write("\nFailed critical debugging commands:\n")
for failed_command in critical_failed_commands:
log.write(failed_command + "\n")
if running_warnings:
log.write("\n\n------------------------------------------------------------------------------------------------------------------\n")
log.write("\nRunning warnings:\n")
for warning in running_warnings:
log.write(warning + "\n")
log.write("\n\n------------------------------------------------------------------------------------------------------------------\n")
log.write("\nFull log:\n")
log.write(log_content)
# After moving status log inside the TGZ file, remove it from /tmp
try:
os.remove(temp_log_path)
except BaseException as e:
with open(temp_log_path ,'a') as temp_log:
temp_log.write("\nError in removing status log from /tmp. Full path is: " + temp_log_path + "\n" + str(e))
#*****************************************************************************************************
# log
# A decorater that helps figure out the timing each command took, parent function, input / output of the invoked command
def log(f):
def wrap(*args, **kwargs):
time1 = time.time()
invoke_time = datetime.datetime.now()
ret = f(*args, **kwargs)
time2 = time.time()
st = ret[0]
res = ret[1]
time_taken = '{0:.3f}'.format((time2-time1))
invoked_command = args[0]
parent = inspect.stack()[1][3] # parent function who called the command
log_command_status(parent, invoked_command, st,res ,time_taken, invoke_time)
return ret
return wrap
def is_command_exists(command):
if sys.version_info[0] ==2:
from distutils.spawn import find_executable
if find_executable(command):
return True
else:
return False
elif sys.version_info[0] ==3:
import shutil
if shutil.which(command) is not None:
return True
else:
return False
@log
def get_status_output(command, timeout='10'):
command_with_timeout = "timeout " + timeout + "s " + command
try:
if " cat " in command_with_timeout:
filePath = command_with_timeout.split(" cat ")[1]
filePath = filePath.split("|")[0].strip()
if os.path.exists(filePath) and (not os.access(filePath, os.R_OK)):
return 1, "Cant read file " + filePath + " due to missing permissions"
elif not os.path.exists(filePath):
return 1, "Cant read file " + filePath + " due to file does not exists"
else:
base_command = command.split()[0]
if base_command in command_exists_dict:
if not command_exists_dict[base_command]:
return CANCELED_STATUS , "Command not invoked " + command + " due to " + base_command + " does not exists"
else:
is_exists = is_command_exists(base_command)
command_exists_dict[base_command] = is_exists
if not is_exists:
return CANCELED_STATUS , "Command not invoked " + command + " due to " + base_command + " does not exists"
if verbose_flag:
print("\tExecuting command: %s" % command_with_timeout)
p = subprocess.Popen([command_with_timeout], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1024*1024)
stdout = ""
stderr = ""
stdout, stderr = p.communicate()
return p.returncode, standarize_str(stdout)
except Exception as e:
print(e,"err")
error = "\nError while reading output from command - " + command_with_timeout + "\n"
return 1, error
# Ditto but preserving the exit status.
# Returns a pair (sts, output)
#
@log
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return sts, text
###########################################################
# SIGINT-2-Interrupt from keyboard; Handlers (Ctrl+C)
def signal_handler(signal, frame):
if(not keep_info_flag):
if (path_is_generated == 1):
no_log_status_output("rm -rf " + path)
#invoke_command(['rm', '-rf', path])
else:
# Remove tar out file
no_log_status_output("rm -rf " + path + file_name + ".tgz")
#invoke_command(['rm', '-rf', path+file_name+".tgz"])
remove_unwanted_files()
if driver_required_loading:
os.system('mst stop > /dev/null 2>&1')
print("\nRunning sysinfo-snapshot was halted!\nNo out directories/files.\nNo changes in modules loading states.")
os._exit(0)
else:
if sriov_exists:
build_and_finalize_html3()
build_and_finalize_html2()
build_and_finalize_html()
create_tar_file()
remove_unwanted_files()
if driver_required_loading:
os.system('mst stop > /dev/null 2>&1')
print("\nRunning sysinfo-snapshot was halted!\n ")
print("Temporary destination directory is " + path)
print("Out file name is " + path + file_name + ".tgz\n")
os._exit(0)
signal.signal(signal.SIGTSTP, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
##########################################################
# OS General Variables & Confirmation
#rpm --eval %{_vendor}
#Ubuntu prints debian
#Redhat and CentOS prints redhat
os_st, cur_os = no_log_status_output("rpm --eval %{_vendor}")
def decide():
global cur_os
print("Hence running sysinfo-snapshot may throw an exception or produce an unexpected output.")
print("Continue running sysinfo-snapshot (y/n)? ")
decision_ch = sys.stdin.read(1).lower()
if (decision_ch == 'y'):
cur_os = "redhat"
else:
if (decision_ch != 'n'):
print("Invalid char")
print("Halting sysinfo-snapshot")
sys.exit(0)
if (os_st == 0 and cur_os != "%{_vendor}"):
if (cur_os not in supported_os_collection):
print("Operating system with vendor " + cur_os + " is not tested in this Linux sysinfo snapshot.")
decide()
else:
os_st, o_systems = no_log_status_output("cat /etc/*release*")
if (os_st != 0):
os_st, o_systems = no_log_status_output("cat /etc/issue")
if (os_st != 0):
os_st, o_systems = no_log_status_output("lsb_release -a")
if (os_st != 0):
print("Unable to distinguish operating system.")
decide()
o_systems = o_systems.lower()
o_systems = o_systems.replace('(',' ')
o_systems = o_systems.replace(')',' ')
o_systems = re.split(r'( +|")', o_systems)
if ( ("red" in o_systems and "hat" in o_systems) or ("redhat" in o_systems) or ("centos" in o_systems) or ("fedora" in o_systems) or ("scientific" in o_systems) or ("yocto" in o_systems) or ("blueos" in o_systems) ):
cur_os = "redhat"
if ("yocto" in o_systems) or ("blueos" in o_systems):
blueos_flag = True
elif ("suse" in o_systems):
cur_os = "suse"
elif ( ("ubuntu" in o_systems) or ("debian" in o_systems) or ("uos" in o_systems)):
cur_os = "debian"
else:
print("Unable to distinguish operating system.")
decide()
# Runs ibswitches for a given card and port and returns it output and run status
def get_ibswitches_output(card, port):
ibswitches_st, ibswitches = get_status_output("/usr/sbin/ibswitches -C " + card +" -P " + port)
if ibswitches_st != 0:
ibswitches = "Couldn't find command: ibswitches"
else:
# regex expression working in python 2.7 not 2.6
#ibswitches = re.sub('^((?!Switch).)*$', '', ibswitches, re.IGNORECASE,re.MULTILINE)
ibswitches = ibswitches.splitlines()
ibswitches_new = ''
for ibswitch in ibswitches:
if ibswitch.startswith('Switch'):
if ibswitches_new == '':
ibswitches_new = ibswitch
else:
ibswitches_new = ibswitches_new + '\n' + ibswitch
ibswitches = ibswitches_new
return ibswitches_st, ibswitches
#get the cards and ports that are installed and updates the active subnets
def get_installed_cards_ports():
global active_subnets
global installed_cards_ports
global all_sm_on_fabric
sys_ibdir='/sys/class/infiniband'
if not os.path.exists(sys_ibdir):
return sys_ibdir + " does not exist"
ibdevs = os.listdir(sys_ibdir)
for card_name in ibdevs:
ibdev_path = sys_ibdir + "/" + card_name + "/ports"
installed_cards_ports[card_name] = []
for port_num in os.listdir(ibdev_path):
all_sm_on_fabric = []
installed_cards_ports[card_name].append(port_num)
st, ibnetdiscover_output = get_status_output("/usr/sbin/ibnetdiscover -C " + card_name + " -P " + port_num + "")
if st != 0:
continue
ibnetdiscover_output_hashed = hashlib.sha256(ibnetdiscover_output.encode('utf-8')).hexdigest()
if ibnetdiscover_output_hashed not in all_sm_on_fabric:
all_sm_on_fabric.append(ibnetdiscover_output_hashed)
if card_name not in active_subnets:
active_subnets[card_name] = []
obj = {}
obj["port_num"] = port_num
ibswitches_st, ibswitches = get_ibswitches_output(card_name, port_num)
obj["ibswitches"] = {}
obj["ibswitches"]["ibswitches_st"] = ibswitches_st
obj["ibswitches"]["ibswitches_output"] = ibswitches
active_subnets[card_name].append(obj)
if os.path.exists("/sys/class/net"):
sys_class_net_exists = True
# ---------------------------------------
# CLASSES
# ---------------------------------------
class mlnx_device:
def __init__(self, parent_device, sys_img_guid, board_id, fw_ver, hca_type, hw_rev, node_type):
self.parent_device = parent_device
self.sys_img_guid = sys_img_guid
self.board_id = board_id
self.fw_ver = fw_ver
self.hca_type = hca_type
self.hw_rev = hw_rev
self.node_type = node_type
self.node_guids = {}
def get_parent_device(self):
return self.parent_device
def set_parent_device(self, parent_device):
self.parent_device = parent_device
def get_sys_img_guid(self):
return self.sys_img_guid
def set_sys_img_guid(self, sys_img_guid):
self.sys_img_guid = sys_img_guid
def get_board_id(self):
return self.board_id
def set_board_id(self, board_id):
self.board_id = board_id
def get_fw_ver(self):
return self.fw_ver
def set_fw_ver(self, fw_ver):
self.fw_ver = fw_ver
def get_hca_type(self):
return self.hca_type
def set_hca_type(self, hca_type):
self.hca_type = hca_type
def get_hw_rev(self):
return self.hw_rev
def set_hw_rev(self, hw_rev):
self.hw_rev = hw_rev
def get_node_type(self):
return self.node_type
def set_node_type(self, node_type):
self.node_type = node_type
# Append a node description to the node descriptions list
def add_node_desc(self, node_desc, node_guid):
if not (node_guid in self.node_guids.keys()):
self.node_guids[node_guid] = [] # Initialize list as value
self.node_guids[node_guid].append(node_desc)
else:
self.node_guids[node_guid].append(node_desc)
def get_mlnx_device_info(self):
res = ""
res += "Virtual / physical ports info for: " + self.parent_device + ":\n\n"
res += "System Image GUID: " + "/sys/class/infiniband/" + self.parent_device + "/sys_image_guid = " + self.sys_img_guid + "\n"
res += "Board ID: " + "/sys/class/infiniband/" + self.parent_device + "/board_id = " + self.board_id + "\n"
res += "Firmware Version: " + "/sys/class/infiniband/" + self.parent_device + "/fw_ver = " + self.fw_ver + "\n"
res += "HCA Type: " + "/sys/class/infiniband/" + self.parent_device + "/hca_type = " + self.hca_type + "\n"
res += "HW Rev: " + "/sys/class/infiniband/" + self.parent_device + "/hw_rev = " + self.hw_rev + "\n"
res += "Node Type: " + "/sys/class/infiniband/" + self.parent_device + "/node_type = " + self.node_type + "\n"
for node_guid in self.node_guids:
res += "\nNumber of related nodes with Node GUID = " + node_guid + " is: "+ str(len(self.node_guids[node_guid])) +", with the following Node Descriptions: \n"
for node_desc in self.node_guids[node_guid]:
res += " " + node_desc + "\n"
return res
#return true if command should be invoked. and added to dict in case we are generating new file
def is_command_allowed(config_key,related_flag=""):
global config_dict
if generate_config_flag:
if not config_key in config_dict:
approved = "yes"
if related_flag:
related_flags = related_flag.split("/")
for flag in related_flags:
if not "no" in flag.lower() :
flag = flag.strip()
approved = "no"
config_dict[config_key] = {"approved":approved,"related flag":related_flag}
return False
if config_key in config_dict:
if config_file_flag and config_dict[config_key]["approved"].lower() != 'yes':
return False
else:
return True
else:
if config_file_flag :
print("Warning: following command not collected it's missing in config file :\n" + config_key + ' \n Please make sure that you are using sysinfo-snapshot version (' + version + ') to generate config file (config.csv) \n')
running_warnings.append("following command not collected it's missing in config file :\n" + config_key + "\n")
return True
is_bluefield_involved = False
is_run_from_bluefield_host = False
def update_net_devices():
global pf_devices
global asap_devices
global mtusb_devices
global vf_pf_devices
global all_net_devices
global local_mst_devices
global mst_devices_exist
global is_bluefield_involved
global is_run_from_bluefield_host
global mft_tools_pci_devices
errors = []
if os.path.isdir('/dev/mst'):
current_mst_devices = os.listdir("/dev/mst")
if interfaces_flag:
current_mst_devices = specific_cable_devices
for device in current_mst_devices:
if (not (device.startswith("CA") or device.startswith("SW")) and "cable" in device): # Make sure we get info only for local cables
local_mst_devices.append(device)
if not sys_class_net_exists:
errors.append("No Net Devices - The path /sys/class/net does not exist")
st, network_devices = get_status_output("ls /sys/class/net")
if (st != 0):
errors.append("Failed to run the command ls /sys/class/net")
#e.g: all_net_devices = ['eno2', 'eno3', 'eno4', 'eno5', 'enp0s29u1u1u5', 'enp139s0f1', 'ib0', 'ib1', 'ib2', 'lo']
else: all_net_devices = network_devices.splitlines()
if(interfaces_flag):
specific_all_net_devices = []
for device in specific_net_devices:
if device in all_net_devices:
specific_all_net_devices.append(device)
else :
print(device + " not found in net devices , please make sure you intered correct device\n ")
all_net_devices = specific_all_net_devices
# e.g 81:00.0 Infiniband controller: Mellanox Technologies MT27800 Family [ConnectX-5]
st, lspci_devices = get_status_output("lspci | grep Mellanox")
if (st != 0):
errors.append("Failed to run the command lspci | grep Mellanox")
if "bluefield" in lspci_devices.lower():
is_bluefield_involved = True
st1, result = get_status_output('dmidecode -t 1')
if st1 == 0 and "bluefield" in result.lower():
is_run_from_bluefield_host = True
pci_devices = lspci_devices.splitlines()
mellanox_net_devices = [] # Only Mellanox net_devices
st, all_interfaces = get_status_output("ls -la /sys/class/net")
if (st != 0):
errors.append("Failed to run the command ls -la /sys/class/net")
# e.g /dev/mst/mtusb-1 - USB to I2C adapter as I2C master
if mtusb_flag:
st, mst_status = get_status_output("mst status")
mtusbs = re.findall(r'(.*?)- USB', mst_status)
for mtusb_device in mtusbs:
mtusb_devices.append(mtusb_device.strip()) # Clean the string
if interfaces_flag:
mtusb_dev = []
for dev in mtusb_devices:
if dev in specific_mst_devices:
mtusb_dev.append(dev)
mtusb_devices = mtusb_dev
for lspci_device in pci_devices:
is_valid_mft_tools_dev = is_valid_mft_tools_device(lspci_device)
if is_valid_mft_tools_dev:
mft_tools_pci_devices.append(lspci_device)
device = lspci_device.split()[0]
if "function" in lspci_device.lower():
if not device in vf_pf_devices:
vf_pf_devices.append(device)
# e.g lrwxrwxrwx 1 root root 0 Oct 26 15:51 ens11f0 -> ../../devices/pci0000:80/0000:80:03.0/0000:81:00.0/net/ens11f0
match = re.findall(r'{}/net/([\w.-]+)'.format(device), all_interfaces)
if match:
for interface in match:
mellanox_net_devices.append(interface)
# e.g lrwxrwxrwx 1 root root 0 Oct 26 15:51 ens11f0 -> ../../devices/pci0000:80/0000:80:03.0/0000:81:00.0/net/ens11f0
match = re.findall(r'virtual/net/([\w.-]+)', all_interfaces)
if match:
for interface in match:
mellanox_net_devices.append(interface)
asap_devices = mellanox_net_devices
if "lo" in mellanox_net_devices:
try:
mellanox_net_devices.remove("lo")
asap_devices.remove("lo")
except:
pass
if "bonding_masters" in mellanox_net_devices:
try:
mellanox_net_devices.remove("bonding_masters")
asap_devices.remove("bonding_masters")
except:
pass
if "bond0" in mellanox_net_devices:
try:
mellanox_net_devices.remove("bond0")
except:
pass
pf_devices = mellanox_net_devices
if(interfaces_flag):
specific_mellanox_net_devices = []
specific_asap_devices = []
for device in specific_net_devices:
if device in mellanox_net_devices:
specific_mellanox_net_devices.append(device)
if device in asap_devices:
specific_asap_devices.append(device)
pf_devices = specific_mellanox_net_devices
asap_devices = specific_asap_devices
if errors:
f = open(path + file_name + "/err_messages/dummy_functions", 'a')
f.write("Could not get network devices from the following commands: ")
f.write("\n")
for error in errors:
f.write(error)
f.write("\n\n")
f.close()
###########################################################
# JSON Handlers And Global Variables
# define and initialize dictionaries hierarchy
server_commands_dict = {}
fabric_commands_dict = {}
files_dict = {}
external_files_dict = {}
# Dictionaries for command groups
mft_commands_dict = {}
network_commands_dict = {}
system_commands_dict = {}
gpu_commands_dict = {}
rdma_commands_dict = {}
service_commands_dict = {}
storage_commands_dict = {}
performance_commands_dict = {}
l3_dict = {}
l3_dict[str(section_count) + ". Server Commands: "] = server_commands_dict
section_count += 1
if (is_ib == 0 and no_ib_flag == False):
l3_dict[str(section_count) + ". Fabric Diagnostics Information: "] = fabric_commands_dict
section_count += 1
l3_dict[str(section_count) + ". Internal Files: "] = files_dict
section_count += 1
l3_dict[str(section_count) + ". External Files: "] = external_files_dict
section_count += 1
l2_dict = {}
l2_dict["Version: " + version] = l3_dict
l1_dict = {}
if (is_ib == 0):
l1_dict['Mellanox Technologies - Linux Infiniband Driver System Information Snapshot Utility'] = l2_dict
else:
l1_dict['Mellanox Technologies - Linux Ethernet Driver System Information Snapshot Utility'] = l2_dict
###########################################################
def represents_int(s):
try:
int(s)
return True
except ValueError:
return False
#**********************************************************
# show_pretty_gids Handler
def show_pretty_gids_handler():
n_gids_found = 0
res = "DEV\tPORT\tINDEX\tGID\t\t\t\t\t\tIPv4\n"
res += "---\t----\t-----\t---\t\t\t\t\t\t------------\n"
if os.path.isdir('/sys/class/infiniband'):
for root, dirs, files in os.walk('/sys/class/infiniband'):
for device in dirs:
if os.path.isdir('/sys/class/infiniband/' + device + '/ports'):
for subroot, subdirs, subfiles in os.walk('/sys/class/infiniband/' + device + '/ports'):
for port in subdirs:
if os.path.isdir('/sys/class/infiniband/' + device + '/ports/' + port + '/gids'):
for subsubroot, subsubdirs, subsubfiles in os.walk('/sys/class/infiniband/' + device + '/ports/' + port + '/gids'):
for gid_index in subsubfiles:
gid = r'N\A'
try:
with open('/sys/class/infiniband/' + device + '/ports/' + port + '/gids/' + gid_index, 'r') as gid_index_file:
gid = gid_index_file.readline().strip()
except:
continue
if gid == '' or gid == r'N\A' or gid == '0000:0000:0000:0000:0000:0000:0000:0000' or gid == 'fe80:0000:0000:0000:0000:0000:0000:0000':
continue
n_gids_found += 1
gid_type = r'N\A'
try:
with open('/sys/class/infiniband/' + device + '/ports/' + port + '/gid_attrs/types/' + gid_index, 'r') as gid_type_file:
gid_type = gid_type_file.readline().strip()
except:
pass
if gid_type == '':
gid_type = r'N\A'
gid_ndevs = r'N\A'
try:
with open('/sys/class/infiniband/' + device + '/ports/' + port + '/gid_attrs/ndevs/' + gid_index, 'r') as gid_ndevs_file:
gid_ndevs = gid_ndevs_file.readline().strip()
except:
pass
if gid_ndevs == '':
gid_ndevs = r'N\A'
if len(gid_type) < 8:
gid_type += '\t'
if gid.split(':')[0] == '0000':
try:
ipv4 = str(int(gid[30:32], 16)) + '.' + str(int(gid[32:34], 16)) + '.' + str(int(gid[35:37], 16)) + '.' + str(int(gid[37:39], 16)) + ' \t'
except:
ipv4 = '\t\t'
res += device + '\t' + port + '\t' + gid_index + '\t' + gid + '\t\t' + ipv4 + gid_type + '\t\t' + gid_ndevs + '\n'
else:
res += device + '\t' + port + '\t' + gid_index + '\t' + gid + '\t\t\t\t' + gid_type + '\t\t' + gid_ndevs + '\n'
res += '\nn_gids_found=' + str(n_gids_found) + '\n'
return res
#**********************************************************
# ethtool_version Handlers
def ethtool_version_handler():
global ethtool_command
ethtool_command = "/usr/sbin/ethtool"
st, ethtool_version = get_status_output(ethtool_command + " --version")
if st != 0:
ethtool_command_2 = "/sbin/ethtool"
st, ethtool_version = get_status_output(ethtool_command_2 + " --version")
if st != 0:
return st, "Failed to run the command " + ethtool_command + " or " + ethtool_command_2
ethtool_command = ethtool_command_2
return 0, ethtool_version
#**********************************************************
# ethtool_all_interfaces Handlers
def ethtool_all_interfaces_handler():
if not all_net_devices:
return "No interfaces were found"
mellanox_net_devices = all_net_devices
if (len(mellanox_net_devices) > 0):
get_status_output("mkdir " + path + file_name + "/ethtool_S")
#invoke_command(['mkdir', path + file_name + "/ethtool_S"])
st, ethtool_version = ethtool_version_handler()
if st != 0:
return "Failed to run the command " + ethtool_command
res = ""
#Output - ethtool version 4.8
version = ethtool_version.split()[2]
if (LooseVersion(version) < LooseVersion('4.7')):
ethtool_version = "Warning - " + ethtool_version + ", it is older than 4.7 ! \nIt will not show the 25g generation speeds correctly, cause ethtool 4.6 and below do not support it."
res += ethtool_version