Skip to content

Commit dada9ae

Browse files
committed
Remove os.system and subprocess shell=True
Signed-off-by: maipbui <[email protected]>
1 parent 0a5d46a commit dada9ae

File tree

12 files changed

+116
-215
lines changed

12 files changed

+116
-215
lines changed

device/celestica/x86_64-cel_e1031-r0/sonic_platform/common.py

+13-104
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import imp
44
import yaml
55
import subprocess
6-
from shlex import split
76
from sonic_py_common import device_info
87

98

@@ -25,6 +24,7 @@ class Common:
2524

2625
SET_METHOD_IPMI = 'ipmitool'
2726
NULL_VAL = 'N/A'
27+
HOST_CHK_CMD = "docker"
2828
REF_KEY = '$ref:'
2929

3030
def __init__(self, conf=None):
@@ -46,8 +46,7 @@ def run_command(self, command):
4646
status = False
4747
output = ""
4848
try:
49-
p = subprocess.Popen(
50-
split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
49+
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
5150
raw_data, err = p.communicate()
5251
if p.returncode == 0:
5352
status, output = True, raw_data.strip()
@@ -82,14 +81,7 @@ def _clean_output(self, index, output, config):
8281
output = ast.literal_eval(output_translator[index].format(output))
8382

8483
return output
85-
86-
def _ipmi_get(self, index, config):
87-
argument = config.get('argument')
88-
cmd = config['command'].format(
89-
config['argument'][index]) if argument else config['command']
90-
status, output = self.run_command(cmd)
91-
return output if status else None
92-
84+
9385
def _sysfs_read(self, index, config):
9486
sysfs_path = config.get('sysfs_path')
9587
argument = config.get('argument', '')
@@ -132,10 +124,6 @@ def _sysfs_write(self, index, config, input):
132124
return False, output
133125
return True, output
134126

135-
def _ipmi_set(self, index, config, input):
136-
arg = config['argument'][index].format(input)
137-
return self.run_command(config['command'].format(arg))
138-
139127
def _hex_ver_decode(self, hver, num_of_bits, num_of_points):
140128
ver_list = []
141129
c_bit = 0
@@ -159,14 +147,16 @@ def _get_class(self, config):
159147
return class_
160148

161149
def get_reg(self, path, reg_addr):
162-
cmd = "echo {1} > {0}; cat {0}".format(path, reg_addr)
163-
status, output = self.run_command(cmd)
164-
return output if status else None
150+
with open(path, 'w') as file:
151+
file.write(reg_addr)
152+
with open(path, 'r') as file:
153+
output = file.readline().strip()
154+
return output
165155

166156
def set_reg(self, path, reg_addr, value):
167-
cmd = "echo {0} {1} > {2}".format(reg_addr, value, path)
168-
status, output = self.run_command(cmd)
169-
return output if status else None
157+
with open(path, 'w') as file:
158+
file.write("{0} {1}".format(reg_addr, value))
159+
return None
170160

171161
def read_txt_file(self, path):
172162
try:
@@ -195,7 +185,7 @@ def write_txt_file(self, file_path, value):
195185
return True
196186

197187
def is_host(self):
198-
return subprocess.run('docker', stdout=None, stderr=None).returncode == 0
188+
return subprocess.run(self.HOST_CHK_CMD, stdout=None, stderr=None).returncode == 0
199189

200190
def load_json_file(self, path):
201191
"""
@@ -221,88 +211,7 @@ def get_config_path(self, config_name):
221211
"""
222212
return os.path.join(self.DEVICE_PATH, self.platform, self.CONFIG_DIR, config_name) if self.is_host() else os.path.join(self.PMON_PLATFORM_PATH, self.CONFIG_DIR, config_name)
223213

224-
def get_output(self, index, config, default):
225-
"""
226-
Retrieves the output for each function base on config
227-
228-
Args:
229-
index: An integer containing the index of device.
230-
config: A dict object containing the configuration of specified function.
231-
default: A string containing the default output of specified function.
232-
233-
Returns:
234-
A string containing the output of specified function in config
235-
"""
236-
output_source = config.get('output_source')
237-
238-
if output_source == self.OUTPUT_SOURCE_IPMI:
239-
output = self._ipmi_get(index, config)
240-
241-
elif output_source == self.OUTPUT_SOURCE_GIVEN_VALUE:
242-
output = config["value"]
243-
244-
elif output_source == self.OUTPUT_SOURCE_GIVEN_CLASS:
245-
output = self._get_class(config)
246-
247-
elif output_source == self.OUTPUT_SOURCE_GIVEN_LIST:
248-
output = config["value_list"][index]
249-
250-
elif output_source == self.OUTPUT_SOURCE_SYSFS:
251-
output = self._sysfs_read(index, config)
252-
253-
elif output_source == self.OUTPUT_SOURCE_FUNC:
254-
func_conf = self._main_conf[config['function'][index]]
255-
output = self.get_output(index, func_conf, default)
256-
257-
elif output_source == self.OUTPUT_SOURCE_GIVEN_TXT_FILE:
258-
path = config.get('path')
259-
output = self.read_txt_file(path)
260-
261-
elif output_source == self.OUTPUT_SOURCE_GIVEN_VER_HEX_FILE:
262-
path = config.get('path')
263-
hex_ver = self.read_txt_file(path)
264-
output = self._hex_ver_decode(
265-
hex_ver, config['num_of_bits'], config['num_of_points'])
266-
267-
elif output_source == self.OUTPUT_SOURCE_GIVEN_VER_HEX_ADDR:
268-
path = config.get('path')
269-
addr = config.get('reg_addr')
270-
hex_ver = self.get_reg(path, addr)
271-
output = self._hex_ver_decode(
272-
hex_ver, config['num_of_bits'], config['num_of_points'])
273-
274-
else:
275-
output = default
276-
277-
return self._clean_output(index, output, config) or default
278-
279-
def set_output(self, index, input, config):
280-
"""
281-
Sets the output of specified function on config
282-
283-
Args:
284-
config: A dict object containing the configuration of specified function.
285-
index: An integer containing the index of device.
286-
input: A string containing the input of specified function.
287-
288-
Returns:
289-
bool: True if set function is successfully, False if not
290-
"""
291-
cleaned_input = self._clean_input(input, config)
292-
if not cleaned_input:
293-
return False
294-
295-
set_method = config.get('set_method')
296-
if set_method == self.SET_METHOD_IPMI:
297-
output = self._ipmi_set(index, config, cleaned_input)[0]
298-
elif set_method == self.OUTPUT_SOURCE_SYSFS:
299-
output = self._sysfs_write(index, config, cleaned_input)[0]
300-
else:
301-
output = False
302-
303-
return output
304-
305-
def get_event(self, timeout, config, sfp_list):
214+
def get_event(self, timeout, config, sfp_list):
306215
"""
307216
Returns a nested dictionary containing all devices which have
308217
experienced a change at chassis level

device/celestica/x86_64-cel_e1031-r0/sonic_platform/component.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import os.path
1212
import shutil
1313
import subprocess
14-
from shlex import split
1514
from sonic_platform_base.component_base import ComponentBase
1615
except ImportError as e:
1716
raise ImportError(str(e) + "- required module not found")
@@ -39,8 +38,7 @@ def __init__(self, component_index):
3938
def __run_command(self, command):
4039
# Run bash command and print output to stdout
4140
try:
42-
process = subprocess.Popen(
43-
split(command), universal_newlines=True, stdout=subprocess.PIPE)
41+
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE)
4442
while True:
4543
output = process.stdout.readline()
4644
if output == '' and process.poll() is not None:
@@ -63,12 +61,10 @@ def __get_bios_version(self):
6361

6462
def get_register_value(self, register):
6563
# Retrieves the cpld register value
66-
cmd = "echo {1} > {0}; cat {0}".format(GETREG_PATH, register)
67-
p = subprocess.Popen(
68-
split(cmd), universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
69-
raw_data, err = p.communicate()
70-
if err is not '':
71-
return None
64+
with open(GETREG_PATH, 'w') as file:
65+
file.write(register)
66+
with open(GETREG_PATH, 'r') as file:
67+
raw_data = file.readline()
7268
return raw_data.strip()
7369

7470
def __get_cpld_version(self):
@@ -159,7 +155,7 @@ def install_firmware(self, image_path):
159155
ext = ".vme" if ext == "" else ext
160156
new_image_path = os.path.join("/tmp", (root.lower() + ext))
161157
shutil.copy(image_path, new_image_path)
162-
install_command = "ispvm %s" % new_image_path
158+
install_command = ["ispvm", str(new_image_path)]
163159
# elif self.name == "BIOS":
164160
# install_command = "afulnx_64 %s /p /b /n /x /r" % image_path
165161
return self.__run_command(install_command)

device/celestica/x86_64-cel_e1031-r0/sonic_platform/thermal_actions.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,5 @@ def execute(self, thermal_info_dict):
7373
thermal_overload_position = Common().read_txt_file(
7474
thermal_overload_position_path)
7575

76-
cmd = 'bash /usr/share/sonic/platform/thermal_overload_control.sh {}'.format(
77-
thermal_overload_position)
76+
cmd = ['bash', '/usr/share/sonic/platform/thermal_overload_control.sh', thermal_overload_position]
7877
Common().run_command(cmd)

device/celestica/x86_64-cel_seastone-r0/sonic_platform/component.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,10 @@ def __get_bios_version(self):
5252

5353
def get_register_value(self, register):
5454
# Retrieves the cpld register value
55-
cmd = "echo {1} > {0}; cat {0}".format(GETREG_PATH, register)
56-
p = subprocess.Popen(
57-
cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
58-
raw_data, err = p.communicate()
59-
if err is not '':
60-
return None
55+
with open(GETREG_PATH, 'w') as file:
56+
file.write(register)
57+
with open(GETREG_PATH, 'r') as file:
58+
raw_data = file.readline()
6159
return raw_data.strip()
6260

6361
def __get_cpld_version(self):
@@ -146,11 +144,11 @@ def install_firmware(self, image_path):
146144
ext = ".vme" if ext == "" else ext
147145
new_image_path = os.path.join("/tmp", (root.lower() + ext))
148146
shutil.copy(image_path, new_image_path)
149-
install_command = "ispvm %s" % new_image_path
147+
install_command = ["ispvm", str(new_image_path)]
150148
# elif self.name == "BIOS":
151149
# install_command = "afulnx_64 %s /p /b /n /x /r" % image_path
152150

153-
return self.__run_command(install_command)
151+
return self_api_helper.run_command(install_command)
154152

155153

156154
def update_firmware(self, image_path):

device/celestica/x86_64-cel_seastone-r0/sonic_platform/helper.py

+25-29
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from sonic_py_common import device_info
77

8-
HOST_CHK_CMD = "docker > /dev/null 2>&1"
8+
HOST_CHK_CMD = "docker"
99
EMPTY_STRING = ""
1010

1111

@@ -15,7 +15,7 @@ def __init__(self):
1515
(self.platform, self.hwsku) = device_info.get_platform_and_hwsku()
1616

1717
def is_host(self):
18-
return os.system(HOST_CHK_CMD) == 0
18+
return subprocess.run(HOST_CHK_CMD, stdout=None, stderr=None).returncode == 0
1919

2020
def pci_get_value(self, resource, offset):
2121
status = True
@@ -35,21 +35,14 @@ def run_command(self, cmd):
3535
result = ""
3636
try:
3737
p = subprocess.Popen(
38-
cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
38+
cmd, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
3939
raw_data, err = p.communicate()
4040
if err == '':
4141
result = raw_data.strip()
4242
except:
4343
status = False
4444
return status, result
4545

46-
def run_interactive_command(self, cmd):
47-
try:
48-
os.system(cmd)
49-
except:
50-
return False
51-
return True
52-
5346
def read_txt_file(self, file_path):
5447
try:
5548
with open(file_path, 'r') as fd:
@@ -77,17 +70,19 @@ def write_txt_file(self, file_path, value):
7770
return True
7871

7972
def get_cpld_reg_value(self, getreg_path, register):
80-
cmd = "echo {1} > {0}; cat {0}".format(getreg_path, register)
81-
status, result = self.run_command(cmd)
82-
return result if status else None
73+
with open(getreg_path, 'w') as file:
74+
file.write(register)
75+
with open(getreg_path, 'r') as file:
76+
result = file.readline()
77+
return result
8378

8479
def ipmi_raw(self, netfn, cmd):
8580
status = True
8681
result = ""
8782
try:
88-
cmd = "ipmitool raw {} {}".format(str(netfn), str(cmd))
83+
cmd = ["ipmitool", "raw", str(netfn), str(cmd)]
8984
p = subprocess.Popen(
90-
cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
85+
cmd, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
9186
raw_data, err = p.communicate()
9287
if err == '':
9388
result = raw_data.strip()
@@ -100,29 +95,30 @@ def ipmi_raw(self, netfn, cmd):
10095
def ipmi_fru_id(self, id, key=None):
10196
status = True
10297
result = ""
98+
cmd1_args = ["ipmitool", "fru", "print", str(id)]
10399
try:
104-
cmd = "ipmitool fru print {}".format(str(
105-
id)) if not key else "ipmitool fru print {0} | grep '{1}' ".format(str(id), str(key))
106-
107-
p = subprocess.Popen(
108-
cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
109-
raw_data, err = p.communicate()
110-
if err == '':
111-
result = raw_data.strip()
100+
if not key:
101+
p = subprocess.Popen(
102+
cmd1_args, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
103+
raw_data, err = p.communicate()
112104
else:
113-
status = False
114-
except:
105+
cmd2_args = ["grep", str(key)]
106+
with subprocess.Popen(cmd1_args, universal_newlines=True, stdout=subprocess.PIPE) as p1:
107+
with subprocess.Popen(cmd2_args, universal_newlines=True, stdin=p1.stdout, stdout=subprocess.PIPE) as p2:
108+
raw_data = p2.communicate()[0]
109+
if p2.returncode == 1:
110+
raise subprocess.CalledProcessError(returncode=p2.returncode, cmd=cmd, output=raw_data)
111+
except subprocess.CalledProcessError:
115112
status = False
116-
return status, result
113+
return status, raw_data.strip()
117114

118115
def ipmi_set_ss_thres(self, id, threshold_key, value):
119116
status = True
120117
result = ""
121118
try:
122-
cmd = "ipmitool sensor thresh '{}' {} {}".format(
123-
str(id), str(threshold_key), str(value))
119+
cmd = ["ipmitool", "sensor", "thresh", str(id), str(threshold_key), str(value)]
124120
p = subprocess.Popen(
125-
cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
121+
cmd, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
126122
raw_data, err = p.communicate()
127123
if err == '':
128124
result = raw_data.strip()

device/celestica/x86_64-cel_seastone-r0/sonic_platform/thermal_actions.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,5 @@ def execute(self, thermal_info_dict):
7373
thermal_overload_position = APIHelper().read_one_line_file(
7474
thermal_overload_position_path)
7575

76-
cmd = 'bash /usr/share/sonic/platform/thermal_overload_control.sh {}'.format(
77-
thermal_overload_position)
76+
cmd = ['bash', '/usr/share/sonic/platform/thermal_overload_control.sh', str(thermal_overload_position)]
7877
APIHelper().run_command(cmd)

device/celestica/x86_64-cel_seastone-r0/sonic_platform/thermal_manager.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from .thermal_infos import *
66

77
class ThermalManager(ThermalManagerBase):
8-
FSC_ALGORITHM_CMD = 'service fancontrol {}'
8+
FSC_ALGORITHM_CMD = ['service', 'fancontrol', '']
99

1010
@classmethod
1111
def start_thermal_control_algorithm(cls):
@@ -43,4 +43,5 @@ def _enable_fancontrol_service(cls, enable):
4343
bool: True if set success, False if fail.
4444
"""
4545
cmd = 'start' if enable else 'stop'
46-
return APIHelper().run_command(cls.FSC_ALGORITHM_CMD.format(cmd))
46+
cls.FSC_ALGORITHM_CMD[2] = cmd
47+
return APIHelper().run_command(cls.FSC_ALGORITHM_CMD.format)

0 commit comments

Comments
 (0)