blob: 91fe261c03d65554ecee928f2972c2e612372ae6 [file] [log] [blame]
George Keishinge7e91712021-09-03 11:28:44 -05001#!/usr/bin/env python3
Peter D Phan72ce6b82021-06-03 06:18:26 -05002
3r"""
4See class prolog below for details.
5"""
6
George Keishing09679892022-12-08 08:21:52 -06007from errno import EACCES, EPERM
8
George Keishinge635ddc2022-12-08 07:38:02 -06009import os
10import re
11import sys
12import yaml
13import json
14import time
15import logging
16import platform
George Keishing37c58c82022-12-08 07:42:54 -060017from errno import EACCES, EPERM
George Keishinge635ddc2022-12-08 07:38:02 -060018import subprocess
Peter D Phan5e56f522021-12-20 13:19:41 -060019
Peter D Phancb791d72022-02-08 12:23:03 -060020script_dir = os.path.dirname(os.path.abspath(__file__))
21sys.path.append(script_dir)
22# Walk path and append to sys.path
23for root, dirs, files in os.walk(script_dir):
24 for dir in dirs:
25 sys.path.append(os.path.join(root, dir))
26
George Keishing09679892022-12-08 08:21:52 -060027from ssh_utility import SSHRemoteclient # NOQA
28from telnet_utility import TelnetRemoteclient # NOQA
Peter D Phan72ce6b82021-06-03 06:18:26 -050029
George Keishingb97a9042021-07-29 07:41:20 -050030r"""
31User define plugins python functions.
32
33It will imports files from directory plugins
34
35plugins
36├── file1.py
37└── file2.py
38
39Example how to define in YAML:
40 - plugin:
41 - plugin_name: plugin.foo_func.foo_func_yaml
42 - plugin_args:
43 - arg1
44 - arg2
45"""
George Keishinge635ddc2022-12-08 07:38:02 -060046plugin_dir = __file__.split(__file__.split("/")[-1])[0] + '/plugins'
Peter D Phan5e56f522021-12-20 13:19:41 -060047sys.path.append(plugin_dir)
George Keishingb97a9042021-07-29 07:41:20 -050048try:
49 for module in os.listdir(plugin_dir):
George Keishinge635ddc2022-12-08 07:38:02 -060050 if module == '__init__.py' or module[-3:] != '.py':
George Keishingb97a9042021-07-29 07:41:20 -050051 continue
52 plugin_module = "plugins." + module[:-3]
53 # To access the module plugin.<module name>.<function>
54 # Example: plugin.foo_func.foo_func_yaml()
55 try:
56 plugin = __import__(plugin_module, globals(), locals(), [], 0)
57 except Exception as e:
58 print("PLUGIN: Module import failed: %s" % module)
59 pass
60except FileNotFoundError as e:
61 print("PLUGIN: %s" % e)
62 pass
63
64r"""
65This is for plugin functions returning data or responses to the caller
66in YAML plugin setup.
67
68Example:
69
70 - plugin:
71 - plugin_name: version = plugin.ssh_execution.ssh_execute_cmd
72 - plugin_args:
73 - ${hostname}
74 - ${username}
75 - ${password}
76 - "cat /etc/os-release | grep VERSION_ID | awk -F'=' '{print $2}'"
77 - plugin:
78 - plugin_name: plugin.print_vars.print_vars
79 - plugin_args:
80 - version
81
82where first plugin "version" var is used by another plugin in the YAML
83block or plugin
84
85"""
86global global_log_store_path
87global global_plugin_dict
88global global_plugin_list
George Keishing9348b402021-08-13 12:22:35 -050089
George Keishing0581cb02021-08-05 15:08:58 -050090# Hold the plugin return values in dict and plugin return vars in list.
George Keishing9348b402021-08-13 12:22:35 -050091# Dict is to reference and update vars processing in parser where as
92# list is for current vars from the plugin block which needs processing.
George Keishingb97a9042021-07-29 07:41:20 -050093global_plugin_dict = {}
94global_plugin_list = []
George Keishing9348b402021-08-13 12:22:35 -050095
George Keishing0581cb02021-08-05 15:08:58 -050096# Hold the plugin return named declared if function returned values are list,dict.
97# Refer this name list to look up the plugin dict for eval() args function
George Keishing9348b402021-08-13 12:22:35 -050098# Example ['version']
George Keishing0581cb02021-08-05 15:08:58 -050099global_plugin_type_list = []
George Keishing9348b402021-08-13 12:22:35 -0500100
101# Path where logs are to be stored or written.
George Keishinge635ddc2022-12-08 07:38:02 -0600102global_log_store_path = ''
George Keishingb97a9042021-07-29 07:41:20 -0500103
George Keishing1e7b0182021-08-06 14:05:54 -0500104# Plugin error state defaults.
105plugin_error_dict = {
George Keishinge635ddc2022-12-08 07:38:02 -0600106 'exit_on_error': False,
107 'continue_on_error': False,
George Keishing1e7b0182021-08-06 14:05:54 -0500108}
109
Peter D Phan72ce6b82021-06-03 06:18:26 -0500110
Peter D Phan5e56f522021-12-20 13:19:41 -0600111class ffdc_collector:
George Keishinge635ddc2022-12-08 07:38:02 -0600112
Peter D Phan72ce6b82021-06-03 06:18:26 -0500113 r"""
George Keishing1e7b0182021-08-06 14:05:54 -0500114 Execute commands from configuration file to collect log files.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500115 Fetch and store generated files at the specified location.
116
117 """
118
George Keishinge635ddc2022-12-08 07:38:02 -0600119 def __init__(self,
120 hostname,
121 username,
122 password,
123 ffdc_config,
124 location,
125 remote_type,
126 remote_protocol,
127 env_vars,
128 econfig,
129 log_level):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500130 r"""
131 Description of argument(s):
132
George Keishing8e94f8c2021-07-23 15:06:32 -0500133 hostname name/ip of the targeted (remote) system
134 username user on the targeted system with access to FFDC files
135 password password for user on targeted system
136 ffdc_config configuration file listing commands and files for FFDC
137 location where to store collected FFDC
138 remote_type os type of the remote host
139 remote_protocol Protocol to use to collect data
140 env_vars User define CLI env vars '{"key : "value"}'
141 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -0500142
143 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500144
145 self.hostname = hostname
146 self.username = username
147 self.password = password
148 self.ffdc_config = ffdc_config
149 self.location = location + "/" + remote_type.upper()
150 self.ssh_remoteclient = None
151 self.telnet_remoteclient = None
152 self.ffdc_dir_path = ""
153 self.ffdc_prefix = ""
154 self.target_type = remote_type.upper()
155 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -0500156 self.env_vars = env_vars
157 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -0500158 self.start_time = 0
George Keishinge635ddc2022-12-08 07:38:02 -0600159 self.elapsed_time = ''
Peter D Phane86d9a52021-07-15 10:42:25 -0500160 self.logger = None
161
162 # Set prefix values for scp files and directory.
163 # Since the time stamp is at second granularity, these values are set here
164 # to be sure that all files for this run will have same timestamps
165 # and they will be saved in the same directory.
166 # self.location == local system for now
Peter D Phan5e56f522021-12-20 13:19:41 -0600167 self.set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500168
Peter D Phan5e56f522021-12-20 13:19:41 -0600169 # Logger for this run. Need to be after set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500170 self.script_logging(getattr(logging, log_level.upper()))
171
172 # Verify top level directory exists for storage
173 self.validate_local_store(self.location)
174
Peter D Phan72ce6b82021-06-03 06:18:26 -0500175 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -0500176 # Load default or user define YAML configuration file.
George Keishinge635ddc2022-12-08 07:38:02 -0600177 with open(self.ffdc_config, 'r') as file:
George Keishinge9b23d32021-08-13 12:57:58 -0500178 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -0700179 self.ffdc_actions = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -0500180 except yaml.YAMLError as e:
181 self.logger.error(e)
182 sys.exit(-1)
Peter D Phane86d9a52021-07-15 10:42:25 -0500183
184 if self.target_type not in self.ffdc_actions.keys():
185 self.logger.error(
George Keishinge635ddc2022-12-08 07:38:02 -0600186 "\n\tERROR: %s is not listed in %s.\n\n" % (self.target_type, self.ffdc_config))
Peter D Phane86d9a52021-07-15 10:42:25 -0500187 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500188 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500189 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500190
George Keishing4885b2f2021-07-21 15:22:45 -0500191 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500192 self.logger.info("\n\tENV: User define input YAML variables")
193 self.env_dict = {}
Peter D Phan5e56f522021-12-20 13:19:41 -0600194 self.load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500195
Peter D Phan72ce6b82021-06-03 06:18:26 -0500196 def verify_script_env(self):
George Keishinge635ddc2022-12-08 07:38:02 -0600197
Peter D Phan72ce6b82021-06-03 06:18:26 -0500198 # Import to log version
199 import click
200 import paramiko
201
202 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500203
George Keishinge635ddc2022-12-08 07:38:02 -0600204 redfishtool_version = self.run_tool_cmd('redfishtool -V').split(' ')[2].strip('\n')
205 ipmitool_version = self.run_tool_cmd('ipmitool -V').split(' ')[2]
Peter D Phan0c669772021-06-24 13:52:42 -0500206
Peter D Phane86d9a52021-07-15 10:42:25 -0500207 self.logger.info("\n\t---- Script host environment ----")
George Keishinge635ddc2022-12-08 07:38:02 -0600208 self.logger.info("\t{:<10} {:<10}".format('Script hostname', os.uname()[1]))
209 self.logger.info("\t{:<10} {:<10}".format('Script host os', platform.platform()))
210 self.logger.info("\t{:<10} {:>10}".format('Python', platform.python_version()))
211 self.logger.info("\t{:<10} {:>10}".format('PyYAML', yaml.__version__))
212 self.logger.info("\t{:<10} {:>10}".format('click', click.__version__))
213 self.logger.info("\t{:<10} {:>10}".format('paramiko', paramiko.__version__))
214 self.logger.info("\t{:<10} {:>9}".format('redfishtool', redfishtool_version))
215 self.logger.info("\t{:<10} {:>12}".format('ipmitool', ipmitool_version))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500216
George Keishinge635ddc2022-12-08 07:38:02 -0600217 if eval(yaml.__version__.replace('.', ',')) < (5, 3, 0):
218 self.logger.error("\n\tERROR: Python or python packages do not meet minimum version requirement.")
219 self.logger.error("\tERROR: PyYAML version 5.3.0 or higher is needed.\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500220 run_env_ok = False
221
Peter D Phane86d9a52021-07-15 10:42:25 -0500222 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500223 return run_env_ok
224
George Keishinge635ddc2022-12-08 07:38:02 -0600225 def script_logging(self,
226 log_level_attr):
Peter D Phane86d9a52021-07-15 10:42:25 -0500227 r"""
228 Create logger
229
230 """
231 self.logger = logging.getLogger()
232 self.logger.setLevel(log_level_attr)
George Keishinge635ddc2022-12-08 07:38:02 -0600233 log_file_handler = logging.FileHandler(self.ffdc_dir_path + "collector.log")
Peter D Phane86d9a52021-07-15 10:42:25 -0500234
235 stdout_handler = logging.StreamHandler(sys.stdout)
236 self.logger.addHandler(log_file_handler)
237 self.logger.addHandler(stdout_handler)
238
239 # Turn off paramiko INFO logging
240 logging.getLogger("paramiko").setLevel(logging.WARNING)
241
Peter D Phan72ce6b82021-06-03 06:18:26 -0500242 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500243 r"""
244 Check if target system is ping-able.
245
246 """
George Keishing0662e942021-07-13 05:12:20 -0500247 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500248 if response == 0:
George Keishinge635ddc2022-12-08 07:38:02 -0600249 self.logger.info("\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500250 return True
251 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500252 self.logger.error(
George Keishinge635ddc2022-12-08 07:38:02 -0600253 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500254 sys.exit(-1)
255
Peter D Phan72ce6b82021-06-03 06:18:26 -0500256 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500257 r"""
258 Initiate FFDC Collection depending on requested protocol.
259
260 """
261
George Keishinge635ddc2022-12-08 07:38:02 -0600262 self.logger.info("\n\t---- Start communicating with %s ----" % self.hostname)
Peter D Phan7610bc42021-07-06 06:31:05 -0500263 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500264
George Keishingf5a57502021-07-22 16:43:47 -0500265 # Find the list of target and protocol supported.
266 check_protocol_list = []
267 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500268
George Keishingf5a57502021-07-22 16:43:47 -0500269 for target_type in config_dict.keys():
270 if self.target_type != target_type:
271 continue
George Keishingeafba182021-06-29 13:44:58 -0500272
George Keishingf5a57502021-07-22 16:43:47 -0500273 for k, v in config_dict[target_type].items():
George Keishinge635ddc2022-12-08 07:38:02 -0600274 if config_dict[target_type][k]['PROTOCOL'][0] not in check_protocol_list:
275 check_protocol_list.append(config_dict[target_type][k]['PROTOCOL'][0])
Peter D Phanbff617a2021-07-22 08:41:35 -0500276
George Keishinge635ddc2022-12-08 07:38:02 -0600277 self.logger.info("\n\t %s protocol type: %s" % (self.target_type, check_protocol_list))
Peter D Phanbff617a2021-07-22 08:41:35 -0500278
George Keishingf5a57502021-07-22 16:43:47 -0500279 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500280
George Keishingf5a57502021-07-22 16:43:47 -0500281 if verified_working_protocol:
George Keishinge635ddc2022-12-08 07:38:02 -0600282 self.logger.info("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500283
George Keishingf5a57502021-07-22 16:43:47 -0500284 # Verify top level directory exists for storage
285 self.validate_local_store(self.location)
286
George Keishinge635ddc2022-12-08 07:38:02 -0600287 if ((self.remote_protocol not in verified_working_protocol) and (self.remote_protocol != 'ALL')):
288 self.logger.info("\n\tWorking protocol list: %s" % verified_working_protocol)
George Keishingf5a57502021-07-22 16:43:47 -0500289 self.logger.error(
George Keishinge635ddc2022-12-08 07:38:02 -0600290 '\tERROR: Requested protocol %s is not in working protocol list.\n'
291 % self.remote_protocol)
George Keishingf5a57502021-07-22 16:43:47 -0500292 sys.exit(-1)
293 else:
294 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500295
296 def ssh_to_target_system(self):
297 r"""
298 Open a ssh connection to targeted system.
299
300 """
301
George Keishinge635ddc2022-12-08 07:38:02 -0600302 self.ssh_remoteclient = SSHRemoteclient(self.hostname,
303 self.username,
304 self.password)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500305
Peter D Phan5963d632021-07-12 09:58:55 -0500306 if self.ssh_remoteclient.ssh_remoteclient_login():
George Keishinge635ddc2022-12-08 07:38:02 -0600307 self.logger.info("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500308
Peter D Phan5963d632021-07-12 09:58:55 -0500309 # Check scp connection.
310 # If scp connection fails,
311 # continue with FFDC generation but skip scp files to local host.
312 self.ssh_remoteclient.scp_connection()
313 return True
314 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600315 self.logger.info("\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500316 return False
317
318 def telnet_to_target_system(self):
319 r"""
320 Open a telnet connection to targeted system.
321 """
George Keishinge635ddc2022-12-08 07:38:02 -0600322 self.telnet_remoteclient = TelnetRemoteclient(self.hostname,
323 self.username,
324 self.password)
Peter D Phan5963d632021-07-12 09:58:55 -0500325 if self.telnet_remoteclient.tn_remoteclient_login():
George Keishinge635ddc2022-12-08 07:38:02 -0600326 self.logger.info("\n\t[Check] %s Telnet connection established.\t [OK]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500327 return True
328 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600329 self.logger.info("\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500330 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500331
George Keishing772c9772021-06-16 23:23:42 -0500332 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500333 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500334 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500335
Peter D Phan04aca3b2021-06-21 10:37:18 -0500336 Description of argument(s):
337 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500338 """
339
George Keishinge635ddc2022-12-08 07:38:02 -0600340 self.logger.info("\n\t---- Executing commands on " + self.hostname + " ----")
341 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500342
George Keishingf5a57502021-07-22 16:43:47 -0500343 config_dict = self.ffdc_actions
344 for target_type in config_dict.keys():
345 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500346 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500347
Peter D Phane86d9a52021-07-15 10:42:25 -0500348 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
George Keishinge635ddc2022-12-08 07:38:02 -0600349 global_plugin_dict['global_log_store_path'] = self.ffdc_dir_path
George Keishingf5a57502021-07-22 16:43:47 -0500350 self.logger.info("\tSystem Type: %s" % target_type)
351 for k, v in config_dict[target_type].items():
George Keishinge635ddc2022-12-08 07:38:02 -0600352
353 if self.remote_protocol not in working_protocol_list \
354 and self.remote_protocol != 'ALL':
George Keishing6ea92b02021-07-01 11:20:50 -0500355 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500356
George Keishinge635ddc2022-12-08 07:38:02 -0600357 protocol = config_dict[target_type][k]['PROTOCOL'][0]
George Keishingf5a57502021-07-22 16:43:47 -0500358
359 if protocol not in working_protocol_list:
360 continue
361
George Keishingb7607612021-07-27 13:31:23 -0500362 if protocol in working_protocol_list:
George Keishinge635ddc2022-12-08 07:38:02 -0600363 if protocol == 'SSH' or protocol == 'SCP':
George Keishing12fd0652021-07-27 13:57:11 -0500364 self.protocol_ssh(protocol, target_type, k)
George Keishinge635ddc2022-12-08 07:38:02 -0600365 elif protocol == 'TELNET':
George Keishingf5a57502021-07-22 16:43:47 -0500366 self.protocol_telnet(target_type, k)
George Keishinge635ddc2022-12-08 07:38:02 -0600367 elif protocol == 'REDFISH' or protocol == 'IPMI' or protocol == 'SHELL':
George Keishing506b0582021-07-27 09:31:22 -0500368 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500369 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600370 self.logger.error("\n\tERROR: %s is not available for %s." % (protocol, self.hostname))
George Keishingeafba182021-06-29 13:44:58 -0500371
Peter D Phan04aca3b2021-06-21 10:37:18 -0500372 # Close network connection after collecting all files
George Keishinge635ddc2022-12-08 07:38:02 -0600373 self.elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - self.start_time))
Peter D Phanbff617a2021-07-22 08:41:35 -0500374 if self.ssh_remoteclient:
375 self.ssh_remoteclient.ssh_remoteclient_disconnect()
376 if self.telnet_remoteclient:
377 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500378
George Keishinge635ddc2022-12-08 07:38:02 -0600379 def protocol_ssh(self,
380 protocol,
381 target_type,
382 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500383 r"""
384 Perform actions using SSH and SCP protocols.
385
386 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500387 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500388 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500389 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500390 """
391
George Keishinge635ddc2022-12-08 07:38:02 -0600392 if protocol == 'SCP':
George Keishingf5a57502021-07-22 16:43:47 -0500393 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500394 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600395 self.collect_and_copy_ffdc(self.ffdc_actions[target_type][sub_type])
Peter D Phan0c669772021-06-24 13:52:42 -0500396
George Keishinge635ddc2022-12-08 07:38:02 -0600397 def protocol_telnet(self,
398 target_type,
399 sub_type):
Peter D Phan5963d632021-07-12 09:58:55 -0500400 r"""
401 Perform actions using telnet protocol.
402 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500403 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500404 """
George Keishinge635ddc2022-12-08 07:38:02 -0600405 self.logger.info("\n\t[Run] Executing commands on %s using %s" % (self.hostname, 'TELNET'))
Peter D Phan5963d632021-07-12 09:58:55 -0500406 telnet_files_saved = []
407 progress_counter = 0
George Keishinge635ddc2022-12-08 07:38:02 -0600408 list_of_commands = self.ffdc_actions[target_type][sub_type]['COMMANDS']
Peter D Phan5963d632021-07-12 09:58:55 -0500409 for index, each_cmd in enumerate(list_of_commands, start=0):
410 command_txt, command_timeout = self.unpack_command(each_cmd)
George Keishinge635ddc2022-12-08 07:38:02 -0600411 result = self.telnet_remoteclient.execute_command(command_txt, command_timeout)
Peter D Phan5963d632021-07-12 09:58:55 -0500412 if result:
413 try:
George Keishinge635ddc2022-12-08 07:38:02 -0600414 targ_file = self.ffdc_actions[target_type][sub_type]['FILES'][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500415 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500416 targ_file = command_txt
417 self.logger.warning(
George Keishinge635ddc2022-12-08 07:38:02 -0600418 "\n\t[WARN] Missing filename to store data from telnet %s." % each_cmd)
419 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
420 targ_file_with_path = (self.ffdc_dir_path
421 + self.ffdc_prefix
422 + targ_file)
Peter D Phan5963d632021-07-12 09:58:55 -0500423 # Creates a new file
George Keishinge635ddc2022-12-08 07:38:02 -0600424 with open(targ_file_with_path, 'w') as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500425 fp.write(result)
426 fp.close
427 telnet_files_saved.append(targ_file)
428 progress_counter += 1
429 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500430 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500431 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500432 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500433
George Keishinge635ddc2022-12-08 07:38:02 -0600434 def protocol_execute(self,
435 protocol,
436 target_type,
437 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500438 r"""
George Keishing506b0582021-07-27 09:31:22 -0500439 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500440
441 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500442 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500443 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500444 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500445 """
446
George Keishinge635ddc2022-12-08 07:38:02 -0600447 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, protocol))
George Keishing506b0582021-07-27 09:31:22 -0500448 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500449 progress_counter = 0
George Keishinge635ddc2022-12-08 07:38:02 -0600450 list_of_cmd = self.get_command_list(self.ffdc_actions[target_type][sub_type])
George Keishingeafba182021-06-29 13:44:58 -0500451 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500452 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500453 if isinstance(each_cmd, dict):
George Keishinge635ddc2022-12-08 07:38:02 -0600454 if 'plugin' in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500455 # If the error is set and plugin explicitly
456 # requested to skip execution on error..
George Keishinge635ddc2022-12-08 07:38:02 -0600457 if plugin_error_dict['exit_on_error'] and \
458 self.plugin_error_check(each_cmd['plugin']):
459 self.logger.info("\n\t[PLUGIN-ERROR] exit_on_error: %s" %
460 plugin_error_dict['exit_on_error'])
461 self.logger.info("\t[PLUGIN-SKIP] %s" %
462 each_cmd['plugin'][0])
George Keishing1e7b0182021-08-06 14:05:54 -0500463 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500464 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500465 # call the plugin
466 self.logger.info("\n\t[PLUGIN-START]")
George Keishinge635ddc2022-12-08 07:38:02 -0600467 result = self.execute_plugin_block(each_cmd['plugin'])
George Keishingb97a9042021-07-29 07:41:20 -0500468 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500469 else:
George Keishing2b83e042021-08-03 12:56:11 -0500470 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500471
George Keishingcaa97e62021-08-03 14:00:09 -0500472 if not plugin_call:
473 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500474 if result:
475 try:
George Keishinge635ddc2022-12-08 07:38:02 -0600476 file_name = self.get_file_list(self.ffdc_actions[target_type][sub_type])[index]
George Keishingb97a9042021-07-29 07:41:20 -0500477 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500478 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500479 continue
George Keishinge635ddc2022-12-08 07:38:02 -0600480 targ_file = self.yaml_env_and_plugin_vars_populate(file_name)
George Keishingeafba182021-06-29 13:44:58 -0500481 except IndexError:
George Keishinge635ddc2022-12-08 07:38:02 -0600482 targ_file = each_cmd.split('/')[-1]
George Keishing506b0582021-07-27 09:31:22 -0500483 self.logger.warning(
George Keishinge635ddc2022-12-08 07:38:02 -0600484 "\n\t[WARN] Missing filename to store data from %s." % each_cmd)
485 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500486
George Keishinge635ddc2022-12-08 07:38:02 -0600487 targ_file_with_path = (self.ffdc_dir_path
488 + self.ffdc_prefix
489 + targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500490
491 # Creates a new file
George Keishinge635ddc2022-12-08 07:38:02 -0600492 with open(targ_file_with_path, 'w') as fp:
George Keishing91308ea2021-08-10 14:43:15 -0500493 if isinstance(result, dict):
494 fp.write(json.dumps(result))
495 else:
496 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500497 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500498 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500499
500 progress_counter += 1
501 self.print_progress(progress_counter)
502
Peter D Phane86d9a52021-07-15 10:42:25 -0500503 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500504
George Keishing506b0582021-07-27 09:31:22 -0500505 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500506 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500507
George Keishinge635ddc2022-12-08 07:38:02 -0600508 def collect_and_copy_ffdc(self,
509 ffdc_actions_for_target_type,
510 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500511 r"""
512 Send commands in ffdc_config file to targeted system.
513
514 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500515 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500516 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500517 """
518
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500519 # Executing commands, if any
George Keishinge635ddc2022-12-08 07:38:02 -0600520 self.ssh_execute_ffdc_commands(ffdc_actions_for_target_type,
521 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500522
Peter D Phan3beb02e2021-07-06 13:25:17 -0500523 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500524 if self.ssh_remoteclient.scpclient:
George Keishinge635ddc2022-12-08 07:38:02 -0600525 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500526
Peter D Phan04aca3b2021-06-21 10:37:18 -0500527 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500528 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
George Keishinge635ddc2022-12-08 07:38:02 -0600529 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500530 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600531 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500532
George Keishinge635ddc2022-12-08 07:38:02 -0600533 def get_command_list(self,
534 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500535 r"""
536 Fetch list of commands from configuration file
537
538 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500539 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500540 """
541 try:
George Keishinge635ddc2022-12-08 07:38:02 -0600542 list_of_commands = ffdc_actions_for_target_type['COMMANDS']
Peter D Phanbabf2962021-07-07 11:24:40 -0500543 except KeyError:
544 list_of_commands = []
545 return list_of_commands
546
George Keishinge635ddc2022-12-08 07:38:02 -0600547 def get_file_list(self,
548 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500549 r"""
550 Fetch list of commands from configuration file
551
552 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500553 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500554 """
555 try:
George Keishinge635ddc2022-12-08 07:38:02 -0600556 list_of_files = ffdc_actions_for_target_type['FILES']
Peter D Phanbabf2962021-07-07 11:24:40 -0500557 except KeyError:
558 list_of_files = []
559 return list_of_files
560
George Keishinge635ddc2022-12-08 07:38:02 -0600561 def unpack_command(self,
562 command):
Peter D Phan5963d632021-07-12 09:58:55 -0500563 r"""
564 Unpack command from config file
565
566 Description of argument(s):
567 command Command from config file.
568 """
569 if isinstance(command, dict):
570 command_txt = next(iter(command))
571 command_timeout = next(iter(command.values()))
572 elif isinstance(command, str):
573 command_txt = command
574 # Default command timeout 60 seconds
575 command_timeout = 60
576
577 return command_txt, command_timeout
578
George Keishinge635ddc2022-12-08 07:38:02 -0600579 def ssh_execute_ffdc_commands(self,
580 ffdc_actions_for_target_type,
581 form_filename=False):
Peter D Phan3beb02e2021-07-06 13:25:17 -0500582 r"""
583 Send commands in ffdc_config file to targeted system.
584
585 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500586 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500587 form_filename if true, pre-pend self.target_type to filename
588 """
George Keishinge635ddc2022-12-08 07:38:02 -0600589 self.logger.info("\n\t[Run] Executing commands on %s using %s"
590 % (self.hostname, ffdc_actions_for_target_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500591
George Keishingf5a57502021-07-22 16:43:47 -0500592 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500593 # If command list is empty, returns
594 if not list_of_commands:
595 return
596
597 progress_counter = 0
598 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500599 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500600
601 if form_filename:
602 command_txt = str(command_txt % self.target_type)
603
George Keishinge635ddc2022-12-08 07:38:02 -0600604 cmd_exit_code, err, response = \
605 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500606
607 if cmd_exit_code:
608 self.logger.warning(
George Keishinge635ddc2022-12-08 07:38:02 -0600609 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500610 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500611
Peter D Phan3beb02e2021-07-06 13:25:17 -0500612 progress_counter += 1
613 self.print_progress(progress_counter)
614
Peter D Phane86d9a52021-07-15 10:42:25 -0500615 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500616
George Keishinge635ddc2022-12-08 07:38:02 -0600617 def group_copy(self,
618 ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500619 r"""
620 scp group of files (wild card) from remote host.
621
622 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500623 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500624 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500625
Peter D Phan5963d632021-07-12 09:58:55 -0500626 if self.ssh_remoteclient.scpclient:
George Keishinge635ddc2022-12-08 07:38:02 -0600627 self.logger.info("\n\tCopying files from remote system %s via SCP.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500628
George Keishinge635ddc2022-12-08 07:38:02 -0600629 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phanbabf2962021-07-07 11:24:40 -0500630 # If command list is empty, returns
631 if not list_of_commands:
632 return
Peter D Phan56429a62021-06-23 08:38:29 -0500633
Peter D Phanbabf2962021-07-07 11:24:40 -0500634 for command in list_of_commands:
635 try:
George Keishingb4540e72021-08-02 13:48:46 -0500636 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500637 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500638 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500639 continue
640
George Keishinge635ddc2022-12-08 07:38:02 -0600641 cmd_exit_code, err, response = \
642 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500643
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500644 # If file does not exist, code take no action.
645 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500646 if response:
George Keishinge635ddc2022-12-08 07:38:02 -0600647 scp_result = \
648 self.ssh_remoteclient.scp_file_from_remote(response.split('\n'),
649 self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500650 if scp_result:
George Keishinge635ddc2022-12-08 07:38:02 -0600651 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + command)
Peter D Phan56429a62021-06-23 08:38:29 -0500652 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500653 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500654
655 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600656 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500657
George Keishinge635ddc2022-12-08 07:38:02 -0600658 def scp_ffdc(self,
659 targ_dir_path,
660 targ_file_prefix,
661 form_filename,
662 file_list=None,
663 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500664 r"""
665 SCP all files in file_dict to the indicated directory on the local system.
666
667 Description of argument(s):
668 targ_dir_path The path of the directory to receive the files.
669 targ_file_prefix Prefix which will be pre-pended to each
670 target file's name.
671 file_dict A dictionary of files to scp from targeted system to this system
672
673 """
674
Peter D Phan72ce6b82021-06-03 06:18:26 -0500675 progress_counter = 0
676 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500677 if form_filename:
678 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500679 source_file_path = filename
George Keishinge635ddc2022-12-08 07:38:02 -0600680 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
Peter D Phan72ce6b82021-06-03 06:18:26 -0500681
Peter D Phanbabf2962021-07-07 11:24:40 -0500682 # If source file name contains wild card, copy filename as is.
George Keishinge635ddc2022-12-08 07:38:02 -0600683 if '*' in source_file_path:
684 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500685 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600686 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500687
688 if not quiet:
689 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500690 self.logger.info(
George Keishinge635ddc2022-12-08 07:38:02 -0600691 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500692 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500693 self.logger.info(
George Keishinge635ddc2022-12-08 07:38:02 -0600694 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500695 else:
696 progress_counter += 1
697 self.print_progress(progress_counter)
698
Peter D Phan5e56f522021-12-20 13:19:41 -0600699 def set_ffdc_default_store_path(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500700 r"""
701 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
702 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
703 Individual ffdc file will have timestr_filename.
704
705 Description of class variables:
706 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
707
708 self.ffdc_prefix The prefix to be given to each ffdc file name.
709
710 """
711
712 timestr = time.strftime("%Y%m%d-%H%M%S")
George Keishinge635ddc2022-12-08 07:38:02 -0600713 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
Peter D Phan72ce6b82021-06-03 06:18:26 -0500714 self.ffdc_prefix = timestr + "_"
715 self.validate_local_store(self.ffdc_dir_path)
716
Peter D Phan5e56f522021-12-20 13:19:41 -0600717 # Need to verify local store path exists prior to instantiate this class.
718 # This class method is used to share the same code between CLI input parm
719 # and Robot Framework "${EXECDIR}/logs" before referencing this class.
720 @classmethod
721 def validate_local_store(cls, dir_path):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500722 r"""
723 Ensure path exists to store FFDC files locally.
724
725 Description of variable:
726 dir_path The dir path where collected ffdc data files will be stored.
727
728 """
729
730 if not os.path.exists(dir_path):
731 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500732 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500733 except (IOError, OSError) as e:
734 # PermissionError
735 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500736 self.logger.error(
George Keishinge635ddc2022-12-08 07:38:02 -0600737 '\tERROR: os.makedirs %s failed with PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500738 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500739 self.logger.error(
George Keishinge635ddc2022-12-08 07:38:02 -0600740 '\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500741 sys.exit(-1)
742
743 def print_progress(self, progress):
744 r"""
745 Print activity progress +
746
747 Description of variable:
748 progress Progress counter.
749
750 """
751
752 sys.stdout.write("\r\t" + "+" * progress)
753 sys.stdout.flush()
George Keishinge635ddc2022-12-08 07:38:02 -0600754 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500755
756 def verify_redfish(self):
757 r"""
758 Verify remote host has redfish service active
759
760 """
George Keishinge635ddc2022-12-08 07:38:02 -0600761 redfish_parm = 'redfishtool -r ' \
762 + self.hostname + ' -S Always raw GET /redfish/v1/'
763 return (self.run_tool_cmd(redfish_parm, True))
Peter D Phan0c669772021-06-24 13:52:42 -0500764
George Keishingeafba182021-06-29 13:44:58 -0500765 def verify_ipmi(self):
766 r"""
767 Verify remote host has IPMI LAN service active
768
769 """
George Keishinge635ddc2022-12-08 07:38:02 -0600770 if self.target_type == 'OPENBMC':
771 ipmi_parm = 'ipmitool -I lanplus -C 17 -U ' + self.username + ' -P ' \
772 + self.password + ' -H ' + self.hostname + ' power status'
George Keishing484f8242021-07-27 01:42:02 -0500773 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600774 ipmi_parm = 'ipmitool -I lanplus -P ' \
775 + self.password + ' -H ' + self.hostname + ' power status'
George Keishing484f8242021-07-27 01:42:02 -0500776
George Keishinge635ddc2022-12-08 07:38:02 -0600777 return (self.run_tool_cmd(ipmi_parm, True))
George Keishingeafba182021-06-29 13:44:58 -0500778
George Keishinge635ddc2022-12-08 07:38:02 -0600779 def run_tool_cmd(self,
780 parms_string,
781 quiet=False):
George Keishingeafba182021-06-29 13:44:58 -0500782 r"""
George Keishing506b0582021-07-27 09:31:22 -0500783 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500784
785 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500786 parms_string tool command options.
787 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500788 """
789
George Keishinge635ddc2022-12-08 07:38:02 -0600790 result = subprocess.run([parms_string],
791 stdout=subprocess.PIPE,
792 stderr=subprocess.PIPE,
793 shell=True,
794 universal_newlines=True)
George Keishingeafba182021-06-29 13:44:58 -0500795
796 if result.stderr and not quiet:
George Keishinge635ddc2022-12-08 07:38:02 -0600797 self.logger.error('\n\t\tERROR with %s ' % parms_string)
798 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500799
800 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500801
George Keishingf5a57502021-07-22 16:43:47 -0500802 def verify_protocol(self, protocol_list):
803 r"""
804 Perform protocol working check.
805
806 Description of argument(s):
807 protocol_list List of protocol.
808 """
809
810 tmp_list = []
811 if self.target_is_pingable():
812 tmp_list.append("SHELL")
813
814 for protocol in protocol_list:
George Keishinge635ddc2022-12-08 07:38:02 -0600815 if self.remote_protocol != 'ALL':
George Keishingf5a57502021-07-22 16:43:47 -0500816 if self.remote_protocol != protocol:
817 continue
818
819 # Only check SSH/SCP once for both protocols
George Keishinge635ddc2022-12-08 07:38:02 -0600820 if protocol == 'SSH' or protocol == 'SCP' and protocol not in tmp_list:
George Keishingf5a57502021-07-22 16:43:47 -0500821 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -0500822 # Add only what user asked.
George Keishinge635ddc2022-12-08 07:38:02 -0600823 if self.remote_protocol != 'ALL':
George Keishingaa638702021-07-26 11:48:28 -0500824 tmp_list.append(self.remote_protocol)
825 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600826 tmp_list.append('SSH')
827 tmp_list.append('SCP')
George Keishingf5a57502021-07-22 16:43:47 -0500828
George Keishinge635ddc2022-12-08 07:38:02 -0600829 if protocol == 'TELNET':
George Keishingf5a57502021-07-22 16:43:47 -0500830 if self.telnet_to_target_system():
831 tmp_list.append(protocol)
832
George Keishinge635ddc2022-12-08 07:38:02 -0600833 if protocol == 'REDFISH':
George Keishingf5a57502021-07-22 16:43:47 -0500834 if self.verify_redfish():
835 tmp_list.append(protocol)
George Keishinge635ddc2022-12-08 07:38:02 -0600836 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
George Keishingf5a57502021-07-22 16:43:47 -0500837 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600838 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
George Keishingf5a57502021-07-22 16:43:47 -0500839
George Keishinge635ddc2022-12-08 07:38:02 -0600840 if protocol == 'IPMI':
George Keishingf5a57502021-07-22 16:43:47 -0500841 if self.verify_ipmi():
842 tmp_list.append(protocol)
George Keishinge635ddc2022-12-08 07:38:02 -0600843 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
George Keishingf5a57502021-07-22 16:43:47 -0500844 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600845 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
George Keishingf5a57502021-07-22 16:43:47 -0500846
847 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -0500848
849 def load_env(self):
850 r"""
851 Perform protocol working check.
852
853 """
854 # This is for the env vars a user can use in YAML to load it at runtime.
855 # Example YAML:
856 # -COMMANDS:
857 # - my_command ${hostname} ${username} ${password}
George Keishinge635ddc2022-12-08 07:38:02 -0600858 os.environ['hostname'] = self.hostname
859 os.environ['username'] = self.username
860 os.environ['password'] = self.password
George Keishinge1686752021-07-27 12:55:28 -0500861
862 # Append default Env.
George Keishinge635ddc2022-12-08 07:38:02 -0600863 self.env_dict['hostname'] = self.hostname
864 self.env_dict['username'] = self.username
865 self.env_dict['password'] = self.password
George Keishinge1686752021-07-27 12:55:28 -0500866
867 try:
868 tmp_env_dict = {}
869 if self.env_vars:
870 tmp_env_dict = json.loads(self.env_vars)
871 # Export ENV vars default.
872 for key, value in tmp_env_dict.items():
873 os.environ[key] = value
874 self.env_dict[key] = str(value)
875
876 if self.econfig:
George Keishinge635ddc2022-12-08 07:38:02 -0600877 with open(self.econfig, 'r') as file:
George Keishinge9b23d32021-08-13 12:57:58 -0500878 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -0700879 tmp_env_dict = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -0500880 except yaml.YAMLError as e:
881 self.logger.error(e)
882 sys.exit(-1)
George Keishinge1686752021-07-27 12:55:28 -0500883 # Export ENV vars.
George Keishinge635ddc2022-12-08 07:38:02 -0600884 for key, value in tmp_env_dict['env_params'].items():
George Keishinge1686752021-07-27 12:55:28 -0500885 os.environ[key] = str(value)
886 self.env_dict[key] = str(value)
887 except json.decoder.JSONDecodeError as e:
888 self.logger.error("\n\tERROR: %s " % e)
889 sys.exit(-1)
890
891 # This to mask the password from displaying on the console.
892 mask_dict = self.env_dict.copy()
893 for k, v in mask_dict.items():
894 if k.lower().find("password") != -1:
895 hidden_text = []
896 hidden_text.append(v)
George Keishinge635ddc2022-12-08 07:38:02 -0600897 password_regex = '(' +\
898 '|'.join([re.escape(x) for x in hidden_text]) + ')'
George Keishinge1686752021-07-27 12:55:28 -0500899 mask_dict[k] = re.sub(password_regex, "********", v)
900
901 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -0500902
903 def execute_python_eval(self, eval_string):
904 r"""
George Keishing9348b402021-08-13 12:22:35 -0500905 Execute qualified python function string using eval.
George Keishingb97a9042021-07-29 07:41:20 -0500906
907 Description of argument(s):
908 eval_string Execute the python object.
909
910 Example:
911 eval(plugin.foo_func.foo_func(10))
912 """
913 try:
George Keishingdda48ce2021-08-12 07:02:27 -0500914 self.logger.info("\tExecuting plugin func()")
915 self.logger.debug("\tCall func: %s" % eval_string)
George Keishingb97a9042021-07-29 07:41:20 -0500916 result = eval(eval_string)
917 self.logger.info("\treturn: %s" % str(result))
George Keishinge635ddc2022-12-08 07:38:02 -0600918 except (ValueError,
919 SyntaxError,
920 NameError,
921 AttributeError,
922 TypeError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -0500923 self.logger.error("\tERROR: execute_python_eval: %s" % e)
924 # Set the plugin error state.
George Keishinge635ddc2022-12-08 07:38:02 -0600925 plugin_error_dict['exit_on_error'] = True
George Keishing73b95d12021-08-13 14:30:52 -0500926 self.logger.info("\treturn: PLUGIN_EVAL_ERROR")
George Keishinge635ddc2022-12-08 07:38:02 -0600927 return 'PLUGIN_EVAL_ERROR'
George Keishingb97a9042021-07-29 07:41:20 -0500928
929 return result
930
931 def execute_plugin_block(self, plugin_cmd_list):
932 r"""
Peter D Phan5e56f522021-12-20 13:19:41 -0600933 Pack the plugin command to qualifed python string object.
George Keishingb97a9042021-07-29 07:41:20 -0500934
935 Description of argument(s):
936 plugin_list_dict Plugin block read from YAML
937 [{'plugin_name': 'plugin.foo_func.my_func'},
938 {'plugin_args': [10]}]
939
940 Example:
941 - plugin:
942 - plugin_name: plugin.foo_func.my_func
943 - plugin_args:
944 - arg1
945 - arg2
946
947 - plugin:
948 - plugin_name: result = plugin.foo_func.my_func
949 - plugin_args:
950 - arg1
951 - arg2
952
953 - plugin:
954 - plugin_name: result1,result2 = plugin.foo_func.my_func
955 - plugin_args:
956 - arg1
957 - arg2
958 """
959 try:
George Keishinge635ddc2022-12-08 07:38:02 -0600960 idx = self.key_index_list_dict('plugin_name', plugin_cmd_list)
961 plugin_name = plugin_cmd_list[idx]['plugin_name']
George Keishingb97a9042021-07-29 07:41:20 -0500962 # Equal separator means plugin function returns result.
George Keishinge635ddc2022-12-08 07:38:02 -0600963 if ' = ' in plugin_name:
George Keishingb97a9042021-07-29 07:41:20 -0500964 # Ex. ['result', 'plugin.foo_func.my_func']
George Keishinge635ddc2022-12-08 07:38:02 -0600965 plugin_name_args = plugin_name.split(' = ')
George Keishingb97a9042021-07-29 07:41:20 -0500966 # plugin func return data.
967 for arg in plugin_name_args:
968 if arg == plugin_name_args[-1]:
969 plugin_name = arg
970 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600971 plugin_resp = arg.split(',')
George Keishingb97a9042021-07-29 07:41:20 -0500972 # ['result1','result2']
973 for x in plugin_resp:
974 global_plugin_list.append(x)
975 global_plugin_dict[x] = ""
976
977 # Walk the plugin args ['arg1,'arg2']
978 # If the YAML plugin statement 'plugin_args' is not declared.
George Keishinge635ddc2022-12-08 07:38:02 -0600979 if any('plugin_args' in d for d in plugin_cmd_list):
980 idx = self.key_index_list_dict('plugin_args', plugin_cmd_list)
981 plugin_args = plugin_cmd_list[idx]['plugin_args']
George Keishingb97a9042021-07-29 07:41:20 -0500982 if plugin_args:
983 plugin_args = self.yaml_args_populate(plugin_args)
984 else:
985 plugin_args = []
986 else:
987 plugin_args = self.yaml_args_populate([])
988
989 # Pack the args arg1, arg2, .... argn into
990 # "arg1","arg2","argn" string as params for function.
991 parm_args_str = self.yaml_args_string(plugin_args)
992 if parm_args_str:
George Keishinge635ddc2022-12-08 07:38:02 -0600993 plugin_func = plugin_name + '(' + parm_args_str + ')'
George Keishingb97a9042021-07-29 07:41:20 -0500994 else:
George Keishinge635ddc2022-12-08 07:38:02 -0600995 plugin_func = plugin_name + '()'
George Keishingb97a9042021-07-29 07:41:20 -0500996
997 # Execute plugin function.
998 if global_plugin_dict:
999 resp = self.execute_python_eval(plugin_func)
George Keishing9348b402021-08-13 12:22:35 -05001000 # Update plugin vars dict if there is any.
George Keishinge635ddc2022-12-08 07:38:02 -06001001 if resp != 'PLUGIN_EVAL_ERROR':
George Keishing73b95d12021-08-13 14:30:52 -05001002 self.response_args_data(resp)
George Keishingb97a9042021-07-29 07:41:20 -05001003 else:
George Keishingcaa97e62021-08-03 14:00:09 -05001004 resp = self.execute_python_eval(plugin_func)
George Keishingb97a9042021-07-29 07:41:20 -05001005 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001006 # Set the plugin error state.
George Keishinge635ddc2022-12-08 07:38:02 -06001007 plugin_error_dict['exit_on_error'] = True
George Keishing1e7b0182021-08-06 14:05:54 -05001008 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001009 pass
1010
George Keishing73b95d12021-08-13 14:30:52 -05001011 # There is a real error executing the plugin function.
George Keishinge635ddc2022-12-08 07:38:02 -06001012 if resp == 'PLUGIN_EVAL_ERROR':
George Keishing73b95d12021-08-13 14:30:52 -05001013 return resp
1014
George Keishingde79a9b2021-08-12 16:14:43 -05001015 # Check if plugin_expects_return (int, string, list,dict etc)
George Keishinge635ddc2022-12-08 07:38:02 -06001016 if any('plugin_expects_return' in d for d in plugin_cmd_list):
1017 idx = self.key_index_list_dict('plugin_expects_return', plugin_cmd_list)
1018 plugin_expects = plugin_cmd_list[idx]['plugin_expects_return']
George Keishingde79a9b2021-08-12 16:14:43 -05001019 if plugin_expects:
1020 if resp:
George Keishinge635ddc2022-12-08 07:38:02 -06001021 if self.plugin_expect_type(plugin_expects, resp) == 'INVALID':
George Keishingde79a9b2021-08-12 16:14:43 -05001022 self.logger.error("\tWARN: Plugin error check skipped")
1023 elif not self.plugin_expect_type(plugin_expects, resp):
George Keishinge635ddc2022-12-08 07:38:02 -06001024 self.logger.error("\tERROR: Plugin expects return data: %s"
1025 % plugin_expects)
1026 plugin_error_dict['exit_on_error'] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001027 elif not resp:
George Keishinge635ddc2022-12-08 07:38:02 -06001028 self.logger.error("\tERROR: Plugin func failed to return data")
1029 plugin_error_dict['exit_on_error'] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001030
1031 return resp
1032
George Keishingb97a9042021-07-29 07:41:20 -05001033 def response_args_data(self, plugin_resp):
1034 r"""
George Keishing9348b402021-08-13 12:22:35 -05001035 Parse the plugin function response and update plugin return variable.
George Keishingb97a9042021-07-29 07:41:20 -05001036
1037 plugin_resp Response data from plugin function.
1038 """
1039 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -05001040 resp_data = ""
George Keishing9348b402021-08-13 12:22:35 -05001041
George Keishingb97a9042021-07-29 07:41:20 -05001042 # There is nothing to update the plugin response.
George Keishinge635ddc2022-12-08 07:38:02 -06001043 if len(global_plugin_list) == 0 or plugin_resp == 'None':
George Keishingb97a9042021-07-29 07:41:20 -05001044 return
1045
George Keishing5765f792021-08-02 13:08:53 -05001046 if isinstance(plugin_resp, str):
George Keishinge635ddc2022-12-08 07:38:02 -06001047 resp_data = plugin_resp.strip('\r\n\t')
George Keishing5765f792021-08-02 13:08:53 -05001048 resp_list.append(resp_data)
1049 elif isinstance(plugin_resp, bytes):
George Keishinge635ddc2022-12-08 07:38:02 -06001050 resp_data = str(plugin_resp, 'UTF-8').strip('\r\n\t')
George Keishing5765f792021-08-02 13:08:53 -05001051 resp_list.append(resp_data)
1052 elif isinstance(plugin_resp, tuple):
1053 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -05001054 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -05001055 else:
1056 resp_list = list(plugin_resp)
George Keishinge635ddc2022-12-08 07:38:02 -06001057 resp_list = [x.strip('\r\n\t') for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -05001058 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -05001059 if len(global_plugin_list) == 1:
George Keishinge635ddc2022-12-08 07:38:02 -06001060 resp_list.append([x.strip('\r\n\t') for x in plugin_resp])
George Keishing5765f792021-08-02 13:08:53 -05001061 else:
George Keishinge635ddc2022-12-08 07:38:02 -06001062 resp_list = [x.strip('\r\n\t') for x in plugin_resp]
George Keishing5765f792021-08-02 13:08:53 -05001063 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1064 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001065
George Keishing9348b402021-08-13 12:22:35 -05001066 # Iterate if there is a list of plugin return vars to update.
George Keishingb97a9042021-07-29 07:41:20 -05001067 for idx, item in enumerate(resp_list, start=0):
George Keishing9348b402021-08-13 12:22:35 -05001068 # Exit loop, done required loop.
George Keishingb97a9042021-07-29 07:41:20 -05001069 if idx >= len(global_plugin_list):
1070 break
1071 # Find the index of the return func in the list and
1072 # update the global func return dictionary.
1073 try:
1074 dict_idx = global_plugin_list[idx]
1075 global_plugin_dict[dict_idx] = item
1076 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001077 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001078 pass
1079
1080 # Done updating plugin dict irrespective of pass or failed,
George Keishing9348b402021-08-13 12:22:35 -05001081 # clear all the list element for next plugin block execute.
George Keishingb97a9042021-07-29 07:41:20 -05001082 global_plugin_list.clear()
1083
1084 def yaml_args_string(self, plugin_args):
1085 r"""
1086 Pack the args into string.
1087
1088 plugin_args arg list ['arg1','arg2,'argn']
1089 """
George Keishinge635ddc2022-12-08 07:38:02 -06001090 args_str = ''
George Keishingb97a9042021-07-29 07:41:20 -05001091 for args in plugin_args:
1092 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001093 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001094 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001095 elif args in global_plugin_type_list:
1096 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001097 else:
George Keishinge635ddc2022-12-08 07:38:02 -06001098 args_str += '"' + str(args.strip('\r\n\t')) + '"'
George Keishingb97a9042021-07-29 07:41:20 -05001099 # Skip last list element.
1100 if args != plugin_args[-1]:
1101 args_str += ","
1102 return args_str
1103
1104 def yaml_args_populate(self, yaml_arg_list):
1105 r"""
George Keishing9348b402021-08-13 12:22:35 -05001106 Decode env and plugin vars and populate.
George Keishingb97a9042021-07-29 07:41:20 -05001107
1108 Description of argument(s):
1109 yaml_arg_list arg list read from YAML
1110
1111 Example:
1112 - plugin_args:
1113 - arg1
1114 - arg2
1115
1116 yaml_arg_list: [arg2, arg2]
1117 """
1118 # Get the env loaded keys as list ['hostname', 'username', 'password'].
1119 env_vars_list = list(self.env_dict)
1120
1121 if isinstance(yaml_arg_list, list):
1122 tmp_list = []
1123 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001124 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001125 tmp_list.append(arg)
1126 continue
1127 elif isinstance(arg, str):
1128 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1129 tmp_list.append(arg_str)
1130 else:
1131 tmp_list.append(arg)
1132
1133 # return populated list.
1134 return tmp_list
1135
1136 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1137 r"""
George Keishing9348b402021-08-13 12:22:35 -05001138 Update ${MY_VAR} and plugin vars.
George Keishingb97a9042021-07-29 07:41:20 -05001139
1140 Description of argument(s):
George Keishing9348b402021-08-13 12:22:35 -05001141 yaml_arg_str arg string read from YAML.
George Keishingb97a9042021-07-29 07:41:20 -05001142
1143 Example:
1144 - cat ${MY_VAR}
1145 - ls -AX my_plugin_var
1146 """
George Keishing9348b402021-08-13 12:22:35 -05001147 # Parse the string for env vars ${env_vars}.
George Keishingb97a9042021-07-29 07:41:20 -05001148 try:
1149 # Example, list of matching env vars ['username', 'password', 'hostname']
1150 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
George Keishinge635ddc2022-12-08 07:38:02 -06001151 var_name_regex = '\\$\\{([^\\}]+)\\}'
George Keishingb97a9042021-07-29 07:41:20 -05001152 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1153 for var in env_var_names_list:
1154 env_var = os.environ[var]
George Keishinge635ddc2022-12-08 07:38:02 -06001155 env_replace = '${' + var + '}'
George Keishingb97a9042021-07-29 07:41:20 -05001156 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1157 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001158 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001159 pass
1160
1161 # Parse the string for plugin vars.
1162 try:
1163 # Example, list of plugin vars ['my_username', 'my_data']
1164 plugin_var_name_list = global_plugin_dict.keys()
1165 for var in plugin_var_name_list:
George Keishing9348b402021-08-13 12:22:35 -05001166 # skip env var list already populated above code block list.
George Keishing0581cb02021-08-05 15:08:58 -05001167 if var in env_var_names_list:
1168 continue
George Keishing9348b402021-08-13 12:22:35 -05001169 # If this plugin var exist but empty in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001170 # This is either a YAML plugin statement incorrectly used or
George Keishing9348b402021-08-13 12:22:35 -05001171 # user added a plugin var which is not going to be populated.
George Keishing0581cb02021-08-05 15:08:58 -05001172 if yaml_arg_str in global_plugin_dict:
1173 if isinstance(global_plugin_dict[var], (list, dict)):
1174 # List data type or dict can't be replaced, use directly
1175 # in eval function call.
1176 global_plugin_type_list.append(var)
1177 else:
George Keishinge635ddc2022-12-08 07:38:02 -06001178 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
George Keishing0581cb02021-08-05 15:08:58 -05001179 # Just a string like filename or command.
1180 else:
George Keishinge635ddc2022-12-08 07:38:02 -06001181 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
George Keishingb97a9042021-07-29 07:41:20 -05001182 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001183 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001184 pass
1185
1186 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001187
1188 def plugin_error_check(self, plugin_dict):
1189 r"""
1190 Plugin error dict processing.
1191
1192 Description of argument(s):
1193 plugin_dict Dictionary of plugin error.
1194 """
George Keishinge635ddc2022-12-08 07:38:02 -06001195 if any('plugin_error' in d for d in plugin_dict):
George Keishing1e7b0182021-08-06 14:05:54 -05001196 for d in plugin_dict:
George Keishinge635ddc2022-12-08 07:38:02 -06001197 if 'plugin_error' in d:
1198 value = d['plugin_error']
George Keishing1e7b0182021-08-06 14:05:54 -05001199 # Reference if the error is set or not by plugin.
1200 return plugin_error_dict[value]
George Keishingde79a9b2021-08-12 16:14:43 -05001201
1202 def key_index_list_dict(self, key, list_dict):
1203 r"""
1204 Iterate list of dictionary and return index if the key match is found.
1205
1206 Description of argument(s):
1207 key Valid Key in a dict.
1208 list_dict list of dictionary.
1209 """
1210 for i, d in enumerate(list_dict):
1211 if key in d.keys():
1212 return i
1213
1214 def plugin_expect_type(self, type, data):
1215 r"""
1216 Plugin expect directive type check.
1217 """
George Keishinge635ddc2022-12-08 07:38:02 -06001218 if type == 'int':
George Keishingde79a9b2021-08-12 16:14:43 -05001219 return isinstance(data, int)
George Keishinge635ddc2022-12-08 07:38:02 -06001220 elif type == 'float':
George Keishingde79a9b2021-08-12 16:14:43 -05001221 return isinstance(data, float)
George Keishinge635ddc2022-12-08 07:38:02 -06001222 elif type == 'str':
George Keishingde79a9b2021-08-12 16:14:43 -05001223 return isinstance(data, str)
George Keishinge635ddc2022-12-08 07:38:02 -06001224 elif type == 'list':
George Keishingde79a9b2021-08-12 16:14:43 -05001225 return isinstance(data, list)
George Keishinge635ddc2022-12-08 07:38:02 -06001226 elif type == 'dict':
George Keishingde79a9b2021-08-12 16:14:43 -05001227 return isinstance(data, dict)
George Keishinge635ddc2022-12-08 07:38:02 -06001228 elif type == 'tuple':
George Keishingde79a9b2021-08-12 16:14:43 -05001229 return isinstance(data, tuple)
1230 else:
1231 self.logger.info("\tInvalid data type requested: %s" % type)
George Keishinge635ddc2022-12-08 07:38:02 -06001232 return 'INVALID'