[AS5835-54X] Modify util to support python3 (#8285)

Modify accton_as5835_54x_util.py to support python3 and remove not needed code.

Signed-off-by: Jostar Yang <jostar_yang@accton.com.tw>
This commit is contained in:
jostar-yang 2021-08-13 14:36:19 +08:00 committed by GitHub
parent e42f93b446
commit 4f9de40d07
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python3
# #
# Copyright (C) 2019 Accton Networks, Inc. # Copyright (C) 2019 Accton Networks, Inc.
# #
@ -17,24 +17,18 @@
""" """
Usage: %(scriptName)s [options] command object Usage: %(scriptName)s [options] command object
options: options:
-h | --help : this help message -h | --help : this help message
-d | --debug : run with debug mode -d | --debug : run with debug mode
-f | --force : ignore error during installation or clean -f | --force : ignore error during installation or clean
command: command:
install : install drivers and generate related sysfs nodes install : install drivers and generate related sysfs nodes
clean : uninstall drivers and remove related sysfs nodes clean : uninstall drivers and remove related sysfs nodes
show : show all systen status
sff : dump SFP eeprom
set : change board setting with fan|led|sfp
""" """
import subprocess
import commands
import getopt import getopt
import sys import sys
import logging import logging
import re
import time import time
import os import os
@ -47,15 +41,15 @@ verbose = False
DEBUG = False DEBUG = False
args = [] args = []
ALL_DEVICE = {} ALL_DEVICE = {}
DEVICE_NO = {'led':5, 'fan':5,'thermal':4, 'psu':2, 'sfp':54}
FORCE = 0 FORCE = 0
#logging.basicConfig(filename= PROJECT_NAME+'.log', filemode='w',level=logging.DEBUG) #logging.basicConfig(filename= PROJECT_NAME+'.log', filemode='w',level=logging.DEBUG)
#logging.basicConfig(level=logging.INFO) #logging.basicConfig(level=logging.INFO)
if DEBUG == True: if DEBUG == True:
print sys.argv[0] print(sys.argv[0])
print 'ARGV :', sys.argv[1:] print("ARGV :", sys.argv[1:])
def main(): def main():
@ -71,9 +65,9 @@ def main():
'force', 'force',
]) ])
if DEBUG == True: if DEBUG == True:
print options print(options)
print args print(args)
print len(sys.argv) print(len(sys.argv))
for opt, arg in options: for opt, arg in options:
if opt in ('-h', '--help'): if opt in ('-h', '--help'):
@ -94,22 +88,7 @@ def main():
do_sonic_platform_install() do_sonic_platform_install()
elif arg == 'api_clean': elif arg == 'api_clean':
do_sonic_platform_clean() do_sonic_platform_clean()
elif arg == 'show':
device_traversal()
elif arg == 'sff':
if len(args)!=2:
show_eeprom_help()
elif int(args[1]) ==0 or int(args[1]) > DEVICE_NO['sfp']:
show_eeprom_help()
else:
show_eeprom(args[1])
return
elif arg == 'set':
if len(args)<3:
show_set_help()
else:
set_device(args[1:])
return
else: else:
show_help() show_help()
@ -117,30 +96,18 @@ def main():
return 0 return 0
def show_help(): def show_help():
print __doc__ % {'scriptName' : sys.argv[0].split("/")[-1]} print(__doc__ % {'scriptName' : sys.argv[0].split("/")[-1]})
sys.exit(0) sys.exit(0)
def show_set_help():
cmd = sys.argv[0].split("/")[-1]+ " " + args[0]
print cmd +" [led|sfp|fan]"
print " use \""+ cmd + " led 0-4 \" to set led color"
print " use \""+ cmd + " fan 0-100\" to set fan duty percetage"
print " use \""+ cmd + " sfp 1-48 {0|1}\" to set sfp# tx_disable"
sys.exit(0)
def show_eeprom_help():
cmd = sys.argv[0].split("/")[-1]+ " " + args[0]
print " use \""+ cmd + " 1-54 \" to dump sfp# eeprom"
sys.exit(0)
def my_log(txt): def my_log(txt):
if DEBUG == True: if DEBUG == True:
print "[Debug]"+txt print("[Debug]"+txt)
return return
def log_os_system(cmd, show): def log_os_system(cmd, show):
logging.info('Run :'+cmd) logging.info('Run :'+cmd)
status, output = commands.getstatusoutput(cmd) status, output = subprocess.getstatusoutput(cmd)
my_log (cmd +"with result:" + str(status)) my_log (cmd +"with result:" + str(status))
my_log (" output:"+output) my_log (" output:"+output)
if status: if status:
@ -177,6 +144,8 @@ def driver_install():
if ret[0]: if ret[0]:
if FORCE == 0: if FORCE == 0:
return ret[0] return ret[0]
print("Done driver_install")
return 0 return 0
def driver_uninstall(): def driver_uninstall():
@ -194,12 +163,8 @@ def driver_uninstall():
return ret[0] return ret[0]
return 0 return 0
led_prefix ='/sys/class/leds/'+PROJECT_NAME+'_led::'
hwmon_types = {'led': ['diag','fan','loc','psu1','psu2']}
hwmon_nodes = {'led': ['brightness'] }
hwmon_prefix ={'led': led_prefix}
i2c_prefix = '/sys/bus/i2c/devices/' i2c_prefix = '/sys/bus/i2c/devices/'
'''
i2c_bus = {'fan': ['3-0063'] , i2c_bus = {'fan': ['3-0063'] ,
'thermal': ['18-004b','19-004c', '20-0049', '21-004a'] , 'thermal': ['18-004b','19-004c', '20-0049', '21-004a'] ,
'psu': ['11-0050','12-0053'], 'psu': ['11-0050','12-0053'],
@ -208,7 +173,7 @@ i2c_nodes = {'fan': ['present', 'front_speed_rpm', 'rear_speed_rpm'] ,
'thermal': ['hwmon/hwmon*/temp1_input'] , 'thermal': ['hwmon/hwmon*/temp1_input'] ,
'psu': ['psu_present ', 'psu_power_good'] , 'psu': ['psu_present ', 'psu_power_good'] ,
'sfp': ['module_present_', 'module_tx_disable_']} 'sfp': ['module_present_', 'module_tx_disable_']}
'''
sfp_map = [42,43,44,45,46,47,48,49,50,51, sfp_map = [42,43,44,45,46,47,48,49,50,51,
52,53,54,55,56,57,58,59,60,61, 52,53,54,55,56,57,58,59,60,61,
62,63,64,65,66,67,68,69,70,71, 62,63,64,65,66,67,68,69,70,71,
@ -303,7 +268,7 @@ def device_install():
status, output = log_os_system(mknod2[i], 1) status, output = log_os_system(mknod2[i], 1)
time.sleep(0.01) time.sleep(0.01)
if status: if status:
print output print(output)
if FORCE == 0: if FORCE == 0:
return status return status
else: else:
@ -314,7 +279,7 @@ def device_install():
status, output = log_os_system(mknod[i], 1) status, output = log_os_system(mknod[i], 1)
if status: if status:
print output print(output)
if FORCE == 0: if FORCE == 0:
return status return status
@ -327,9 +292,11 @@ def device_install():
else: else:
status, output =log_os_system("echo optoe1 0x50 > /sys/bus/i2c/devices/i2c-"+str(sfp_map[i])+"/new_device", 1) status, output =log_os_system("echo optoe1 0x50 > /sys/bus/i2c/devices/i2c-"+str(sfp_map[i])+"/new_device", 1)
if status: if status:
print output print(output)
if FORCE == 0: if FORCE == 0:
return status return status
print("Done device_install")
return return
def device_uninstall(): def device_uninstall():
@ -339,7 +306,7 @@ def device_uninstall():
target = "/sys/bus/i2c/devices/i2c-"+str(sfp_map[i])+"/delete_device" target = "/sys/bus/i2c/devices/i2c-"+str(sfp_map[i])+"/delete_device"
status, output =log_os_system("echo 0x50 > "+ target, 1) status, output =log_os_system("echo 0x50 > "+ target, 1)
if status: if status:
print output print(output)
if FORCE == 0: if FORCE == 0:
return status return status
@ -356,7 +323,7 @@ def device_uninstall():
temp[-1] = temp[-1].replace('new_device', 'delete_device') temp[-1] = temp[-1].replace('new_device', 'delete_device')
status, output = log_os_system(" ".join(temp), 1) status, output = log_os_system(" ".join(temp), 1)
if status: if status:
print output print(output)
if FORCE == 0: if FORCE == 0:
return status return status
@ -381,10 +348,10 @@ def do_sonic_platform_install():
if os.path.exists(SONIC_PLATFORM_BSP_WHL_PKG_PY3): if os.path.exists(SONIC_PLATFORM_BSP_WHL_PKG_PY3):
status, output = log_os_system("pip3 install "+ SONIC_PLATFORM_BSP_WHL_PKG_PY3, 1) status, output = log_os_system("pip3 install "+ SONIC_PLATFORM_BSP_WHL_PKG_PY3, 1)
if status: if status:
print "Error: Failed to install {}".format(PLATFORM_API2_WHL_FILE_PY3) print("Error: Failed to install {}".format(PLATFORM_API2_WHL_FILE_PY3) )
return status return status
else: else:
print "Successfully installed {} package".format(PLATFORM_API2_WHL_FILE_PY3) print("Successfully installed {} package".format(PLATFORM_API2_WHL_FILE_PY3) )
else: else:
print('{} is not found'.format(PLATFORM_API2_WHL_FILE_PY3)) print('{} is not found'.format(PLATFORM_API2_WHL_FILE_PY3))
else: else:
@ -408,231 +375,52 @@ def do_sonic_platform_clean():
return return
def do_install(): def do_install():
print "Checking system...." print("Checking system....")
if driver_check() == False: if driver_check() == False:
print "No driver, installing...." print("No driver, installing....")
status = driver_install() status = driver_install()
if status: if status:
if FORCE == 0: if FORCE == 0:
return status return status
else: else:
print PROJECT_NAME.upper()+" drivers detected...." print(PROJECT_NAME.upper()+" drivers detected....")
if not device_exist(): if not device_exist():
print "No device, installing...." print("No device, installing....")
status = device_install() status = device_install()
if status: if status:
if FORCE == 0: if FORCE == 0:
return status return status
else: else:
print PROJECT_NAME.upper()+" devices detected...." print(PROJECT_NAME.upper()+" devices detected....")
do_sonic_platform_install() do_sonic_platform_install()
return return
def do_uninstall(): def do_uninstall():
print "Checking system...." print("Checking system....")
if not device_exist(): if not device_exist():
print PROJECT_NAME.upper() +" has no device installed...." print(PROJECT_NAME.upper() +" has no device installed....")
else: else:
print "Removing device...." print("Removing device....")
status = device_uninstall() status = device_uninstall()
if status: if status:
if FORCE == 0: if FORCE == 0:
return status return status
if driver_check()== False : if driver_check()== False :
print PROJECT_NAME.upper() +" has no driver installed...." print(PROJECT_NAME.upper() +" has no driver installed....")
else: else:
print "Removing installed driver...." print("Removing installed driver....")
status = driver_uninstall() status = driver_uninstall()
if status: if status:
if FORCE == 0: if FORCE == 0:
return status return status
do_sonic_platform_clean() do_sonic_platform_clean()
return return
def devices_info():
global DEVICE_NO
global ALL_DEVICE
global i2c_bus, hwmon_types
for key in DEVICE_NO:
ALL_DEVICE[key]= {}
for i in range(0,DEVICE_NO[key]):
ALL_DEVICE[key][key+str(i+1)] = []
for key in i2c_bus:
buses = i2c_bus[key]
nodes = i2c_nodes[key]
for i in range(0,len(buses)):
for j in range(0,len(nodes)):
if 'fan' == key:
for k in range(0,DEVICE_NO[key]):
node = key+str(k+1)
path = i2c_prefix+ buses[i]+"/fan"+str(k+1)+"_"+ nodes[j]
my_log(node+": "+ path)
ALL_DEVICE[key][node].append(path)
elif 'sfp' == key:
for k in range(0,DEVICE_NO[key]):
for lk in cpld_of_module:
if k in cpld_of_module[lk]:
node = key+str(k+1)
path = i2c_prefix + lk + "/"+ nodes[j] + str(k+1)
my_log(node+": "+ path)
ALL_DEVICE[key][node].append(path)
else:
node = key+str(i+1)
path = i2c_prefix+ buses[i]+"/"+ nodes[j]
my_log(node+": "+ path)
ALL_DEVICE[key][node].append(path)
for key in hwmon_types:
itypes = hwmon_types[key]
nodes = hwmon_nodes[key]
for i in range(0,len(itypes)):
for j in range(0,len(nodes)):
node = key+"_"+itypes[i]
path = hwmon_prefix[key]+ itypes[i]+"/"+ nodes[j]
my_log(node+": "+ path)
ALL_DEVICE[key][ key+str(i+1)].append(path)
#show dict all in the order
if DEBUG == True:
for i in sorted(ALL_DEVICE.keys()):
print(i+": ")
for j in sorted(ALL_DEVICE[i].keys()):
print(" "+j)
for k in (ALL_DEVICE[i][j]):
print(" "+" "+k)
return
def show_eeprom(index):
if system_ready()==False:
print("System's not ready.")
print("Please install first!")
return
if len(ALL_DEVICE)==0:
devices_info()
node = ALL_DEVICE['sfp'] ['sfp'+str(index)][0]
node = node.replace(node.split("/")[-1], 'sfp_eeprom')
# check if got hexdump command in current environment
ret, log = log_os_system("which hexdump", 0)
ret, log2 = log_os_system("which busybox hexdump", 0)
if log :
hex_cmd = 'hexdump'
elif log2 :
hex_cmd = ' busybox hexdump'
else:
log = 'Failed : no hexdump cmd!!'
logging.info(log)
print log
return 1
print node + ":"
ret, log = log_os_system("cat "+node+"| "+hex_cmd+" -C", 1)
if ret==0:
print log
else:
print "**********device no found**********"
return
def set_device(args):
global DEVICE_NO
global ALL_DEVICE
if system_ready()==False:
print("System's not ready.")
print("Please install first!")
return
if len(ALL_DEVICE)==0:
devices_info()
if args[0]=='led':
if int(args[1])>4:
show_set_help()
return
#print ALL_DEVICE['led']
for i in range(0,len(ALL_DEVICE['led'])):
for k in (ALL_DEVICE['led']['led'+str(i+1)]):
ret = log_os_system("echo "+args[1]+" >"+k, 1)
if ret[0]:
return ret[0]
elif args[0]=='fan':
if int(args[1])>100:
show_set_help()
return
#print ALL_DEVICE['fan']
#fan1~5 is all fine, all fan share same setting
node = ALL_DEVICE['fan'] ['fan1'][0]
node = node.replace(node.split("/")[-1], 'fan_duty_cycle_percentage')
ret = log_os_system("cat "+ node, 1)
if ret[0] == 0:
print ("Previous fan duty: " + log.strip() +"%")
ret = log_os_system("echo "+args[1]+" >"+node, 1)
if ret[0] == 0:
print ("Current fan duty: " + args[1] +"%")
return ret[0]
elif args[0]=='sfp':
if int(args[1])> qsfp_start or int(args[1])==0:
show_set_help()
return
if len(args)<2:
show_set_help()
return
if int(args[2])>1:
show_set_help()
return
#print ALL_DEVICE[args[0]]
for i in range(0,len(ALL_DEVICE[args[0]])):
for j in ALL_DEVICE[args[0]][args[0]+str(args[1])]:
if j.find('tx_disable')!= -1:
ret = log_os_system("echo "+args[2]+" >"+ j, 1)
if ret[0]:
return ret[0]
return
#get digits inside a string.
#Ex: 31 for "sfp31"
def get_value(input):
digit = re.findall('\d+', input)
return int(digit[0])
def device_traversal():
if system_ready()==False:
print("System's not ready.")
print("Please install first!")
return
if len(ALL_DEVICE)==0:
devices_info()
for i in sorted(ALL_DEVICE.keys()):
print("============================================")
print(i.upper()+": ")
print("============================================")
for j in sorted(ALL_DEVICE[i].keys(), key=get_value):
print " "+j+":",
for k in (ALL_DEVICE[i][j]):
ret, log = log_os_system("cat "+k, 0)
func = k.split("/")[-1].strip()
func = re.sub(j+'_','',func,1)
func = re.sub(i.lower()+'_','',func,1)
if ret==0:
print func+"="+log+" ",
else:
print func+"="+"X"+" ",
print
print("----------------------------------------------------------------")
print
return
def device_exist(): def device_exist():
ret1 = log_os_system("ls "+i2c_prefix+"*0077", 0) ret1 = log_os_system("ls "+i2c_prefix+"*0077", 0)