blob: b017efa1adbbd3264dfa53558a53f11bd8a729e8 [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
Patrick Williams20f38712022-12-08 06:18:26 -06007import json
8import logging
9import os
10import platform
11import re
12import subprocess
13import sys
14import time
George Keishing09679892022-12-08 08:21:52 -060015from errno import EACCES, EPERM
16
George Keishinge635ddc2022-12-08 07:38:02 -060017import yaml
Peter D Phan5e56f522021-12-20 13:19:41 -060018
Peter D Phancb791d72022-02-08 12:23:03 -060019script_dir = os.path.dirname(os.path.abspath(__file__))
20sys.path.append(script_dir)
21# Walk path and append to sys.path
22for root, dirs, files in os.walk(script_dir):
23 for dir in dirs:
24 sys.path.append(os.path.join(root, dir))
25
Patrick Williams20f38712022-12-08 06:18:26 -060026from ssh_utility import SSHRemoteclient # NOQA
27from telnet_utility import TelnetRemoteclient # NOQA
Peter D Phan72ce6b82021-06-03 06:18:26 -050028
George Keishingb97a9042021-07-29 07:41:20 -050029r"""
30User define plugins python functions.
31
32It will imports files from directory plugins
33
34plugins
35├── file1.py
36└── file2.py
37
38Example how to define in YAML:
39 - plugin:
40 - plugin_name: plugin.foo_func.foo_func_yaml
41 - plugin_args:
42 - arg1
43 - arg2
44"""
Patrick Williams20f38712022-12-08 06:18:26 -060045plugin_dir = __file__.split(__file__.split("/")[-1])[0] + "/plugins"
Peter D Phan5e56f522021-12-20 13:19:41 -060046sys.path.append(plugin_dir)
George Keishingb97a9042021-07-29 07:41:20 -050047try:
48 for module in os.listdir(plugin_dir):
Patrick Williams20f38712022-12-08 06:18:26 -060049 if module == "__init__.py" or module[-3:] != ".py":
George Keishingb97a9042021-07-29 07:41:20 -050050 continue
51 plugin_module = "plugins." + module[:-3]
52 # To access the module plugin.<module name>.<function>
53 # Example: plugin.foo_func.foo_func_yaml()
54 try:
55 plugin = __import__(plugin_module, globals(), locals(), [], 0)
56 except Exception as e:
George Keishing15352052025-04-24 18:55:47 +053057 print("PLUGIN: Exception: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -050058 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 Keishingc754b432025-04-24 14:27:14 +053096# Hold the plugin return named declared if function returned values are
97# list,dict.
George Keishing0581cb02021-08-05 15:08:58 -050098# Refer this name list to look up the plugin dict for eval() args function
George Keishing9348b402021-08-13 12:22:35 -050099# Example ['version']
George Keishing0581cb02021-08-05 15:08:58 -0500100global_plugin_type_list = []
George Keishing9348b402021-08-13 12:22:35 -0500101
102# Path where logs are to be stored or written.
Patrick Williams20f38712022-12-08 06:18:26 -0600103global_log_store_path = ""
George Keishingb97a9042021-07-29 07:41:20 -0500104
George Keishing1e7b0182021-08-06 14:05:54 -0500105# Plugin error state defaults.
106plugin_error_dict = {
Patrick Williams20f38712022-12-08 06:18:26 -0600107 "exit_on_error": False,
108 "continue_on_error": False,
George Keishing1e7b0182021-08-06 14:05:54 -0500109}
110
Peter D Phan72ce6b82021-06-03 06:18:26 -0500111
Peter D Phan5e56f522021-12-20 13:19:41 -0600112class ffdc_collector:
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
Patrick Williams20f38712022-12-08 06:18:26 -0600119 def __init__(
120 self,
121 hostname,
122 username,
123 password,
George Keishing7a61aa22023-06-26 13:18:37 +0530124 port_ssh,
George Keishinge8a41752023-06-22 21:42:47 +0530125 port_https,
126 port_ipmi,
Patrick Williams20f38712022-12-08 06:18:26 -0600127 ffdc_config,
128 location,
129 remote_type,
130 remote_protocol,
131 env_vars,
132 econfig,
133 log_level,
134 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500135 r"""
136 Description of argument(s):
137
George Keishingc754b432025-04-24 14:27:14 +0530138 hostname Name/ip of the targeted (remote) system
139 username User on the targeted system with access to
140 FFDC files
141 password Password for user on targeted system
George Keishing7a61aa22023-06-26 13:18:37 +0530142 port_ssh SSH port value. By default 22
George Keishinge8a41752023-06-22 21:42:47 +0530143 port_https HTTPS port value. By default 443
144 port_ipmi IPMI port value. By default 623
George Keishingc754b432025-04-24 14:27:14 +0530145 ffdc_config Configuration file listing commands and files
146 for FFDC
147 location Where to store collected FFDC
148 remote_type OS type of the remote host
George Keishing8e94f8c2021-07-23 15:06:32 -0500149 remote_protocol Protocol to use to collect data
150 env_vars User define CLI env vars '{"key : "value"}'
151 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -0500152
153 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500154
155 self.hostname = hostname
156 self.username = username
157 self.password = password
George Keishing7a61aa22023-06-26 13:18:37 +0530158 self.port_ssh = str(port_ssh)
George Keishinge8a41752023-06-22 21:42:47 +0530159 self.port_https = str(port_https)
160 self.port_ipmi = str(port_ipmi)
Peter D Phane86d9a52021-07-15 10:42:25 -0500161 self.ffdc_config = ffdc_config
162 self.location = location + "/" + remote_type.upper()
163 self.ssh_remoteclient = None
164 self.telnet_remoteclient = None
165 self.ffdc_dir_path = ""
166 self.ffdc_prefix = ""
167 self.target_type = remote_type.upper()
168 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -0500169 self.env_vars = env_vars
170 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -0500171 self.start_time = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600172 self.elapsed_time = ""
Peter D Phane86d9a52021-07-15 10:42:25 -0500173 self.logger = None
174
175 # Set prefix values for scp files and directory.
George Keishingc754b432025-04-24 14:27:14 +0530176 # Since the time stamp is at second granularity, these values are set
177 # here to be sure that all files for this run will have same timestamps
Peter D Phane86d9a52021-07-15 10:42:25 -0500178 # and they will be saved in the same directory.
179 # self.location == local system for now
Peter D Phan5e56f522021-12-20 13:19:41 -0600180 self.set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500181
Peter D Phan5e56f522021-12-20 13:19:41 -0600182 # Logger for this run. Need to be after set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500183 self.script_logging(getattr(logging, log_level.upper()))
184
185 # Verify top level directory exists for storage
186 self.validate_local_store(self.location)
187
Peter D Phan72ce6b82021-06-03 06:18:26 -0500188 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -0500189 # Load default or user define YAML configuration file.
Patrick Williams20f38712022-12-08 06:18:26 -0600190 with open(self.ffdc_config, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -0500191 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -0700192 self.ffdc_actions = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -0500193 except yaml.YAMLError as e:
194 self.logger.error(e)
195 sys.exit(-1)
Peter D Phane86d9a52021-07-15 10:42:25 -0500196
197 if self.target_type not in self.ffdc_actions.keys():
198 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600199 "\n\tERROR: %s is not listed in %s.\n\n"
200 % (self.target_type, self.ffdc_config)
201 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500202 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500203 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500204 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500205
George Keishing4885b2f2021-07-21 15:22:45 -0500206 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500207 self.logger.info("\n\tENV: User define input YAML variables")
208 self.env_dict = {}
Peter D Phan5e56f522021-12-20 13:19:41 -0600209 self.load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500210
Peter D Phan72ce6b82021-06-03 06:18:26 -0500211 def verify_script_env(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500212 # Import to log version
213 import click
214 import paramiko
215
216 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500217
George Keishingd805bc02025-02-28 12:17:13 +0530218 try:
219 redfishtool_version = (
220 self.run_tool_cmd("redfishtool -V").split(" ")[2].strip("\n")
221 )
222 except Exception as e:
223 self.logger.error("\tEXCEPTION redfishtool: %s", e)
224 redfishtool_version = "Not Installed (optional)"
225
226 try:
227 ipmitool_version = self.run_tool_cmd("ipmitool -V").split(" ")[2]
228 except Exception as e:
229 self.logger.error("\tEXCEPTION ipmitool: %s", e)
230 ipmitool_version = "Not Installed (optional)"
Peter D Phan0c669772021-06-24 13:52:42 -0500231
Peter D Phane86d9a52021-07-15 10:42:25 -0500232 self.logger.info("\n\t---- Script host environment ----")
Patrick Williams20f38712022-12-08 06:18:26 -0600233 self.logger.info(
234 "\t{:<10} {:<10}".format("Script hostname", os.uname()[1])
235 )
236 self.logger.info(
237 "\t{:<10} {:<10}".format("Script host os", platform.platform())
238 )
239 self.logger.info(
240 "\t{:<10} {:>10}".format("Python", platform.python_version())
241 )
242 self.logger.info("\t{:<10} {:>10}".format("PyYAML", yaml.__version__))
243 self.logger.info("\t{:<10} {:>10}".format("click", click.__version__))
244 self.logger.info(
245 "\t{:<10} {:>10}".format("paramiko", paramiko.__version__)
246 )
247 self.logger.info(
248 "\t{:<10} {:>9}".format("redfishtool", redfishtool_version)
249 )
250 self.logger.info(
251 "\t{:<10} {:>12}".format("ipmitool", ipmitool_version)
252 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500253
Patrick Williams20f38712022-12-08 06:18:26 -0600254 if eval(yaml.__version__.replace(".", ",")) < (5, 3, 0):
255 self.logger.error(
256 "\n\tERROR: Python or python packages do not meet minimum"
257 " version requirement."
258 )
259 self.logger.error(
260 "\tERROR: PyYAML version 5.3.0 or higher is needed.\n"
261 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500262 run_env_ok = False
263
Peter D Phane86d9a52021-07-15 10:42:25 -0500264 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500265 return run_env_ok
266
Patrick Williams20f38712022-12-08 06:18:26 -0600267 def script_logging(self, log_level_attr):
Peter D Phane86d9a52021-07-15 10:42:25 -0500268 r"""
269 Create logger
270
271 """
272 self.logger = logging.getLogger()
273 self.logger.setLevel(log_level_attr)
Patrick Williams20f38712022-12-08 06:18:26 -0600274 log_file_handler = logging.FileHandler(
275 self.ffdc_dir_path + "collector.log"
276 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500277
278 stdout_handler = logging.StreamHandler(sys.stdout)
279 self.logger.addHandler(log_file_handler)
280 self.logger.addHandler(stdout_handler)
281
282 # Turn off paramiko INFO logging
283 logging.getLogger("paramiko").setLevel(logging.WARNING)
284
Peter D Phan72ce6b82021-06-03 06:18:26 -0500285 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500286 r"""
287 Check if target system is ping-able.
288
289 """
George Keishing0662e942021-07-13 05:12:20 -0500290 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500291 if response == 0:
Patrick Williams20f38712022-12-08 06:18:26 -0600292 self.logger.info(
293 "\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname
294 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500295 return True
296 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500297 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600298 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n"
299 % self.hostname
300 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500301 sys.exit(-1)
302
Peter D Phan72ce6b82021-06-03 06:18:26 -0500303 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500304 r"""
305 Initiate FFDC Collection depending on requested protocol.
306
307 """
308
Patrick Williams20f38712022-12-08 06:18:26 -0600309 self.logger.info(
310 "\n\t---- Start communicating with %s ----" % self.hostname
311 )
Peter D Phan7610bc42021-07-06 06:31:05 -0500312 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500313
George Keishingf5a57502021-07-22 16:43:47 -0500314 # Find the list of target and protocol supported.
315 check_protocol_list = []
316 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500317
George Keishingf5a57502021-07-22 16:43:47 -0500318 for target_type in config_dict.keys():
319 if self.target_type != target_type:
320 continue
George Keishingeafba182021-06-29 13:44:58 -0500321
George Keishingf5a57502021-07-22 16:43:47 -0500322 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600323 if (
324 config_dict[target_type][k]["PROTOCOL"][0]
325 not in check_protocol_list
326 ):
327 check_protocol_list.append(
328 config_dict[target_type][k]["PROTOCOL"][0]
329 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500330
Patrick Williams20f38712022-12-08 06:18:26 -0600331 self.logger.info(
332 "\n\t %s protocol type: %s"
333 % (self.target_type, check_protocol_list)
334 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500335
George Keishingf5a57502021-07-22 16:43:47 -0500336 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500337
George Keishingf5a57502021-07-22 16:43:47 -0500338 if verified_working_protocol:
Patrick Williams20f38712022-12-08 06:18:26 -0600339 self.logger.info(
340 "\n\t---- Completed protocol pre-requisite check ----\n"
341 )
Peter D Phan0c669772021-06-24 13:52:42 -0500342
George Keishingf5a57502021-07-22 16:43:47 -0500343 # Verify top level directory exists for storage
344 self.validate_local_store(self.location)
345
Patrick Williams20f38712022-12-08 06:18:26 -0600346 if (self.remote_protocol not in verified_working_protocol) and (
347 self.remote_protocol != "ALL"
348 ):
349 self.logger.info(
350 "\n\tWorking protocol list: %s" % verified_working_protocol
351 )
George Keishingf5a57502021-07-22 16:43:47 -0500352 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600353 "\tERROR: Requested protocol %s is not in working protocol"
George Keishing7899a452023-02-15 02:46:54 -0600354 " list.\n" % self.remote_protocol
Patrick Williams20f38712022-12-08 06:18:26 -0600355 )
George Keishingf5a57502021-07-22 16:43:47 -0500356 sys.exit(-1)
357 else:
358 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500359
360 def ssh_to_target_system(self):
361 r"""
362 Open a ssh connection to targeted system.
363
364 """
365
Patrick Williams20f38712022-12-08 06:18:26 -0600366 self.ssh_remoteclient = SSHRemoteclient(
George Keishing7a61aa22023-06-26 13:18:37 +0530367 self.hostname, self.username, self.password, self.port_ssh
Patrick Williams20f38712022-12-08 06:18:26 -0600368 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500369
Peter D Phan5963d632021-07-12 09:58:55 -0500370 if self.ssh_remoteclient.ssh_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600371 self.logger.info(
372 "\n\t[Check] %s SSH connection established.\t [OK]"
373 % self.hostname
374 )
Peter D Phan733df632021-06-17 13:13:36 -0500375
Peter D Phan5963d632021-07-12 09:58:55 -0500376 # Check scp connection.
377 # If scp connection fails,
378 # continue with FFDC generation but skip scp files to local host.
379 self.ssh_remoteclient.scp_connection()
380 return True
381 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600382 self.logger.info(
383 "\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]"
384 % self.hostname
385 )
Peter D Phan5963d632021-07-12 09:58:55 -0500386 return False
387
388 def telnet_to_target_system(self):
389 r"""
390 Open a telnet connection to targeted system.
391 """
Patrick Williams20f38712022-12-08 06:18:26 -0600392 self.telnet_remoteclient = TelnetRemoteclient(
393 self.hostname, self.username, self.password
394 )
Peter D Phan5963d632021-07-12 09:58:55 -0500395 if self.telnet_remoteclient.tn_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600396 self.logger.info(
397 "\n\t[Check] %s Telnet connection established.\t [OK]"
398 % self.hostname
399 )
Peter D Phan5963d632021-07-12 09:58:55 -0500400 return True
401 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600402 self.logger.info(
403 "\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]"
404 % self.hostname
405 )
Peter D Phan5963d632021-07-12 09:58:55 -0500406 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500407
George Keishing772c9772021-06-16 23:23:42 -0500408 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500409 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500410 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500411
Peter D Phan04aca3b2021-06-21 10:37:18 -0500412 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530413 working_protocol_list List of confirmed working protocols to
414 connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500415 """
416
Patrick Williams20f38712022-12-08 06:18:26 -0600417 self.logger.info(
418 "\n\t---- Executing commands on " + self.hostname + " ----"
419 )
420 self.logger.info(
421 "\n\tWorking protocol list: %s" % working_protocol_list
422 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500423
George Keishingf5a57502021-07-22 16:43:47 -0500424 config_dict = self.ffdc_actions
425 for target_type in config_dict.keys():
426 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500427 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500428
Peter D Phane86d9a52021-07-15 10:42:25 -0500429 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
Patrick Williams20f38712022-12-08 06:18:26 -0600430 global_plugin_dict["global_log_store_path"] = self.ffdc_dir_path
George Keishingf5a57502021-07-22 16:43:47 -0500431 self.logger.info("\tSystem Type: %s" % target_type)
432 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600433 if (
434 self.remote_protocol not in working_protocol_list
435 and self.remote_protocol != "ALL"
436 ):
George Keishing6ea92b02021-07-01 11:20:50 -0500437 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500438
Patrick Williams20f38712022-12-08 06:18:26 -0600439 protocol = config_dict[target_type][k]["PROTOCOL"][0]
George Keishingf5a57502021-07-22 16:43:47 -0500440
441 if protocol not in working_protocol_list:
442 continue
443
George Keishingb7607612021-07-27 13:31:23 -0500444 if protocol in working_protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -0600445 if protocol == "SSH" or protocol == "SCP":
George Keishing12fd0652021-07-27 13:57:11 -0500446 self.protocol_ssh(protocol, target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600447 elif protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -0500448 self.protocol_telnet(target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600449 elif (
450 protocol == "REDFISH"
451 or protocol == "IPMI"
452 or protocol == "SHELL"
453 ):
George Keishing506b0582021-07-27 09:31:22 -0500454 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500455 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600456 self.logger.error(
457 "\n\tERROR: %s is not available for %s."
458 % (protocol, self.hostname)
459 )
George Keishingeafba182021-06-29 13:44:58 -0500460
Peter D Phan04aca3b2021-06-21 10:37:18 -0500461 # Close network connection after collecting all files
Patrick Williams20f38712022-12-08 06:18:26 -0600462 self.elapsed_time = time.strftime(
463 "%H:%M:%S", time.gmtime(time.time() - self.start_time)
464 )
George Keishing48972ba2025-05-05 17:40:29 +0530465 self.logger.info("\n\tTotal time taken: %s" % self.elapsed_time)
Peter D Phanbff617a2021-07-22 08:41:35 -0500466 if self.ssh_remoteclient:
467 self.ssh_remoteclient.ssh_remoteclient_disconnect()
468 if self.telnet_remoteclient:
469 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500470
Patrick Williams20f38712022-12-08 06:18:26 -0600471 def protocol_ssh(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500472 r"""
473 Perform actions using SSH and SCP protocols.
474
475 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500476 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500477 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500478 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500479 """
480
Patrick Williams20f38712022-12-08 06:18:26 -0600481 if protocol == "SCP":
George Keishingf5a57502021-07-22 16:43:47 -0500482 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500483 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600484 self.collect_and_copy_ffdc(
485 self.ffdc_actions[target_type][sub_type]
486 )
Peter D Phan0c669772021-06-24 13:52:42 -0500487
Patrick Williams20f38712022-12-08 06:18:26 -0600488 def protocol_telnet(self, target_type, sub_type):
Peter D Phan5963d632021-07-12 09:58:55 -0500489 r"""
490 Perform actions using telnet protocol.
491 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500492 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500493 """
Patrick Williams20f38712022-12-08 06:18:26 -0600494 self.logger.info(
495 "\n\t[Run] Executing commands on %s using %s"
496 % (self.hostname, "TELNET")
497 )
Peter D Phan5963d632021-07-12 09:58:55 -0500498 telnet_files_saved = []
499 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600500 list_of_commands = self.ffdc_actions[target_type][sub_type]["COMMANDS"]
Peter D Phan5963d632021-07-12 09:58:55 -0500501 for index, each_cmd in enumerate(list_of_commands, start=0):
502 command_txt, command_timeout = self.unpack_command(each_cmd)
Patrick Williams20f38712022-12-08 06:18:26 -0600503 result = self.telnet_remoteclient.execute_command(
504 command_txt, command_timeout
505 )
Peter D Phan5963d632021-07-12 09:58:55 -0500506 if result:
507 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600508 targ_file = self.ffdc_actions[target_type][sub_type][
509 "FILES"
510 ][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500511 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500512 targ_file = command_txt
513 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600514 "\n\t[WARN] Missing filename to store data from"
515 " telnet %s." % each_cmd
516 )
517 self.logger.warning(
518 "\t[WARN] Data will be stored in %s." % targ_file
519 )
520 targ_file_with_path = (
521 self.ffdc_dir_path + self.ffdc_prefix + targ_file
522 )
Peter D Phan5963d632021-07-12 09:58:55 -0500523 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600524 with open(targ_file_with_path, "w") as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500525 fp.write(result)
526 fp.close
527 telnet_files_saved.append(targ_file)
528 progress_counter += 1
529 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500530 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500531 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500532 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500533
Patrick Williams20f38712022-12-08 06:18:26 -0600534 def protocol_execute(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500535 r"""
George Keishing506b0582021-07-27 09:31:22 -0500536 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500537
538 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500539 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500540 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500541 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500542 """
543
Patrick Williams20f38712022-12-08 06:18:26 -0600544 self.logger.info(
545 "\n\t[Run] Executing commands to %s using %s"
546 % (self.hostname, protocol)
547 )
George Keishing506b0582021-07-27 09:31:22 -0500548 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500549 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600550 list_of_cmd = self.get_command_list(
551 self.ffdc_actions[target_type][sub_type]
552 )
George Keishingeafba182021-06-29 13:44:58 -0500553 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500554 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500555 if isinstance(each_cmd, dict):
Patrick Williams20f38712022-12-08 06:18:26 -0600556 if "plugin" in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500557 # If the error is set and plugin explicitly
558 # requested to skip execution on error..
Patrick Williams20f38712022-12-08 06:18:26 -0600559 if plugin_error_dict[
560 "exit_on_error"
561 ] and self.plugin_error_check(each_cmd["plugin"]):
562 self.logger.info(
563 "\n\t[PLUGIN-ERROR] exit_on_error: %s"
564 % plugin_error_dict["exit_on_error"]
565 )
566 self.logger.info(
567 "\t[PLUGIN-SKIP] %s" % each_cmd["plugin"][0]
568 )
George Keishing1e7b0182021-08-06 14:05:54 -0500569 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500570 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500571 # call the plugin
572 self.logger.info("\n\t[PLUGIN-START]")
Patrick Williams20f38712022-12-08 06:18:26 -0600573 result = self.execute_plugin_block(each_cmd["plugin"])
George Keishingb97a9042021-07-29 07:41:20 -0500574 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500575 else:
George Keishing2b83e042021-08-03 12:56:11 -0500576 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500577
George Keishingcaa97e62021-08-03 14:00:09 -0500578 if not plugin_call:
579 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500580 if result:
581 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600582 file_name = self.get_file_list(
583 self.ffdc_actions[target_type][sub_type]
584 )[index]
George Keishingb97a9042021-07-29 07:41:20 -0500585 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500586 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500587 continue
Patrick Williams20f38712022-12-08 06:18:26 -0600588 targ_file = self.yaml_env_and_plugin_vars_populate(
589 file_name
590 )
George Keishingeafba182021-06-29 13:44:58 -0500591 except IndexError:
Patrick Williams20f38712022-12-08 06:18:26 -0600592 targ_file = each_cmd.split("/")[-1]
George Keishing506b0582021-07-27 09:31:22 -0500593 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600594 "\n\t[WARN] Missing filename to store data from %s."
595 % each_cmd
596 )
597 self.logger.warning(
598 "\t[WARN] Data will be stored in %s." % targ_file
599 )
George Keishingeafba182021-06-29 13:44:58 -0500600
Patrick Williams20f38712022-12-08 06:18:26 -0600601 targ_file_with_path = (
602 self.ffdc_dir_path + self.ffdc_prefix + targ_file
603 )
George Keishingeafba182021-06-29 13:44:58 -0500604
605 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600606 with open(targ_file_with_path, "w") as fp:
George Keishing91308ea2021-08-10 14:43:15 -0500607 if isinstance(result, dict):
608 fp.write(json.dumps(result))
609 else:
610 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500611 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500612 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500613
614 progress_counter += 1
615 self.print_progress(progress_counter)
616
Peter D Phane86d9a52021-07-15 10:42:25 -0500617 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500618
George Keishing506b0582021-07-27 09:31:22 -0500619 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500620 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500621
Patrick Williams20f38712022-12-08 06:18:26 -0600622 def collect_and_copy_ffdc(
623 self, ffdc_actions_for_target_type, form_filename=False
624 ):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500625 r"""
626 Send commands in ffdc_config file to targeted system.
627
628 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530629 ffdc_actions_for_target_type Commands and files for the selected
630 remote host type.
631 form_filename If true, pre-pend self.target_type to
632 filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500633 """
634
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500635 # Executing commands, if any
Patrick Williams20f38712022-12-08 06:18:26 -0600636 self.ssh_execute_ffdc_commands(
637 ffdc_actions_for_target_type, form_filename
638 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500639
Peter D Phan3beb02e2021-07-06 13:25:17 -0500640 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500641 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600642 self.logger.info(
643 "\n\n\tCopying FFDC files from remote system %s.\n"
644 % self.hostname
645 )
Peter D Phan2b8052d2021-06-22 10:55:41 -0500646
Peter D Phan04aca3b2021-06-21 10:37:18 -0500647 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500648 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Patrick Williams20f38712022-12-08 06:18:26 -0600649 self.scp_ffdc(
650 self.ffdc_dir_path,
651 self.ffdc_prefix,
652 form_filename,
653 list_of_files,
654 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500655 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600656 self.logger.info(
657 "\n\n\tSkip copying FFDC files from remote system %s.\n"
658 % self.hostname
659 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500660
Patrick Williams20f38712022-12-08 06:18:26 -0600661 def get_command_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500662 r"""
663 Fetch list of commands from configuration file
664
665 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530666 ffdc_actions_for_target_type Commands and files for the selected
667 remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500668 """
669 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600670 list_of_commands = ffdc_actions_for_target_type["COMMANDS"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500671 except KeyError:
672 list_of_commands = []
673 return list_of_commands
674
Patrick Williams20f38712022-12-08 06:18:26 -0600675 def get_file_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500676 r"""
677 Fetch list of commands from configuration file
678
679 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530680 ffdc_actions_for_target_type Commands and files for the selected
681 remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500682 """
683 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600684 list_of_files = ffdc_actions_for_target_type["FILES"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500685 except KeyError:
686 list_of_files = []
687 return list_of_files
688
Patrick Williams20f38712022-12-08 06:18:26 -0600689 def unpack_command(self, command):
Peter D Phan5963d632021-07-12 09:58:55 -0500690 r"""
691 Unpack command from config file
692
693 Description of argument(s):
694 command Command from config file.
695 """
696 if isinstance(command, dict):
697 command_txt = next(iter(command))
698 command_timeout = next(iter(command.values()))
699 elif isinstance(command, str):
700 command_txt = command
701 # Default command timeout 60 seconds
702 command_timeout = 60
703
704 return command_txt, command_timeout
705
Patrick Williams20f38712022-12-08 06:18:26 -0600706 def ssh_execute_ffdc_commands(
707 self, ffdc_actions_for_target_type, form_filename=False
708 ):
Peter D Phan3beb02e2021-07-06 13:25:17 -0500709 r"""
710 Send commands in ffdc_config file to targeted system.
711
712 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530713 ffdc_actions_for_target_type Commands and files for the selected
714 remote host type.
715 form_filename If true, pre-pend self.target_type to
716 filename
Peter D Phan3beb02e2021-07-06 13:25:17 -0500717 """
Patrick Williams20f38712022-12-08 06:18:26 -0600718 self.logger.info(
719 "\n\t[Run] Executing commands on %s using %s"
720 % (self.hostname, ffdc_actions_for_target_type["PROTOCOL"][0])
721 )
Peter D Phan3beb02e2021-07-06 13:25:17 -0500722
George Keishingf5a57502021-07-22 16:43:47 -0500723 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500724 # If command list is empty, returns
725 if not list_of_commands:
726 return
727
728 progress_counter = 0
729 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500730 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500731
732 if form_filename:
733 command_txt = str(command_txt % self.target_type)
734
Patrick Williams20f38712022-12-08 06:18:26 -0600735 (
736 cmd_exit_code,
737 err,
738 response,
739 ) = self.ssh_remoteclient.execute_command(
740 command_txt, command_timeout
741 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500742
743 if cmd_exit_code:
744 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600745 "\n\t\t[WARN] %s exits with code %s."
746 % (command_txt, str(cmd_exit_code))
747 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500748 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500749
Peter D Phan3beb02e2021-07-06 13:25:17 -0500750 progress_counter += 1
751 self.print_progress(progress_counter)
752
Peter D Phane86d9a52021-07-15 10:42:25 -0500753 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500754
Patrick Williams20f38712022-12-08 06:18:26 -0600755 def group_copy(self, ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500756 r"""
757 scp group of files (wild card) from remote host.
758
759 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530760 fdc_actions_for_target_type Commands and files for the selected
761 remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500762 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500763
Peter D Phan5963d632021-07-12 09:58:55 -0500764 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600765 self.logger.info(
766 "\n\tCopying files from remote system %s via SCP.\n"
767 % self.hostname
768 )
Peter D Phan56429a62021-06-23 08:38:29 -0500769
Patrick Williams20f38712022-12-08 06:18:26 -0600770 list_of_commands = self.get_command_list(
771 ffdc_actions_for_target_type
772 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500773 # If command list is empty, returns
774 if not list_of_commands:
775 return
Peter D Phan56429a62021-06-23 08:38:29 -0500776
Peter D Phanbabf2962021-07-07 11:24:40 -0500777 for command in list_of_commands:
778 try:
George Keishingb4540e72021-08-02 13:48:46 -0500779 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500780 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500781 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500782 continue
783
Patrick Williams20f38712022-12-08 06:18:26 -0600784 (
785 cmd_exit_code,
786 err,
787 response,
788 ) = self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500789
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500790 # If file does not exist, code take no action.
791 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500792 if response:
Patrick Williams20f38712022-12-08 06:18:26 -0600793 scp_result = self.ssh_remoteclient.scp_file_from_remote(
794 response.split("\n"), self.ffdc_dir_path
795 )
Peter D Phan56429a62021-06-23 08:38:29 -0500796 if scp_result:
Patrick Williams20f38712022-12-08 06:18:26 -0600797 self.logger.info(
798 "\t\tSuccessfully copied from "
799 + self.hostname
800 + ":"
801 + command
802 )
Peter D Phan56429a62021-06-23 08:38:29 -0500803 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500804 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500805
806 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600807 self.logger.info(
808 "\n\n\tSkip copying files from remote system %s.\n"
809 % self.hostname
810 )
Peter D Phan56429a62021-06-23 08:38:29 -0500811
Patrick Williams20f38712022-12-08 06:18:26 -0600812 def scp_ffdc(
813 self,
814 targ_dir_path,
815 targ_file_prefix,
816 form_filename,
817 file_list=None,
818 quiet=None,
819 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500820 r"""
George Keishingc754b432025-04-24 14:27:14 +0530821 SCP all files in file_dict to the indicated directory on the local
822 system.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500823
824 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530825 targ_dir_path The path of the directory to receive
826 the files.
George Keishinge16f1582022-12-15 07:32:21 -0600827 targ_file_prefix Prefix which will be prepended to each
Peter D Phan72ce6b82021-06-03 06:18:26 -0500828 target file's name.
George Keishingc754b432025-04-24 14:27:14 +0530829 file_dict A dictionary of files to scp from
830 targeted system to this system
Peter D Phan72ce6b82021-06-03 06:18:26 -0500831
832 """
833
Peter D Phan72ce6b82021-06-03 06:18:26 -0500834 progress_counter = 0
835 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500836 if form_filename:
837 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500838 source_file_path = filename
Patrick Williams20f38712022-12-08 06:18:26 -0600839 targ_file_path = (
840 targ_dir_path + targ_file_prefix + filename.split("/")[-1]
841 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500842
Peter D Phanbabf2962021-07-07 11:24:40 -0500843 # If source file name contains wild card, copy filename as is.
Patrick Williams20f38712022-12-08 06:18:26 -0600844 if "*" in source_file_path:
845 scp_result = self.ssh_remoteclient.scp_file_from_remote(
846 source_file_path, self.ffdc_dir_path
847 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500848 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600849 scp_result = self.ssh_remoteclient.scp_file_from_remote(
850 source_file_path, targ_file_path
851 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500852
853 if not quiet:
854 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500855 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600856 "\t\tSuccessfully copied from "
857 + self.hostname
858 + ":"
859 + source_file_path
860 + ".\n"
861 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500862 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500863 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600864 "\t\tFail to copy from "
865 + self.hostname
866 + ":"
867 + source_file_path
868 + ".\n"
869 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500870 else:
871 progress_counter += 1
872 self.print_progress(progress_counter)
873
Peter D Phan5e56f522021-12-20 13:19:41 -0600874 def set_ffdc_default_store_path(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500875 r"""
876 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
George Keishingc754b432025-04-24 14:27:14 +0530877 Collected ffdc file will be stored in dir
878 /self.location/hostname_timestr/.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500879 Individual ffdc file will have timestr_filename.
880
881 Description of class variables:
George Keishingc754b432025-04-24 14:27:14 +0530882 self.ffdc_dir_path The dir path where collected ffdc data files
883 should be put.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500884
885 self.ffdc_prefix The prefix to be given to each ffdc file name.
886
887 """
888
889 timestr = time.strftime("%Y%m%d-%H%M%S")
Patrick Williams20f38712022-12-08 06:18:26 -0600890 self.ffdc_dir_path = (
891 self.location + "/" + self.hostname + "_" + timestr + "/"
892 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500893 self.ffdc_prefix = timestr + "_"
894 self.validate_local_store(self.ffdc_dir_path)
895
Peter D Phan5e56f522021-12-20 13:19:41 -0600896 # Need to verify local store path exists prior to instantiate this class.
897 # This class method is used to share the same code between CLI input parm
898 # and Robot Framework "${EXECDIR}/logs" before referencing this class.
899 @classmethod
900 def validate_local_store(cls, dir_path):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500901 r"""
902 Ensure path exists to store FFDC files locally.
903
904 Description of variable:
905 dir_path The dir path where collected ffdc data files will be stored.
906
907 """
908
909 if not os.path.exists(dir_path):
910 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500911 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500912 except (IOError, OSError) as e:
913 # PermissionError
914 if e.errno == EPERM or e.errno == EACCES:
George Keishing15352052025-04-24 18:55:47 +0530915 print(
Patrick Williams20f38712022-12-08 06:18:26 -0600916 "\tERROR: os.makedirs %s failed with"
917 " PermissionError.\n" % dir_path
918 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500919 else:
George Keishing15352052025-04-24 18:55:47 +0530920 print(
Patrick Williams20f38712022-12-08 06:18:26 -0600921 "\tERROR: os.makedirs %s failed with %s.\n"
922 % (dir_path, e.strerror)
923 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500924 sys.exit(-1)
925
926 def print_progress(self, progress):
927 r"""
928 Print activity progress +
929
930 Description of variable:
931 progress Progress counter.
932
933 """
934
935 sys.stdout.write("\r\t" + "+" * progress)
936 sys.stdout.flush()
Patrick Williams20f38712022-12-08 06:18:26 -0600937 time.sleep(0.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500938
939 def verify_redfish(self):
940 r"""
941 Verify remote host has redfish service active
942
943 """
Patrick Williams20f38712022-12-08 06:18:26 -0600944 redfish_parm = (
945 "redfishtool -r "
946 + self.hostname
George Keishing7a61aa22023-06-26 13:18:37 +0530947 + ":"
948 + self.port_https
Patrick Williams20f38712022-12-08 06:18:26 -0600949 + " -S Always raw GET /redfish/v1/"
950 )
951 return self.run_tool_cmd(redfish_parm, True)
Peter D Phan0c669772021-06-24 13:52:42 -0500952
George Keishingeafba182021-06-29 13:44:58 -0500953 def verify_ipmi(self):
954 r"""
955 Verify remote host has IPMI LAN service active
956
957 """
Patrick Williams20f38712022-12-08 06:18:26 -0600958 if self.target_type == "OPENBMC":
959 ipmi_parm = (
960 "ipmitool -I lanplus -C 17 -U "
961 + self.username
962 + " -P "
963 + self.password
964 + " -H "
965 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530966 + " -p "
967 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600968 + " power status"
969 )
George Keishing484f8242021-07-27 01:42:02 -0500970 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600971 ipmi_parm = (
972 "ipmitool -I lanplus -P "
973 + self.password
974 + " -H "
975 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530976 + " -p "
977 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600978 + " power status"
979 )
George Keishing484f8242021-07-27 01:42:02 -0500980
Patrick Williams20f38712022-12-08 06:18:26 -0600981 return self.run_tool_cmd(ipmi_parm, True)
George Keishingeafba182021-06-29 13:44:58 -0500982
Patrick Williams20f38712022-12-08 06:18:26 -0600983 def run_tool_cmd(self, parms_string, quiet=False):
George Keishingeafba182021-06-29 13:44:58 -0500984 r"""
George Keishing506b0582021-07-27 09:31:22 -0500985 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500986
987 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500988 parms_string tool command options.
989 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500990 """
991
Patrick Williams20f38712022-12-08 06:18:26 -0600992 result = subprocess.run(
993 [parms_string],
994 stdout=subprocess.PIPE,
995 stderr=subprocess.PIPE,
996 shell=True,
997 universal_newlines=True,
998 )
George Keishingeafba182021-06-29 13:44:58 -0500999
1000 if result.stderr and not quiet:
Patrick Williams20f38712022-12-08 06:18:26 -06001001 self.logger.error("\n\t\tERROR with %s " % parms_string)
1002 self.logger.error("\t\t" + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -05001003
1004 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -05001005
George Keishingf5a57502021-07-22 16:43:47 -05001006 def verify_protocol(self, protocol_list):
1007 r"""
1008 Perform protocol working check.
1009
1010 Description of argument(s):
1011 protocol_list List of protocol.
1012 """
1013
1014 tmp_list = []
1015 if self.target_is_pingable():
1016 tmp_list.append("SHELL")
1017
1018 for protocol in protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -06001019 if self.remote_protocol != "ALL":
George Keishingf5a57502021-07-22 16:43:47 -05001020 if self.remote_protocol != protocol:
1021 continue
1022
1023 # Only check SSH/SCP once for both protocols
Patrick Williams20f38712022-12-08 06:18:26 -06001024 if (
1025 protocol == "SSH"
1026 or protocol == "SCP"
1027 and protocol not in tmp_list
1028 ):
George Keishingf5a57502021-07-22 16:43:47 -05001029 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -05001030 # Add only what user asked.
Patrick Williams20f38712022-12-08 06:18:26 -06001031 if self.remote_protocol != "ALL":
George Keishingaa638702021-07-26 11:48:28 -05001032 tmp_list.append(self.remote_protocol)
1033 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001034 tmp_list.append("SSH")
1035 tmp_list.append("SCP")
George Keishingf5a57502021-07-22 16:43:47 -05001036
Patrick Williams20f38712022-12-08 06:18:26 -06001037 if protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -05001038 if self.telnet_to_target_system():
1039 tmp_list.append(protocol)
1040
Patrick Williams20f38712022-12-08 06:18:26 -06001041 if protocol == "REDFISH":
George Keishingf5a57502021-07-22 16:43:47 -05001042 if self.verify_redfish():
1043 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001044 self.logger.info(
1045 "\n\t[Check] %s Redfish Service.\t\t [OK]"
1046 % self.hostname
1047 )
George Keishingf5a57502021-07-22 16:43:47 -05001048 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001049 self.logger.info(
1050 "\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]"
1051 % self.hostname
1052 )
George Keishingf5a57502021-07-22 16:43:47 -05001053
Patrick Williams20f38712022-12-08 06:18:26 -06001054 if protocol == "IPMI":
George Keishingf5a57502021-07-22 16:43:47 -05001055 if self.verify_ipmi():
1056 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001057 self.logger.info(
1058 "\n\t[Check] %s IPMI LAN Service.\t\t [OK]"
1059 % self.hostname
1060 )
George Keishingf5a57502021-07-22 16:43:47 -05001061 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001062 self.logger.info(
1063 "\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]"
1064 % self.hostname
1065 )
George Keishingf5a57502021-07-22 16:43:47 -05001066
1067 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -05001068
1069 def load_env(self):
1070 r"""
1071 Perform protocol working check.
1072
1073 """
George Keishingc754b432025-04-24 14:27:14 +05301074 # This is for the env vars a user can use in YAML to load
1075 # it at runtime.
George Keishinge1686752021-07-27 12:55:28 -05001076 # Example YAML:
1077 # -COMMANDS:
1078 # - my_command ${hostname} ${username} ${password}
Patrick Williams20f38712022-12-08 06:18:26 -06001079 os.environ["hostname"] = self.hostname
1080 os.environ["username"] = self.username
1081 os.environ["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301082 os.environ["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301083 os.environ["port_https"] = self.port_https
1084 os.environ["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001085
1086 # Append default Env.
Patrick Williams20f38712022-12-08 06:18:26 -06001087 self.env_dict["hostname"] = self.hostname
1088 self.env_dict["username"] = self.username
1089 self.env_dict["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301090 self.env_dict["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301091 self.env_dict["port_https"] = self.port_https
1092 self.env_dict["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001093
1094 try:
1095 tmp_env_dict = {}
1096 if self.env_vars:
1097 tmp_env_dict = json.loads(self.env_vars)
1098 # Export ENV vars default.
1099 for key, value in tmp_env_dict.items():
1100 os.environ[key] = value
1101 self.env_dict[key] = str(value)
1102
1103 if self.econfig:
Patrick Williams20f38712022-12-08 06:18:26 -06001104 with open(self.econfig, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -05001105 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -07001106 tmp_env_dict = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -05001107 except yaml.YAMLError as e:
1108 self.logger.error(e)
1109 sys.exit(-1)
George Keishinge1686752021-07-27 12:55:28 -05001110 # Export ENV vars.
Patrick Williams20f38712022-12-08 06:18:26 -06001111 for key, value in tmp_env_dict["env_params"].items():
George Keishinge1686752021-07-27 12:55:28 -05001112 os.environ[key] = str(value)
1113 self.env_dict[key] = str(value)
1114 except json.decoder.JSONDecodeError as e:
1115 self.logger.error("\n\tERROR: %s " % e)
1116 sys.exit(-1)
1117
1118 # This to mask the password from displaying on the console.
1119 mask_dict = self.env_dict.copy()
1120 for k, v in mask_dict.items():
1121 if k.lower().find("password") != -1:
1122 hidden_text = []
1123 hidden_text.append(v)
Patrick Williams20f38712022-12-08 06:18:26 -06001124 password_regex = (
1125 "(" + "|".join([re.escape(x) for x in hidden_text]) + ")"
1126 )
George Keishinge1686752021-07-27 12:55:28 -05001127 mask_dict[k] = re.sub(password_regex, "********", v)
1128
1129 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -05001130
1131 def execute_python_eval(self, eval_string):
1132 r"""
George Keishing9348b402021-08-13 12:22:35 -05001133 Execute qualified python function string using eval.
George Keishingb97a9042021-07-29 07:41:20 -05001134
1135 Description of argument(s):
1136 eval_string Execute the python object.
1137
1138 Example:
1139 eval(plugin.foo_func.foo_func(10))
1140 """
1141 try:
George Keishingdda48ce2021-08-12 07:02:27 -05001142 self.logger.info("\tExecuting plugin func()")
1143 self.logger.debug("\tCall func: %s" % eval_string)
George Keishingb97a9042021-07-29 07:41:20 -05001144 result = eval(eval_string)
1145 self.logger.info("\treturn: %s" % str(result))
Patrick Williams20f38712022-12-08 06:18:26 -06001146 except (
1147 ValueError,
1148 SyntaxError,
1149 NameError,
1150 AttributeError,
1151 TypeError,
1152 ) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001153 self.logger.error("\tERROR: execute_python_eval: %s" % e)
1154 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001155 plugin_error_dict["exit_on_error"] = True
George Keishing73b95d12021-08-13 14:30:52 -05001156 self.logger.info("\treturn: PLUGIN_EVAL_ERROR")
Patrick Williams20f38712022-12-08 06:18:26 -06001157 return "PLUGIN_EVAL_ERROR"
George Keishingb97a9042021-07-29 07:41:20 -05001158
1159 return result
1160
1161 def execute_plugin_block(self, plugin_cmd_list):
1162 r"""
Peter D Phan5e56f522021-12-20 13:19:41 -06001163 Pack the plugin command to qualifed python string object.
George Keishingb97a9042021-07-29 07:41:20 -05001164
1165 Description of argument(s):
1166 plugin_list_dict Plugin block read from YAML
1167 [{'plugin_name': 'plugin.foo_func.my_func'},
1168 {'plugin_args': [10]}]
1169
1170 Example:
1171 - plugin:
1172 - plugin_name: plugin.foo_func.my_func
1173 - plugin_args:
1174 - arg1
1175 - arg2
1176
1177 - plugin:
1178 - plugin_name: result = plugin.foo_func.my_func
1179 - plugin_args:
1180 - arg1
1181 - arg2
1182
1183 - plugin:
1184 - plugin_name: result1,result2 = plugin.foo_func.my_func
1185 - plugin_args:
1186 - arg1
1187 - arg2
1188 """
1189 try:
Patrick Williams20f38712022-12-08 06:18:26 -06001190 idx = self.key_index_list_dict("plugin_name", plugin_cmd_list)
1191 plugin_name = plugin_cmd_list[idx]["plugin_name"]
George Keishingb97a9042021-07-29 07:41:20 -05001192 # Equal separator means plugin function returns result.
Patrick Williams20f38712022-12-08 06:18:26 -06001193 if " = " in plugin_name:
George Keishingb97a9042021-07-29 07:41:20 -05001194 # Ex. ['result', 'plugin.foo_func.my_func']
Patrick Williams20f38712022-12-08 06:18:26 -06001195 plugin_name_args = plugin_name.split(" = ")
George Keishingb97a9042021-07-29 07:41:20 -05001196 # plugin func return data.
1197 for arg in plugin_name_args:
1198 if arg == plugin_name_args[-1]:
1199 plugin_name = arg
1200 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001201 plugin_resp = arg.split(",")
George Keishingb97a9042021-07-29 07:41:20 -05001202 # ['result1','result2']
1203 for x in plugin_resp:
1204 global_plugin_list.append(x)
1205 global_plugin_dict[x] = ""
1206
1207 # Walk the plugin args ['arg1,'arg2']
1208 # If the YAML plugin statement 'plugin_args' is not declared.
Patrick Williams20f38712022-12-08 06:18:26 -06001209 if any("plugin_args" in d for d in plugin_cmd_list):
1210 idx = self.key_index_list_dict("plugin_args", plugin_cmd_list)
1211 plugin_args = plugin_cmd_list[idx]["plugin_args"]
George Keishingb97a9042021-07-29 07:41:20 -05001212 if plugin_args:
1213 plugin_args = self.yaml_args_populate(plugin_args)
1214 else:
1215 plugin_args = []
1216 else:
1217 plugin_args = self.yaml_args_populate([])
1218
1219 # Pack the args arg1, arg2, .... argn into
1220 # "arg1","arg2","argn" string as params for function.
1221 parm_args_str = self.yaml_args_string(plugin_args)
1222 if parm_args_str:
Patrick Williams20f38712022-12-08 06:18:26 -06001223 plugin_func = plugin_name + "(" + parm_args_str + ")"
George Keishingb97a9042021-07-29 07:41:20 -05001224 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001225 plugin_func = plugin_name + "()"
George Keishingb97a9042021-07-29 07:41:20 -05001226
1227 # Execute plugin function.
1228 if global_plugin_dict:
1229 resp = self.execute_python_eval(plugin_func)
George Keishing9348b402021-08-13 12:22:35 -05001230 # Update plugin vars dict if there is any.
Patrick Williams20f38712022-12-08 06:18:26 -06001231 if resp != "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001232 self.response_args_data(resp)
George Keishingb97a9042021-07-29 07:41:20 -05001233 else:
George Keishingcaa97e62021-08-03 14:00:09 -05001234 resp = self.execute_python_eval(plugin_func)
George Keishingb97a9042021-07-29 07:41:20 -05001235 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001236 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001237 plugin_error_dict["exit_on_error"] = True
George Keishing1e7b0182021-08-06 14:05:54 -05001238 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001239 pass
1240
George Keishing73b95d12021-08-13 14:30:52 -05001241 # There is a real error executing the plugin function.
Patrick Williams20f38712022-12-08 06:18:26 -06001242 if resp == "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001243 return resp
1244
George Keishingde79a9b2021-08-12 16:14:43 -05001245 # Check if plugin_expects_return (int, string, list,dict etc)
Patrick Williams20f38712022-12-08 06:18:26 -06001246 if any("plugin_expects_return" in d for d in plugin_cmd_list):
1247 idx = self.key_index_list_dict(
1248 "plugin_expects_return", plugin_cmd_list
1249 )
1250 plugin_expects = plugin_cmd_list[idx]["plugin_expects_return"]
George Keishingde79a9b2021-08-12 16:14:43 -05001251 if plugin_expects:
1252 if resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001253 if (
1254 self.plugin_expect_type(plugin_expects, resp)
1255 == "INVALID"
1256 ):
George Keishingde79a9b2021-08-12 16:14:43 -05001257 self.logger.error("\tWARN: Plugin error check skipped")
1258 elif not self.plugin_expect_type(plugin_expects, resp):
Patrick Williams20f38712022-12-08 06:18:26 -06001259 self.logger.error(
1260 "\tERROR: Plugin expects return data: %s"
1261 % plugin_expects
1262 )
1263 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001264 elif not resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001265 self.logger.error(
1266 "\tERROR: Plugin func failed to return data"
1267 )
1268 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001269
1270 return resp
1271
George Keishingb97a9042021-07-29 07:41:20 -05001272 def response_args_data(self, plugin_resp):
1273 r"""
George Keishing9348b402021-08-13 12:22:35 -05001274 Parse the plugin function response and update plugin return variable.
George Keishingb97a9042021-07-29 07:41:20 -05001275
1276 plugin_resp Response data from plugin function.
1277 """
1278 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -05001279 resp_data = ""
George Keishing9348b402021-08-13 12:22:35 -05001280
George Keishingb97a9042021-07-29 07:41:20 -05001281 # There is nothing to update the plugin response.
Patrick Williams20f38712022-12-08 06:18:26 -06001282 if len(global_plugin_list) == 0 or plugin_resp == "None":
George Keishingb97a9042021-07-29 07:41:20 -05001283 return
1284
George Keishing5765f792021-08-02 13:08:53 -05001285 if isinstance(plugin_resp, str):
Patrick Williams20f38712022-12-08 06:18:26 -06001286 resp_data = plugin_resp.strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001287 resp_list.append(resp_data)
1288 elif isinstance(plugin_resp, bytes):
Patrick Williams20f38712022-12-08 06:18:26 -06001289 resp_data = str(plugin_resp, "UTF-8").strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001290 resp_list.append(resp_data)
1291 elif isinstance(plugin_resp, tuple):
1292 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -05001293 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -05001294 else:
1295 resp_list = list(plugin_resp)
Patrick Williams20f38712022-12-08 06:18:26 -06001296 resp_list = [x.strip("\r\n\t") for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -05001297 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -05001298 if len(global_plugin_list) == 1:
Patrick Williams20f38712022-12-08 06:18:26 -06001299 resp_list.append([x.strip("\r\n\t") for x in plugin_resp])
George Keishing5765f792021-08-02 13:08:53 -05001300 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001301 resp_list = [x.strip("\r\n\t") for x in plugin_resp]
George Keishing5765f792021-08-02 13:08:53 -05001302 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1303 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001304
George Keishing9348b402021-08-13 12:22:35 -05001305 # Iterate if there is a list of plugin return vars to update.
George Keishingb97a9042021-07-29 07:41:20 -05001306 for idx, item in enumerate(resp_list, start=0):
George Keishing9348b402021-08-13 12:22:35 -05001307 # Exit loop, done required loop.
George Keishingb97a9042021-07-29 07:41:20 -05001308 if idx >= len(global_plugin_list):
1309 break
1310 # Find the index of the return func in the list and
1311 # update the global func return dictionary.
1312 try:
1313 dict_idx = global_plugin_list[idx]
1314 global_plugin_dict[dict_idx] = item
1315 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001316 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001317 pass
1318
1319 # Done updating plugin dict irrespective of pass or failed,
George Keishing9348b402021-08-13 12:22:35 -05001320 # clear all the list element for next plugin block execute.
George Keishingb97a9042021-07-29 07:41:20 -05001321 global_plugin_list.clear()
1322
1323 def yaml_args_string(self, plugin_args):
1324 r"""
1325 Pack the args into string.
1326
1327 plugin_args arg list ['arg1','arg2,'argn']
1328 """
Patrick Williams20f38712022-12-08 06:18:26 -06001329 args_str = ""
George Keishingb97a9042021-07-29 07:41:20 -05001330 for args in plugin_args:
1331 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001332 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001333 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001334 elif args in global_plugin_type_list:
1335 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001336 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001337 args_str += '"' + str(args.strip("\r\n\t")) + '"'
George Keishingb97a9042021-07-29 07:41:20 -05001338 # Skip last list element.
1339 if args != plugin_args[-1]:
1340 args_str += ","
1341 return args_str
1342
1343 def yaml_args_populate(self, yaml_arg_list):
1344 r"""
George Keishing9348b402021-08-13 12:22:35 -05001345 Decode env and plugin vars and populate.
George Keishingb97a9042021-07-29 07:41:20 -05001346
1347 Description of argument(s):
1348 yaml_arg_list arg list read from YAML
1349
1350 Example:
1351 - plugin_args:
1352 - arg1
1353 - arg2
1354
1355 yaml_arg_list: [arg2, arg2]
1356 """
1357 # Get the env loaded keys as list ['hostname', 'username', 'password'].
George Keishingb97a9042021-07-29 07:41:20 -05001358
1359 if isinstance(yaml_arg_list, list):
1360 tmp_list = []
1361 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001362 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001363 tmp_list.append(arg)
1364 continue
1365 elif isinstance(arg, str):
1366 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1367 tmp_list.append(arg_str)
1368 else:
1369 tmp_list.append(arg)
1370
1371 # return populated list.
1372 return tmp_list
1373
1374 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1375 r"""
George Keishing9348b402021-08-13 12:22:35 -05001376 Update ${MY_VAR} and plugin vars.
George Keishingb97a9042021-07-29 07:41:20 -05001377
1378 Description of argument(s):
George Keishing9348b402021-08-13 12:22:35 -05001379 yaml_arg_str arg string read from YAML.
George Keishingb97a9042021-07-29 07:41:20 -05001380
1381 Example:
1382 - cat ${MY_VAR}
1383 - ls -AX my_plugin_var
1384 """
George Keishing9348b402021-08-13 12:22:35 -05001385 # Parse the string for env vars ${env_vars}.
George Keishingb97a9042021-07-29 07:41:20 -05001386 try:
George Keishingc754b432025-04-24 14:27:14 +05301387 # Example, list of matching
1388 # env vars ['username', 'password', 'hostname']
George Keishingb97a9042021-07-29 07:41:20 -05001389 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
Patrick Williams20f38712022-12-08 06:18:26 -06001390 var_name_regex = "\\$\\{([^\\}]+)\\}"
George Keishingb97a9042021-07-29 07:41:20 -05001391 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1392 for var in env_var_names_list:
1393 env_var = os.environ[var]
Patrick Williams20f38712022-12-08 06:18:26 -06001394 env_replace = "${" + var + "}"
George Keishingb97a9042021-07-29 07:41:20 -05001395 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1396 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001397 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001398 pass
1399
1400 # Parse the string for plugin vars.
1401 try:
1402 # Example, list of plugin vars ['my_username', 'my_data']
1403 plugin_var_name_list = global_plugin_dict.keys()
1404 for var in plugin_var_name_list:
George Keishing9348b402021-08-13 12:22:35 -05001405 # skip env var list already populated above code block list.
George Keishing0581cb02021-08-05 15:08:58 -05001406 if var in env_var_names_list:
1407 continue
George Keishing9348b402021-08-13 12:22:35 -05001408 # If this plugin var exist but empty in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001409 # This is either a YAML plugin statement incorrectly used or
George Keishing9348b402021-08-13 12:22:35 -05001410 # user added a plugin var which is not going to be populated.
George Keishing0581cb02021-08-05 15:08:58 -05001411 if yaml_arg_str in global_plugin_dict:
1412 if isinstance(global_plugin_dict[var], (list, dict)):
George Keishingc754b432025-04-24 14:27:14 +05301413 # List data type or dict can't be replaced, use
1414 # directly in eval function call.
George Keishing0581cb02021-08-05 15:08:58 -05001415 global_plugin_type_list.append(var)
1416 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001417 yaml_arg_str = yaml_arg_str.replace(
1418 str(var), str(global_plugin_dict[var])
1419 )
George Keishing0581cb02021-08-05 15:08:58 -05001420 # Just a string like filename or command.
1421 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001422 yaml_arg_str = yaml_arg_str.replace(
1423 str(var), str(global_plugin_dict[var])
1424 )
George Keishingb97a9042021-07-29 07:41:20 -05001425 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001426 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001427 pass
1428
1429 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001430
1431 def plugin_error_check(self, plugin_dict):
1432 r"""
1433 Plugin error dict processing.
1434
1435 Description of argument(s):
1436 plugin_dict Dictionary of plugin error.
1437 """
Patrick Williams20f38712022-12-08 06:18:26 -06001438 if any("plugin_error" in d for d in plugin_dict):
George Keishing1e7b0182021-08-06 14:05:54 -05001439 for d in plugin_dict:
Patrick Williams20f38712022-12-08 06:18:26 -06001440 if "plugin_error" in d:
1441 value = d["plugin_error"]
George Keishing1e7b0182021-08-06 14:05:54 -05001442 # Reference if the error is set or not by plugin.
1443 return plugin_error_dict[value]
George Keishingde79a9b2021-08-12 16:14:43 -05001444
1445 def key_index_list_dict(self, key, list_dict):
1446 r"""
1447 Iterate list of dictionary and return index if the key match is found.
1448
1449 Description of argument(s):
1450 key Valid Key in a dict.
1451 list_dict list of dictionary.
1452 """
1453 for i, d in enumerate(list_dict):
1454 if key in d.keys():
1455 return i
1456
1457 def plugin_expect_type(self, type, data):
1458 r"""
1459 Plugin expect directive type check.
1460 """
Patrick Williams20f38712022-12-08 06:18:26 -06001461 if type == "int":
George Keishingde79a9b2021-08-12 16:14:43 -05001462 return isinstance(data, int)
Patrick Williams20f38712022-12-08 06:18:26 -06001463 elif type == "float":
George Keishingde79a9b2021-08-12 16:14:43 -05001464 return isinstance(data, float)
Patrick Williams20f38712022-12-08 06:18:26 -06001465 elif type == "str":
George Keishingde79a9b2021-08-12 16:14:43 -05001466 return isinstance(data, str)
Patrick Williams20f38712022-12-08 06:18:26 -06001467 elif type == "list":
George Keishingde79a9b2021-08-12 16:14:43 -05001468 return isinstance(data, list)
Patrick Williams20f38712022-12-08 06:18:26 -06001469 elif type == "dict":
George Keishingde79a9b2021-08-12 16:14:43 -05001470 return isinstance(data, dict)
Patrick Williams20f38712022-12-08 06:18:26 -06001471 elif type == "tuple":
George Keishingde79a9b2021-08-12 16:14:43 -05001472 return isinstance(data, tuple)
1473 else:
1474 self.logger.info("\tInvalid data type requested: %s" % type)
Patrick Williams20f38712022-12-08 06:18:26 -06001475 return "INVALID"