blob: c99873f5c7b4de61e9c8113ea32a4c8b76f148ea [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 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500465 if self.ssh_remoteclient:
466 self.ssh_remoteclient.ssh_remoteclient_disconnect()
467 if self.telnet_remoteclient:
468 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500469
Patrick Williams20f38712022-12-08 06:18:26 -0600470 def protocol_ssh(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500471 r"""
472 Perform actions using SSH and SCP protocols.
473
474 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500475 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500476 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500477 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500478 """
479
Patrick Williams20f38712022-12-08 06:18:26 -0600480 if protocol == "SCP":
George Keishingf5a57502021-07-22 16:43:47 -0500481 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500482 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600483 self.collect_and_copy_ffdc(
484 self.ffdc_actions[target_type][sub_type]
485 )
Peter D Phan0c669772021-06-24 13:52:42 -0500486
Patrick Williams20f38712022-12-08 06:18:26 -0600487 def protocol_telnet(self, target_type, sub_type):
Peter D Phan5963d632021-07-12 09:58:55 -0500488 r"""
489 Perform actions using telnet protocol.
490 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500491 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500492 """
Patrick Williams20f38712022-12-08 06:18:26 -0600493 self.logger.info(
494 "\n\t[Run] Executing commands on %s using %s"
495 % (self.hostname, "TELNET")
496 )
Peter D Phan5963d632021-07-12 09:58:55 -0500497 telnet_files_saved = []
498 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600499 list_of_commands = self.ffdc_actions[target_type][sub_type]["COMMANDS"]
Peter D Phan5963d632021-07-12 09:58:55 -0500500 for index, each_cmd in enumerate(list_of_commands, start=0):
501 command_txt, command_timeout = self.unpack_command(each_cmd)
Patrick Williams20f38712022-12-08 06:18:26 -0600502 result = self.telnet_remoteclient.execute_command(
503 command_txt, command_timeout
504 )
Peter D Phan5963d632021-07-12 09:58:55 -0500505 if result:
506 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600507 targ_file = self.ffdc_actions[target_type][sub_type][
508 "FILES"
509 ][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500510 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500511 targ_file = command_txt
512 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600513 "\n\t[WARN] Missing filename to store data from"
514 " telnet %s." % each_cmd
515 )
516 self.logger.warning(
517 "\t[WARN] Data will be stored in %s." % targ_file
518 )
519 targ_file_with_path = (
520 self.ffdc_dir_path + self.ffdc_prefix + targ_file
521 )
Peter D Phan5963d632021-07-12 09:58:55 -0500522 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600523 with open(targ_file_with_path, "w") as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500524 fp.write(result)
525 fp.close
526 telnet_files_saved.append(targ_file)
527 progress_counter += 1
528 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500529 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500530 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500531 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500532
Patrick Williams20f38712022-12-08 06:18:26 -0600533 def protocol_execute(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500534 r"""
George Keishing506b0582021-07-27 09:31:22 -0500535 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500536
537 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500538 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500539 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500540 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500541 """
542
Patrick Williams20f38712022-12-08 06:18:26 -0600543 self.logger.info(
544 "\n\t[Run] Executing commands to %s using %s"
545 % (self.hostname, protocol)
546 )
George Keishing506b0582021-07-27 09:31:22 -0500547 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500548 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600549 list_of_cmd = self.get_command_list(
550 self.ffdc_actions[target_type][sub_type]
551 )
George Keishingeafba182021-06-29 13:44:58 -0500552 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500553 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500554 if isinstance(each_cmd, dict):
Patrick Williams20f38712022-12-08 06:18:26 -0600555 if "plugin" in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500556 # If the error is set and plugin explicitly
557 # requested to skip execution on error..
Patrick Williams20f38712022-12-08 06:18:26 -0600558 if plugin_error_dict[
559 "exit_on_error"
560 ] and self.plugin_error_check(each_cmd["plugin"]):
561 self.logger.info(
562 "\n\t[PLUGIN-ERROR] exit_on_error: %s"
563 % plugin_error_dict["exit_on_error"]
564 )
565 self.logger.info(
566 "\t[PLUGIN-SKIP] %s" % each_cmd["plugin"][0]
567 )
George Keishing1e7b0182021-08-06 14:05:54 -0500568 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500569 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500570 # call the plugin
571 self.logger.info("\n\t[PLUGIN-START]")
Patrick Williams20f38712022-12-08 06:18:26 -0600572 result = self.execute_plugin_block(each_cmd["plugin"])
George Keishingb97a9042021-07-29 07:41:20 -0500573 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500574 else:
George Keishing2b83e042021-08-03 12:56:11 -0500575 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500576
George Keishingcaa97e62021-08-03 14:00:09 -0500577 if not plugin_call:
578 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500579 if result:
580 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600581 file_name = self.get_file_list(
582 self.ffdc_actions[target_type][sub_type]
583 )[index]
George Keishingb97a9042021-07-29 07:41:20 -0500584 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500585 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500586 continue
Patrick Williams20f38712022-12-08 06:18:26 -0600587 targ_file = self.yaml_env_and_plugin_vars_populate(
588 file_name
589 )
George Keishingeafba182021-06-29 13:44:58 -0500590 except IndexError:
Patrick Williams20f38712022-12-08 06:18:26 -0600591 targ_file = each_cmd.split("/")[-1]
George Keishing506b0582021-07-27 09:31:22 -0500592 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600593 "\n\t[WARN] Missing filename to store data from %s."
594 % each_cmd
595 )
596 self.logger.warning(
597 "\t[WARN] Data will be stored in %s." % targ_file
598 )
George Keishingeafba182021-06-29 13:44:58 -0500599
Patrick Williams20f38712022-12-08 06:18:26 -0600600 targ_file_with_path = (
601 self.ffdc_dir_path + self.ffdc_prefix + targ_file
602 )
George Keishingeafba182021-06-29 13:44:58 -0500603
604 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600605 with open(targ_file_with_path, "w") as fp:
George Keishing91308ea2021-08-10 14:43:15 -0500606 if isinstance(result, dict):
607 fp.write(json.dumps(result))
608 else:
609 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500610 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500611 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500612
613 progress_counter += 1
614 self.print_progress(progress_counter)
615
Peter D Phane86d9a52021-07-15 10:42:25 -0500616 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500617
George Keishing506b0582021-07-27 09:31:22 -0500618 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500619 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500620
Patrick Williams20f38712022-12-08 06:18:26 -0600621 def collect_and_copy_ffdc(
622 self, ffdc_actions_for_target_type, form_filename=False
623 ):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500624 r"""
625 Send commands in ffdc_config file to targeted system.
626
627 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530628 ffdc_actions_for_target_type Commands and files for the selected
629 remote host type.
630 form_filename If true, pre-pend self.target_type to
631 filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500632 """
633
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500634 # Executing commands, if any
Patrick Williams20f38712022-12-08 06:18:26 -0600635 self.ssh_execute_ffdc_commands(
636 ffdc_actions_for_target_type, form_filename
637 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500638
Peter D Phan3beb02e2021-07-06 13:25:17 -0500639 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500640 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600641 self.logger.info(
642 "\n\n\tCopying FFDC files from remote system %s.\n"
643 % self.hostname
644 )
Peter D Phan2b8052d2021-06-22 10:55:41 -0500645
Peter D Phan04aca3b2021-06-21 10:37:18 -0500646 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500647 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Patrick Williams20f38712022-12-08 06:18:26 -0600648 self.scp_ffdc(
649 self.ffdc_dir_path,
650 self.ffdc_prefix,
651 form_filename,
652 list_of_files,
653 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500654 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600655 self.logger.info(
656 "\n\n\tSkip copying FFDC files from remote system %s.\n"
657 % self.hostname
658 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500659
Patrick Williams20f38712022-12-08 06:18:26 -0600660 def get_command_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500661 r"""
662 Fetch list of commands from configuration file
663
664 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530665 ffdc_actions_for_target_type Commands and files for the selected
666 remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500667 """
668 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600669 list_of_commands = ffdc_actions_for_target_type["COMMANDS"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500670 except KeyError:
671 list_of_commands = []
672 return list_of_commands
673
Patrick Williams20f38712022-12-08 06:18:26 -0600674 def get_file_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500675 r"""
676 Fetch list of commands from configuration file
677
678 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530679 ffdc_actions_for_target_type Commands and files for the selected
680 remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500681 """
682 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600683 list_of_files = ffdc_actions_for_target_type["FILES"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500684 except KeyError:
685 list_of_files = []
686 return list_of_files
687
Patrick Williams20f38712022-12-08 06:18:26 -0600688 def unpack_command(self, command):
Peter D Phan5963d632021-07-12 09:58:55 -0500689 r"""
690 Unpack command from config file
691
692 Description of argument(s):
693 command Command from config file.
694 """
695 if isinstance(command, dict):
696 command_txt = next(iter(command))
697 command_timeout = next(iter(command.values()))
698 elif isinstance(command, str):
699 command_txt = command
700 # Default command timeout 60 seconds
701 command_timeout = 60
702
703 return command_txt, command_timeout
704
Patrick Williams20f38712022-12-08 06:18:26 -0600705 def ssh_execute_ffdc_commands(
706 self, ffdc_actions_for_target_type, form_filename=False
707 ):
Peter D Phan3beb02e2021-07-06 13:25:17 -0500708 r"""
709 Send commands in ffdc_config file to targeted system.
710
711 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530712 ffdc_actions_for_target_type Commands and files for the selected
713 remote host type.
714 form_filename If true, pre-pend self.target_type to
715 filename
Peter D Phan3beb02e2021-07-06 13:25:17 -0500716 """
Patrick Williams20f38712022-12-08 06:18:26 -0600717 self.logger.info(
718 "\n\t[Run] Executing commands on %s using %s"
719 % (self.hostname, ffdc_actions_for_target_type["PROTOCOL"][0])
720 )
Peter D Phan3beb02e2021-07-06 13:25:17 -0500721
George Keishingf5a57502021-07-22 16:43:47 -0500722 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500723 # If command list is empty, returns
724 if not list_of_commands:
725 return
726
727 progress_counter = 0
728 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500729 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500730
731 if form_filename:
732 command_txt = str(command_txt % self.target_type)
733
Patrick Williams20f38712022-12-08 06:18:26 -0600734 (
735 cmd_exit_code,
736 err,
737 response,
738 ) = self.ssh_remoteclient.execute_command(
739 command_txt, command_timeout
740 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500741
742 if cmd_exit_code:
743 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600744 "\n\t\t[WARN] %s exits with code %s."
745 % (command_txt, str(cmd_exit_code))
746 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500747 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500748
Peter D Phan3beb02e2021-07-06 13:25:17 -0500749 progress_counter += 1
750 self.print_progress(progress_counter)
751
Peter D Phane86d9a52021-07-15 10:42:25 -0500752 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500753
Patrick Williams20f38712022-12-08 06:18:26 -0600754 def group_copy(self, ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500755 r"""
756 scp group of files (wild card) from remote host.
757
758 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530759 fdc_actions_for_target_type Commands and files for the selected
760 remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500761 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500762
Peter D Phan5963d632021-07-12 09:58:55 -0500763 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600764 self.logger.info(
765 "\n\tCopying files from remote system %s via SCP.\n"
766 % self.hostname
767 )
Peter D Phan56429a62021-06-23 08:38:29 -0500768
Patrick Williams20f38712022-12-08 06:18:26 -0600769 list_of_commands = self.get_command_list(
770 ffdc_actions_for_target_type
771 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500772 # If command list is empty, returns
773 if not list_of_commands:
774 return
Peter D Phan56429a62021-06-23 08:38:29 -0500775
Peter D Phanbabf2962021-07-07 11:24:40 -0500776 for command in list_of_commands:
777 try:
George Keishingb4540e72021-08-02 13:48:46 -0500778 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500779 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500780 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500781 continue
782
Patrick Williams20f38712022-12-08 06:18:26 -0600783 (
784 cmd_exit_code,
785 err,
786 response,
787 ) = self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500788
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500789 # If file does not exist, code take no action.
790 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500791 if response:
Patrick Williams20f38712022-12-08 06:18:26 -0600792 scp_result = self.ssh_remoteclient.scp_file_from_remote(
793 response.split("\n"), self.ffdc_dir_path
794 )
Peter D Phan56429a62021-06-23 08:38:29 -0500795 if scp_result:
Patrick Williams20f38712022-12-08 06:18:26 -0600796 self.logger.info(
797 "\t\tSuccessfully copied from "
798 + self.hostname
799 + ":"
800 + command
801 )
Peter D Phan56429a62021-06-23 08:38:29 -0500802 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500803 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500804
805 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600806 self.logger.info(
807 "\n\n\tSkip copying files from remote system %s.\n"
808 % self.hostname
809 )
Peter D Phan56429a62021-06-23 08:38:29 -0500810
Patrick Williams20f38712022-12-08 06:18:26 -0600811 def scp_ffdc(
812 self,
813 targ_dir_path,
814 targ_file_prefix,
815 form_filename,
816 file_list=None,
817 quiet=None,
818 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500819 r"""
George Keishingc754b432025-04-24 14:27:14 +0530820 SCP all files in file_dict to the indicated directory on the local
821 system.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500822
823 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530824 targ_dir_path The path of the directory to receive
825 the files.
George Keishinge16f1582022-12-15 07:32:21 -0600826 targ_file_prefix Prefix which will be prepended to each
Peter D Phan72ce6b82021-06-03 06:18:26 -0500827 target file's name.
George Keishingc754b432025-04-24 14:27:14 +0530828 file_dict A dictionary of files to scp from
829 targeted system to this system
Peter D Phan72ce6b82021-06-03 06:18:26 -0500830
831 """
832
Peter D Phan72ce6b82021-06-03 06:18:26 -0500833 progress_counter = 0
834 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500835 if form_filename:
836 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500837 source_file_path = filename
Patrick Williams20f38712022-12-08 06:18:26 -0600838 targ_file_path = (
839 targ_dir_path + targ_file_prefix + filename.split("/")[-1]
840 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500841
Peter D Phanbabf2962021-07-07 11:24:40 -0500842 # If source file name contains wild card, copy filename as is.
Patrick Williams20f38712022-12-08 06:18:26 -0600843 if "*" in source_file_path:
844 scp_result = self.ssh_remoteclient.scp_file_from_remote(
845 source_file_path, self.ffdc_dir_path
846 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500847 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600848 scp_result = self.ssh_remoteclient.scp_file_from_remote(
849 source_file_path, targ_file_path
850 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500851
852 if not quiet:
853 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500854 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600855 "\t\tSuccessfully copied from "
856 + self.hostname
857 + ":"
858 + source_file_path
859 + ".\n"
860 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500861 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500862 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600863 "\t\tFail to copy from "
864 + self.hostname
865 + ":"
866 + source_file_path
867 + ".\n"
868 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500869 else:
870 progress_counter += 1
871 self.print_progress(progress_counter)
872
Peter D Phan5e56f522021-12-20 13:19:41 -0600873 def set_ffdc_default_store_path(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500874 r"""
875 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
George Keishingc754b432025-04-24 14:27:14 +0530876 Collected ffdc file will be stored in dir
877 /self.location/hostname_timestr/.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500878 Individual ffdc file will have timestr_filename.
879
880 Description of class variables:
George Keishingc754b432025-04-24 14:27:14 +0530881 self.ffdc_dir_path The dir path where collected ffdc data files
882 should be put.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500883
884 self.ffdc_prefix The prefix to be given to each ffdc file name.
885
886 """
887
888 timestr = time.strftime("%Y%m%d-%H%M%S")
Patrick Williams20f38712022-12-08 06:18:26 -0600889 self.ffdc_dir_path = (
890 self.location + "/" + self.hostname + "_" + timestr + "/"
891 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500892 self.ffdc_prefix = timestr + "_"
893 self.validate_local_store(self.ffdc_dir_path)
894
Peter D Phan5e56f522021-12-20 13:19:41 -0600895 # Need to verify local store path exists prior to instantiate this class.
896 # This class method is used to share the same code between CLI input parm
897 # and Robot Framework "${EXECDIR}/logs" before referencing this class.
898 @classmethod
899 def validate_local_store(cls, dir_path):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500900 r"""
901 Ensure path exists to store FFDC files locally.
902
903 Description of variable:
904 dir_path The dir path where collected ffdc data files will be stored.
905
906 """
907
908 if not os.path.exists(dir_path):
909 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500910 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500911 except (IOError, OSError) as e:
912 # PermissionError
913 if e.errno == EPERM or e.errno == EACCES:
George Keishing15352052025-04-24 18:55:47 +0530914 print(
Patrick Williams20f38712022-12-08 06:18:26 -0600915 "\tERROR: os.makedirs %s failed with"
916 " PermissionError.\n" % dir_path
917 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500918 else:
George Keishing15352052025-04-24 18:55:47 +0530919 print(
Patrick Williams20f38712022-12-08 06:18:26 -0600920 "\tERROR: os.makedirs %s failed with %s.\n"
921 % (dir_path, e.strerror)
922 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500923 sys.exit(-1)
924
925 def print_progress(self, progress):
926 r"""
927 Print activity progress +
928
929 Description of variable:
930 progress Progress counter.
931
932 """
933
934 sys.stdout.write("\r\t" + "+" * progress)
935 sys.stdout.flush()
Patrick Williams20f38712022-12-08 06:18:26 -0600936 time.sleep(0.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500937
938 def verify_redfish(self):
939 r"""
940 Verify remote host has redfish service active
941
942 """
Patrick Williams20f38712022-12-08 06:18:26 -0600943 redfish_parm = (
944 "redfishtool -r "
945 + self.hostname
George Keishing7a61aa22023-06-26 13:18:37 +0530946 + ":"
947 + self.port_https
Patrick Williams20f38712022-12-08 06:18:26 -0600948 + " -S Always raw GET /redfish/v1/"
949 )
950 return self.run_tool_cmd(redfish_parm, True)
Peter D Phan0c669772021-06-24 13:52:42 -0500951
George Keishingeafba182021-06-29 13:44:58 -0500952 def verify_ipmi(self):
953 r"""
954 Verify remote host has IPMI LAN service active
955
956 """
Patrick Williams20f38712022-12-08 06:18:26 -0600957 if self.target_type == "OPENBMC":
958 ipmi_parm = (
959 "ipmitool -I lanplus -C 17 -U "
960 + self.username
961 + " -P "
962 + self.password
963 + " -H "
964 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530965 + " -p "
966 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600967 + " power status"
968 )
George Keishing484f8242021-07-27 01:42:02 -0500969 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600970 ipmi_parm = (
971 "ipmitool -I lanplus -P "
972 + self.password
973 + " -H "
974 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530975 + " -p "
976 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600977 + " power status"
978 )
George Keishing484f8242021-07-27 01:42:02 -0500979
Patrick Williams20f38712022-12-08 06:18:26 -0600980 return self.run_tool_cmd(ipmi_parm, True)
George Keishingeafba182021-06-29 13:44:58 -0500981
Patrick Williams20f38712022-12-08 06:18:26 -0600982 def run_tool_cmd(self, parms_string, quiet=False):
George Keishingeafba182021-06-29 13:44:58 -0500983 r"""
George Keishing506b0582021-07-27 09:31:22 -0500984 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500985
986 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500987 parms_string tool command options.
988 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500989 """
990
Patrick Williams20f38712022-12-08 06:18:26 -0600991 result = subprocess.run(
992 [parms_string],
993 stdout=subprocess.PIPE,
994 stderr=subprocess.PIPE,
995 shell=True,
996 universal_newlines=True,
997 )
George Keishingeafba182021-06-29 13:44:58 -0500998
999 if result.stderr and not quiet:
Patrick Williams20f38712022-12-08 06:18:26 -06001000 self.logger.error("\n\t\tERROR with %s " % parms_string)
1001 self.logger.error("\t\t" + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -05001002
1003 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -05001004
George Keishingf5a57502021-07-22 16:43:47 -05001005 def verify_protocol(self, protocol_list):
1006 r"""
1007 Perform protocol working check.
1008
1009 Description of argument(s):
1010 protocol_list List of protocol.
1011 """
1012
1013 tmp_list = []
1014 if self.target_is_pingable():
1015 tmp_list.append("SHELL")
1016
1017 for protocol in protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -06001018 if self.remote_protocol != "ALL":
George Keishingf5a57502021-07-22 16:43:47 -05001019 if self.remote_protocol != protocol:
1020 continue
1021
1022 # Only check SSH/SCP once for both protocols
Patrick Williams20f38712022-12-08 06:18:26 -06001023 if (
1024 protocol == "SSH"
1025 or protocol == "SCP"
1026 and protocol not in tmp_list
1027 ):
George Keishingf5a57502021-07-22 16:43:47 -05001028 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -05001029 # Add only what user asked.
Patrick Williams20f38712022-12-08 06:18:26 -06001030 if self.remote_protocol != "ALL":
George Keishingaa638702021-07-26 11:48:28 -05001031 tmp_list.append(self.remote_protocol)
1032 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001033 tmp_list.append("SSH")
1034 tmp_list.append("SCP")
George Keishingf5a57502021-07-22 16:43:47 -05001035
Patrick Williams20f38712022-12-08 06:18:26 -06001036 if protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -05001037 if self.telnet_to_target_system():
1038 tmp_list.append(protocol)
1039
Patrick Williams20f38712022-12-08 06:18:26 -06001040 if protocol == "REDFISH":
George Keishingf5a57502021-07-22 16:43:47 -05001041 if self.verify_redfish():
1042 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001043 self.logger.info(
1044 "\n\t[Check] %s Redfish Service.\t\t [OK]"
1045 % self.hostname
1046 )
George Keishingf5a57502021-07-22 16:43:47 -05001047 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001048 self.logger.info(
1049 "\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]"
1050 % self.hostname
1051 )
George Keishingf5a57502021-07-22 16:43:47 -05001052
Patrick Williams20f38712022-12-08 06:18:26 -06001053 if protocol == "IPMI":
George Keishingf5a57502021-07-22 16:43:47 -05001054 if self.verify_ipmi():
1055 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001056 self.logger.info(
1057 "\n\t[Check] %s IPMI LAN Service.\t\t [OK]"
1058 % self.hostname
1059 )
George Keishingf5a57502021-07-22 16:43:47 -05001060 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001061 self.logger.info(
1062 "\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]"
1063 % self.hostname
1064 )
George Keishingf5a57502021-07-22 16:43:47 -05001065
1066 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -05001067
1068 def load_env(self):
1069 r"""
1070 Perform protocol working check.
1071
1072 """
George Keishingc754b432025-04-24 14:27:14 +05301073 # This is for the env vars a user can use in YAML to load
1074 # it at runtime.
George Keishinge1686752021-07-27 12:55:28 -05001075 # Example YAML:
1076 # -COMMANDS:
1077 # - my_command ${hostname} ${username} ${password}
Patrick Williams20f38712022-12-08 06:18:26 -06001078 os.environ["hostname"] = self.hostname
1079 os.environ["username"] = self.username
1080 os.environ["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301081 os.environ["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301082 os.environ["port_https"] = self.port_https
1083 os.environ["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001084
1085 # Append default Env.
Patrick Williams20f38712022-12-08 06:18:26 -06001086 self.env_dict["hostname"] = self.hostname
1087 self.env_dict["username"] = self.username
1088 self.env_dict["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301089 self.env_dict["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301090 self.env_dict["port_https"] = self.port_https
1091 self.env_dict["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001092
1093 try:
1094 tmp_env_dict = {}
1095 if self.env_vars:
1096 tmp_env_dict = json.loads(self.env_vars)
1097 # Export ENV vars default.
1098 for key, value in tmp_env_dict.items():
1099 os.environ[key] = value
1100 self.env_dict[key] = str(value)
1101
1102 if self.econfig:
Patrick Williams20f38712022-12-08 06:18:26 -06001103 with open(self.econfig, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -05001104 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -07001105 tmp_env_dict = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -05001106 except yaml.YAMLError as e:
1107 self.logger.error(e)
1108 sys.exit(-1)
George Keishinge1686752021-07-27 12:55:28 -05001109 # Export ENV vars.
Patrick Williams20f38712022-12-08 06:18:26 -06001110 for key, value in tmp_env_dict["env_params"].items():
George Keishinge1686752021-07-27 12:55:28 -05001111 os.environ[key] = str(value)
1112 self.env_dict[key] = str(value)
1113 except json.decoder.JSONDecodeError as e:
1114 self.logger.error("\n\tERROR: %s " % e)
1115 sys.exit(-1)
1116
1117 # This to mask the password from displaying on the console.
1118 mask_dict = self.env_dict.copy()
1119 for k, v in mask_dict.items():
1120 if k.lower().find("password") != -1:
1121 hidden_text = []
1122 hidden_text.append(v)
Patrick Williams20f38712022-12-08 06:18:26 -06001123 password_regex = (
1124 "(" + "|".join([re.escape(x) for x in hidden_text]) + ")"
1125 )
George Keishinge1686752021-07-27 12:55:28 -05001126 mask_dict[k] = re.sub(password_regex, "********", v)
1127
1128 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -05001129
1130 def execute_python_eval(self, eval_string):
1131 r"""
George Keishing9348b402021-08-13 12:22:35 -05001132 Execute qualified python function string using eval.
George Keishingb97a9042021-07-29 07:41:20 -05001133
1134 Description of argument(s):
1135 eval_string Execute the python object.
1136
1137 Example:
1138 eval(plugin.foo_func.foo_func(10))
1139 """
1140 try:
George Keishingdda48ce2021-08-12 07:02:27 -05001141 self.logger.info("\tExecuting plugin func()")
1142 self.logger.debug("\tCall func: %s" % eval_string)
George Keishingb97a9042021-07-29 07:41:20 -05001143 result = eval(eval_string)
1144 self.logger.info("\treturn: %s" % str(result))
Patrick Williams20f38712022-12-08 06:18:26 -06001145 except (
1146 ValueError,
1147 SyntaxError,
1148 NameError,
1149 AttributeError,
1150 TypeError,
1151 ) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001152 self.logger.error("\tERROR: execute_python_eval: %s" % e)
1153 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001154 plugin_error_dict["exit_on_error"] = True
George Keishing73b95d12021-08-13 14:30:52 -05001155 self.logger.info("\treturn: PLUGIN_EVAL_ERROR")
Patrick Williams20f38712022-12-08 06:18:26 -06001156 return "PLUGIN_EVAL_ERROR"
George Keishingb97a9042021-07-29 07:41:20 -05001157
1158 return result
1159
1160 def execute_plugin_block(self, plugin_cmd_list):
1161 r"""
Peter D Phan5e56f522021-12-20 13:19:41 -06001162 Pack the plugin command to qualifed python string object.
George Keishingb97a9042021-07-29 07:41:20 -05001163
1164 Description of argument(s):
1165 plugin_list_dict Plugin block read from YAML
1166 [{'plugin_name': 'plugin.foo_func.my_func'},
1167 {'plugin_args': [10]}]
1168
1169 Example:
1170 - plugin:
1171 - plugin_name: plugin.foo_func.my_func
1172 - plugin_args:
1173 - arg1
1174 - arg2
1175
1176 - plugin:
1177 - plugin_name: result = plugin.foo_func.my_func
1178 - plugin_args:
1179 - arg1
1180 - arg2
1181
1182 - plugin:
1183 - plugin_name: result1,result2 = plugin.foo_func.my_func
1184 - plugin_args:
1185 - arg1
1186 - arg2
1187 """
1188 try:
Patrick Williams20f38712022-12-08 06:18:26 -06001189 idx = self.key_index_list_dict("plugin_name", plugin_cmd_list)
1190 plugin_name = plugin_cmd_list[idx]["plugin_name"]
George Keishingb97a9042021-07-29 07:41:20 -05001191 # Equal separator means plugin function returns result.
Patrick Williams20f38712022-12-08 06:18:26 -06001192 if " = " in plugin_name:
George Keishingb97a9042021-07-29 07:41:20 -05001193 # Ex. ['result', 'plugin.foo_func.my_func']
Patrick Williams20f38712022-12-08 06:18:26 -06001194 plugin_name_args = plugin_name.split(" = ")
George Keishingb97a9042021-07-29 07:41:20 -05001195 # plugin func return data.
1196 for arg in plugin_name_args:
1197 if arg == plugin_name_args[-1]:
1198 plugin_name = arg
1199 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001200 plugin_resp = arg.split(",")
George Keishingb97a9042021-07-29 07:41:20 -05001201 # ['result1','result2']
1202 for x in plugin_resp:
1203 global_plugin_list.append(x)
1204 global_plugin_dict[x] = ""
1205
1206 # Walk the plugin args ['arg1,'arg2']
1207 # If the YAML plugin statement 'plugin_args' is not declared.
Patrick Williams20f38712022-12-08 06:18:26 -06001208 if any("plugin_args" in d for d in plugin_cmd_list):
1209 idx = self.key_index_list_dict("plugin_args", plugin_cmd_list)
1210 plugin_args = plugin_cmd_list[idx]["plugin_args"]
George Keishingb97a9042021-07-29 07:41:20 -05001211 if plugin_args:
1212 plugin_args = self.yaml_args_populate(plugin_args)
1213 else:
1214 plugin_args = []
1215 else:
1216 plugin_args = self.yaml_args_populate([])
1217
1218 # Pack the args arg1, arg2, .... argn into
1219 # "arg1","arg2","argn" string as params for function.
1220 parm_args_str = self.yaml_args_string(plugin_args)
1221 if parm_args_str:
Patrick Williams20f38712022-12-08 06:18:26 -06001222 plugin_func = plugin_name + "(" + parm_args_str + ")"
George Keishingb97a9042021-07-29 07:41:20 -05001223 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001224 plugin_func = plugin_name + "()"
George Keishingb97a9042021-07-29 07:41:20 -05001225
1226 # Execute plugin function.
1227 if global_plugin_dict:
1228 resp = self.execute_python_eval(plugin_func)
George Keishing9348b402021-08-13 12:22:35 -05001229 # Update plugin vars dict if there is any.
Patrick Williams20f38712022-12-08 06:18:26 -06001230 if resp != "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001231 self.response_args_data(resp)
George Keishingb97a9042021-07-29 07:41:20 -05001232 else:
George Keishingcaa97e62021-08-03 14:00:09 -05001233 resp = self.execute_python_eval(plugin_func)
George Keishingb97a9042021-07-29 07:41:20 -05001234 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001235 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001236 plugin_error_dict["exit_on_error"] = True
George Keishing1e7b0182021-08-06 14:05:54 -05001237 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001238 pass
1239
George Keishing73b95d12021-08-13 14:30:52 -05001240 # There is a real error executing the plugin function.
Patrick Williams20f38712022-12-08 06:18:26 -06001241 if resp == "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001242 return resp
1243
George Keishingde79a9b2021-08-12 16:14:43 -05001244 # Check if plugin_expects_return (int, string, list,dict etc)
Patrick Williams20f38712022-12-08 06:18:26 -06001245 if any("plugin_expects_return" in d for d in plugin_cmd_list):
1246 idx = self.key_index_list_dict(
1247 "plugin_expects_return", plugin_cmd_list
1248 )
1249 plugin_expects = plugin_cmd_list[idx]["plugin_expects_return"]
George Keishingde79a9b2021-08-12 16:14:43 -05001250 if plugin_expects:
1251 if resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001252 if (
1253 self.plugin_expect_type(plugin_expects, resp)
1254 == "INVALID"
1255 ):
George Keishingde79a9b2021-08-12 16:14:43 -05001256 self.logger.error("\tWARN: Plugin error check skipped")
1257 elif not self.plugin_expect_type(plugin_expects, resp):
Patrick Williams20f38712022-12-08 06:18:26 -06001258 self.logger.error(
1259 "\tERROR: Plugin expects return data: %s"
1260 % plugin_expects
1261 )
1262 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001263 elif not resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001264 self.logger.error(
1265 "\tERROR: Plugin func failed to return data"
1266 )
1267 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001268
1269 return resp
1270
George Keishingb97a9042021-07-29 07:41:20 -05001271 def response_args_data(self, plugin_resp):
1272 r"""
George Keishing9348b402021-08-13 12:22:35 -05001273 Parse the plugin function response and update plugin return variable.
George Keishingb97a9042021-07-29 07:41:20 -05001274
1275 plugin_resp Response data from plugin function.
1276 """
1277 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -05001278 resp_data = ""
George Keishing9348b402021-08-13 12:22:35 -05001279
George Keishingb97a9042021-07-29 07:41:20 -05001280 # There is nothing to update the plugin response.
Patrick Williams20f38712022-12-08 06:18:26 -06001281 if len(global_plugin_list) == 0 or plugin_resp == "None":
George Keishingb97a9042021-07-29 07:41:20 -05001282 return
1283
George Keishing5765f792021-08-02 13:08:53 -05001284 if isinstance(plugin_resp, str):
Patrick Williams20f38712022-12-08 06:18:26 -06001285 resp_data = plugin_resp.strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001286 resp_list.append(resp_data)
1287 elif isinstance(plugin_resp, bytes):
Patrick Williams20f38712022-12-08 06:18:26 -06001288 resp_data = str(plugin_resp, "UTF-8").strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001289 resp_list.append(resp_data)
1290 elif isinstance(plugin_resp, tuple):
1291 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -05001292 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -05001293 else:
1294 resp_list = list(plugin_resp)
Patrick Williams20f38712022-12-08 06:18:26 -06001295 resp_list = [x.strip("\r\n\t") for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -05001296 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -05001297 if len(global_plugin_list) == 1:
Patrick Williams20f38712022-12-08 06:18:26 -06001298 resp_list.append([x.strip("\r\n\t") for x in plugin_resp])
George Keishing5765f792021-08-02 13:08:53 -05001299 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001300 resp_list = [x.strip("\r\n\t") for x in plugin_resp]
George Keishing5765f792021-08-02 13:08:53 -05001301 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1302 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001303
George Keishing9348b402021-08-13 12:22:35 -05001304 # Iterate if there is a list of plugin return vars to update.
George Keishingb97a9042021-07-29 07:41:20 -05001305 for idx, item in enumerate(resp_list, start=0):
George Keishing9348b402021-08-13 12:22:35 -05001306 # Exit loop, done required loop.
George Keishingb97a9042021-07-29 07:41:20 -05001307 if idx >= len(global_plugin_list):
1308 break
1309 # Find the index of the return func in the list and
1310 # update the global func return dictionary.
1311 try:
1312 dict_idx = global_plugin_list[idx]
1313 global_plugin_dict[dict_idx] = item
1314 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001315 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001316 pass
1317
1318 # Done updating plugin dict irrespective of pass or failed,
George Keishing9348b402021-08-13 12:22:35 -05001319 # clear all the list element for next plugin block execute.
George Keishingb97a9042021-07-29 07:41:20 -05001320 global_plugin_list.clear()
1321
1322 def yaml_args_string(self, plugin_args):
1323 r"""
1324 Pack the args into string.
1325
1326 plugin_args arg list ['arg1','arg2,'argn']
1327 """
Patrick Williams20f38712022-12-08 06:18:26 -06001328 args_str = ""
George Keishingb97a9042021-07-29 07:41:20 -05001329 for args in plugin_args:
1330 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001331 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001332 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001333 elif args in global_plugin_type_list:
1334 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001335 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001336 args_str += '"' + str(args.strip("\r\n\t")) + '"'
George Keishingb97a9042021-07-29 07:41:20 -05001337 # Skip last list element.
1338 if args != plugin_args[-1]:
1339 args_str += ","
1340 return args_str
1341
1342 def yaml_args_populate(self, yaml_arg_list):
1343 r"""
George Keishing9348b402021-08-13 12:22:35 -05001344 Decode env and plugin vars and populate.
George Keishingb97a9042021-07-29 07:41:20 -05001345
1346 Description of argument(s):
1347 yaml_arg_list arg list read from YAML
1348
1349 Example:
1350 - plugin_args:
1351 - arg1
1352 - arg2
1353
1354 yaml_arg_list: [arg2, arg2]
1355 """
1356 # Get the env loaded keys as list ['hostname', 'username', 'password'].
George Keishingb97a9042021-07-29 07:41:20 -05001357
1358 if isinstance(yaml_arg_list, list):
1359 tmp_list = []
1360 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001361 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001362 tmp_list.append(arg)
1363 continue
1364 elif isinstance(arg, str):
1365 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1366 tmp_list.append(arg_str)
1367 else:
1368 tmp_list.append(arg)
1369
1370 # return populated list.
1371 return tmp_list
1372
1373 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1374 r"""
George Keishing9348b402021-08-13 12:22:35 -05001375 Update ${MY_VAR} and plugin vars.
George Keishingb97a9042021-07-29 07:41:20 -05001376
1377 Description of argument(s):
George Keishing9348b402021-08-13 12:22:35 -05001378 yaml_arg_str arg string read from YAML.
George Keishingb97a9042021-07-29 07:41:20 -05001379
1380 Example:
1381 - cat ${MY_VAR}
1382 - ls -AX my_plugin_var
1383 """
George Keishing9348b402021-08-13 12:22:35 -05001384 # Parse the string for env vars ${env_vars}.
George Keishingb97a9042021-07-29 07:41:20 -05001385 try:
George Keishingc754b432025-04-24 14:27:14 +05301386 # Example, list of matching
1387 # env vars ['username', 'password', 'hostname']
George Keishingb97a9042021-07-29 07:41:20 -05001388 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
Patrick Williams20f38712022-12-08 06:18:26 -06001389 var_name_regex = "\\$\\{([^\\}]+)\\}"
George Keishingb97a9042021-07-29 07:41:20 -05001390 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1391 for var in env_var_names_list:
1392 env_var = os.environ[var]
Patrick Williams20f38712022-12-08 06:18:26 -06001393 env_replace = "${" + var + "}"
George Keishingb97a9042021-07-29 07:41:20 -05001394 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1395 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001396 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001397 pass
1398
1399 # Parse the string for plugin vars.
1400 try:
1401 # Example, list of plugin vars ['my_username', 'my_data']
1402 plugin_var_name_list = global_plugin_dict.keys()
1403 for var in plugin_var_name_list:
George Keishing9348b402021-08-13 12:22:35 -05001404 # skip env var list already populated above code block list.
George Keishing0581cb02021-08-05 15:08:58 -05001405 if var in env_var_names_list:
1406 continue
George Keishing9348b402021-08-13 12:22:35 -05001407 # If this plugin var exist but empty in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001408 # This is either a YAML plugin statement incorrectly used or
George Keishing9348b402021-08-13 12:22:35 -05001409 # user added a plugin var which is not going to be populated.
George Keishing0581cb02021-08-05 15:08:58 -05001410 if yaml_arg_str in global_plugin_dict:
1411 if isinstance(global_plugin_dict[var], (list, dict)):
George Keishingc754b432025-04-24 14:27:14 +05301412 # List data type or dict can't be replaced, use
1413 # directly in eval function call.
George Keishing0581cb02021-08-05 15:08:58 -05001414 global_plugin_type_list.append(var)
1415 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001416 yaml_arg_str = yaml_arg_str.replace(
1417 str(var), str(global_plugin_dict[var])
1418 )
George Keishing0581cb02021-08-05 15:08:58 -05001419 # Just a string like filename or command.
1420 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001421 yaml_arg_str = yaml_arg_str.replace(
1422 str(var), str(global_plugin_dict[var])
1423 )
George Keishingb97a9042021-07-29 07:41:20 -05001424 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001425 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001426 pass
1427
1428 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001429
1430 def plugin_error_check(self, plugin_dict):
1431 r"""
1432 Plugin error dict processing.
1433
1434 Description of argument(s):
1435 plugin_dict Dictionary of plugin error.
1436 """
Patrick Williams20f38712022-12-08 06:18:26 -06001437 if any("plugin_error" in d for d in plugin_dict):
George Keishing1e7b0182021-08-06 14:05:54 -05001438 for d in plugin_dict:
Patrick Williams20f38712022-12-08 06:18:26 -06001439 if "plugin_error" in d:
1440 value = d["plugin_error"]
George Keishing1e7b0182021-08-06 14:05:54 -05001441 # Reference if the error is set or not by plugin.
1442 return plugin_error_dict[value]
George Keishingde79a9b2021-08-12 16:14:43 -05001443
1444 def key_index_list_dict(self, key, list_dict):
1445 r"""
1446 Iterate list of dictionary and return index if the key match is found.
1447
1448 Description of argument(s):
1449 key Valid Key in a dict.
1450 list_dict list of dictionary.
1451 """
1452 for i, d in enumerate(list_dict):
1453 if key in d.keys():
1454 return i
1455
1456 def plugin_expect_type(self, type, data):
1457 r"""
1458 Plugin expect directive type check.
1459 """
Patrick Williams20f38712022-12-08 06:18:26 -06001460 if type == "int":
George Keishingde79a9b2021-08-12 16:14:43 -05001461 return isinstance(data, int)
Patrick Williams20f38712022-12-08 06:18:26 -06001462 elif type == "float":
George Keishingde79a9b2021-08-12 16:14:43 -05001463 return isinstance(data, float)
Patrick Williams20f38712022-12-08 06:18:26 -06001464 elif type == "str":
George Keishingde79a9b2021-08-12 16:14:43 -05001465 return isinstance(data, str)
Patrick Williams20f38712022-12-08 06:18:26 -06001466 elif type == "list":
George Keishingde79a9b2021-08-12 16:14:43 -05001467 return isinstance(data, list)
Patrick Williams20f38712022-12-08 06:18:26 -06001468 elif type == "dict":
George Keishingde79a9b2021-08-12 16:14:43 -05001469 return isinstance(data, dict)
Patrick Williams20f38712022-12-08 06:18:26 -06001470 elif type == "tuple":
George Keishingde79a9b2021-08-12 16:14:43 -05001471 return isinstance(data, tuple)
1472 else:
1473 self.logger.info("\tInvalid data type requested: %s" % type)
Patrick Williams20f38712022-12-08 06:18:26 -06001474 return "INVALID"