blob: 6044e5edcf58f1233bb6cdd063bb7fd0b0cac02e [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:
57 print("PLUGIN: Module import failed: %s" % module)
58 pass
59except FileNotFoundError as e:
60 print("PLUGIN: %s" % e)
61 pass
62
63r"""
64This is for plugin functions returning data or responses to the caller
65in YAML plugin setup.
66
67Example:
68
69 - plugin:
70 - plugin_name: version = plugin.ssh_execution.ssh_execute_cmd
71 - plugin_args:
72 - ${hostname}
73 - ${username}
74 - ${password}
75 - "cat /etc/os-release | grep VERSION_ID | awk -F'=' '{print $2}'"
76 - plugin:
77 - plugin_name: plugin.print_vars.print_vars
78 - plugin_args:
79 - version
80
81where first plugin "version" var is used by another plugin in the YAML
82block or plugin
83
84"""
85global global_log_store_path
86global global_plugin_dict
87global global_plugin_list
George Keishing9348b402021-08-13 12:22:35 -050088
George Keishing0581cb02021-08-05 15:08:58 -050089# Hold the plugin return values in dict and plugin return vars in list.
George Keishing9348b402021-08-13 12:22:35 -050090# Dict is to reference and update vars processing in parser where as
91# list is for current vars from the plugin block which needs processing.
George Keishingb97a9042021-07-29 07:41:20 -050092global_plugin_dict = {}
93global_plugin_list = []
George Keishing9348b402021-08-13 12:22:35 -050094
George Keishingc754b432025-04-24 14:27:14 +053095# Hold the plugin return named declared if function returned values are
96# list,dict.
George Keishing0581cb02021-08-05 15:08:58 -050097# Refer this name list to look up the plugin dict for eval() args function
George Keishing9348b402021-08-13 12:22:35 -050098# Example ['version']
George Keishing0581cb02021-08-05 15:08:58 -050099global_plugin_type_list = []
George Keishing9348b402021-08-13 12:22:35 -0500100
101# Path where logs are to be stored or written.
Patrick Williams20f38712022-12-08 06:18:26 -0600102global_log_store_path = ""
George Keishingb97a9042021-07-29 07:41:20 -0500103
George Keishing1e7b0182021-08-06 14:05:54 -0500104# Plugin error state defaults.
105plugin_error_dict = {
Patrick Williams20f38712022-12-08 06:18:26 -0600106 "exit_on_error": False,
107 "continue_on_error": False,
George Keishing1e7b0182021-08-06 14:05:54 -0500108}
109
Peter D Phan72ce6b82021-06-03 06:18:26 -0500110
Peter D Phan5e56f522021-12-20 13:19:41 -0600111class ffdc_collector:
Peter D Phan72ce6b82021-06-03 06:18:26 -0500112 r"""
George Keishing1e7b0182021-08-06 14:05:54 -0500113 Execute commands from configuration file to collect log files.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500114 Fetch and store generated files at the specified location.
115
116 """
117
Patrick Williams20f38712022-12-08 06:18:26 -0600118 def __init__(
119 self,
120 hostname,
121 username,
122 password,
George Keishing7a61aa22023-06-26 13:18:37 +0530123 port_ssh,
George Keishinge8a41752023-06-22 21:42:47 +0530124 port_https,
125 port_ipmi,
Patrick Williams20f38712022-12-08 06:18:26 -0600126 ffdc_config,
127 location,
128 remote_type,
129 remote_protocol,
130 env_vars,
131 econfig,
132 log_level,
133 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500134 r"""
135 Description of argument(s):
136
George Keishingc754b432025-04-24 14:27:14 +0530137 hostname Name/ip of the targeted (remote) system
138 username User on the targeted system with access to
139 FFDC files
140 password Password for user on targeted system
George Keishing7a61aa22023-06-26 13:18:37 +0530141 port_ssh SSH port value. By default 22
George Keishinge8a41752023-06-22 21:42:47 +0530142 port_https HTTPS port value. By default 443
143 port_ipmi IPMI port value. By default 623
George Keishingc754b432025-04-24 14:27:14 +0530144 ffdc_config Configuration file listing commands and files
145 for FFDC
146 location Where to store collected FFDC
147 remote_type OS type of the remote host
George Keishing8e94f8c2021-07-23 15:06:32 -0500148 remote_protocol Protocol to use to collect data
149 env_vars User define CLI env vars '{"key : "value"}'
150 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -0500151
152 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500153
154 self.hostname = hostname
155 self.username = username
156 self.password = password
George Keishing7a61aa22023-06-26 13:18:37 +0530157 self.port_ssh = str(port_ssh)
George Keishinge8a41752023-06-22 21:42:47 +0530158 self.port_https = str(port_https)
159 self.port_ipmi = str(port_ipmi)
Peter D Phane86d9a52021-07-15 10:42:25 -0500160 self.ffdc_config = ffdc_config
161 self.location = location + "/" + remote_type.upper()
162 self.ssh_remoteclient = None
163 self.telnet_remoteclient = None
164 self.ffdc_dir_path = ""
165 self.ffdc_prefix = ""
166 self.target_type = remote_type.upper()
167 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -0500168 self.env_vars = env_vars
169 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -0500170 self.start_time = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600171 self.elapsed_time = ""
Peter D Phane86d9a52021-07-15 10:42:25 -0500172 self.logger = None
173
174 # Set prefix values for scp files and directory.
George Keishingc754b432025-04-24 14:27:14 +0530175 # Since the time stamp is at second granularity, these values are set
176 # here to be sure that all files for this run will have same timestamps
Peter D Phane86d9a52021-07-15 10:42:25 -0500177 # and they will be saved in the same directory.
178 # self.location == local system for now
Peter D Phan5e56f522021-12-20 13:19:41 -0600179 self.set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500180
Peter D Phan5e56f522021-12-20 13:19:41 -0600181 # Logger for this run. Need to be after set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500182 self.script_logging(getattr(logging, log_level.upper()))
183
184 # Verify top level directory exists for storage
185 self.validate_local_store(self.location)
186
Peter D Phan72ce6b82021-06-03 06:18:26 -0500187 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -0500188 # Load default or user define YAML configuration file.
Patrick Williams20f38712022-12-08 06:18:26 -0600189 with open(self.ffdc_config, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -0500190 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -0700191 self.ffdc_actions = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -0500192 except yaml.YAMLError as e:
193 self.logger.error(e)
194 sys.exit(-1)
Peter D Phane86d9a52021-07-15 10:42:25 -0500195
196 if self.target_type not in self.ffdc_actions.keys():
197 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600198 "\n\tERROR: %s is not listed in %s.\n\n"
199 % (self.target_type, self.ffdc_config)
200 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500201 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500202 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500203 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500204
George Keishing4885b2f2021-07-21 15:22:45 -0500205 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500206 self.logger.info("\n\tENV: User define input YAML variables")
207 self.env_dict = {}
Peter D Phan5e56f522021-12-20 13:19:41 -0600208 self.load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500209
Peter D Phan72ce6b82021-06-03 06:18:26 -0500210 def verify_script_env(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500211 # Import to log version
212 import click
213 import paramiko
214
215 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500216
George Keishingd805bc02025-02-28 12:17:13 +0530217 try:
218 redfishtool_version = (
219 self.run_tool_cmd("redfishtool -V").split(" ")[2].strip("\n")
220 )
221 except Exception as e:
222 self.logger.error("\tEXCEPTION redfishtool: %s", e)
223 redfishtool_version = "Not Installed (optional)"
224
225 try:
226 ipmitool_version = self.run_tool_cmd("ipmitool -V").split(" ")[2]
227 except Exception as e:
228 self.logger.error("\tEXCEPTION ipmitool: %s", e)
229 ipmitool_version = "Not Installed (optional)"
Peter D Phan0c669772021-06-24 13:52:42 -0500230
Peter D Phane86d9a52021-07-15 10:42:25 -0500231 self.logger.info("\n\t---- Script host environment ----")
Patrick Williams20f38712022-12-08 06:18:26 -0600232 self.logger.info(
233 "\t{:<10} {:<10}".format("Script hostname", os.uname()[1])
234 )
235 self.logger.info(
236 "\t{:<10} {:<10}".format("Script host os", platform.platform())
237 )
238 self.logger.info(
239 "\t{:<10} {:>10}".format("Python", platform.python_version())
240 )
241 self.logger.info("\t{:<10} {:>10}".format("PyYAML", yaml.__version__))
242 self.logger.info("\t{:<10} {:>10}".format("click", click.__version__))
243 self.logger.info(
244 "\t{:<10} {:>10}".format("paramiko", paramiko.__version__)
245 )
246 self.logger.info(
247 "\t{:<10} {:>9}".format("redfishtool", redfishtool_version)
248 )
249 self.logger.info(
250 "\t{:<10} {:>12}".format("ipmitool", ipmitool_version)
251 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500252
Patrick Williams20f38712022-12-08 06:18:26 -0600253 if eval(yaml.__version__.replace(".", ",")) < (5, 3, 0):
254 self.logger.error(
255 "\n\tERROR: Python or python packages do not meet minimum"
256 " version requirement."
257 )
258 self.logger.error(
259 "\tERROR: PyYAML version 5.3.0 or higher is needed.\n"
260 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500261 run_env_ok = False
262
Peter D Phane86d9a52021-07-15 10:42:25 -0500263 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500264 return run_env_ok
265
Patrick Williams20f38712022-12-08 06:18:26 -0600266 def script_logging(self, log_level_attr):
Peter D Phane86d9a52021-07-15 10:42:25 -0500267 r"""
268 Create logger
269
270 """
271 self.logger = logging.getLogger()
272 self.logger.setLevel(log_level_attr)
Patrick Williams20f38712022-12-08 06:18:26 -0600273 log_file_handler = logging.FileHandler(
274 self.ffdc_dir_path + "collector.log"
275 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500276
277 stdout_handler = logging.StreamHandler(sys.stdout)
278 self.logger.addHandler(log_file_handler)
279 self.logger.addHandler(stdout_handler)
280
281 # Turn off paramiko INFO logging
282 logging.getLogger("paramiko").setLevel(logging.WARNING)
283
Peter D Phan72ce6b82021-06-03 06:18:26 -0500284 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500285 r"""
286 Check if target system is ping-able.
287
288 """
George Keishing0662e942021-07-13 05:12:20 -0500289 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500290 if response == 0:
Patrick Williams20f38712022-12-08 06:18:26 -0600291 self.logger.info(
292 "\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname
293 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500294 return True
295 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500296 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600297 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n"
298 % self.hostname
299 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500300 sys.exit(-1)
301
Peter D Phan72ce6b82021-06-03 06:18:26 -0500302 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500303 r"""
304 Initiate FFDC Collection depending on requested protocol.
305
306 """
307
Patrick Williams20f38712022-12-08 06:18:26 -0600308 self.logger.info(
309 "\n\t---- Start communicating with %s ----" % self.hostname
310 )
Peter D Phan7610bc42021-07-06 06:31:05 -0500311 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500312
George Keishingf5a57502021-07-22 16:43:47 -0500313 # Find the list of target and protocol supported.
314 check_protocol_list = []
315 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500316
George Keishingf5a57502021-07-22 16:43:47 -0500317 for target_type in config_dict.keys():
318 if self.target_type != target_type:
319 continue
George Keishingeafba182021-06-29 13:44:58 -0500320
George Keishingf5a57502021-07-22 16:43:47 -0500321 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600322 if (
323 config_dict[target_type][k]["PROTOCOL"][0]
324 not in check_protocol_list
325 ):
326 check_protocol_list.append(
327 config_dict[target_type][k]["PROTOCOL"][0]
328 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500329
Patrick Williams20f38712022-12-08 06:18:26 -0600330 self.logger.info(
331 "\n\t %s protocol type: %s"
332 % (self.target_type, check_protocol_list)
333 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500334
George Keishingf5a57502021-07-22 16:43:47 -0500335 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500336
George Keishingf5a57502021-07-22 16:43:47 -0500337 if verified_working_protocol:
Patrick Williams20f38712022-12-08 06:18:26 -0600338 self.logger.info(
339 "\n\t---- Completed protocol pre-requisite check ----\n"
340 )
Peter D Phan0c669772021-06-24 13:52:42 -0500341
George Keishingf5a57502021-07-22 16:43:47 -0500342 # Verify top level directory exists for storage
343 self.validate_local_store(self.location)
344
Patrick Williams20f38712022-12-08 06:18:26 -0600345 if (self.remote_protocol not in verified_working_protocol) and (
346 self.remote_protocol != "ALL"
347 ):
348 self.logger.info(
349 "\n\tWorking protocol list: %s" % verified_working_protocol
350 )
George Keishingf5a57502021-07-22 16:43:47 -0500351 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600352 "\tERROR: Requested protocol %s is not in working protocol"
George Keishing7899a452023-02-15 02:46:54 -0600353 " list.\n" % self.remote_protocol
Patrick Williams20f38712022-12-08 06:18:26 -0600354 )
George Keishingf5a57502021-07-22 16:43:47 -0500355 sys.exit(-1)
356 else:
357 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500358
359 def ssh_to_target_system(self):
360 r"""
361 Open a ssh connection to targeted system.
362
363 """
364
Patrick Williams20f38712022-12-08 06:18:26 -0600365 self.ssh_remoteclient = SSHRemoteclient(
George Keishing7a61aa22023-06-26 13:18:37 +0530366 self.hostname, self.username, self.password, self.port_ssh
Patrick Williams20f38712022-12-08 06:18:26 -0600367 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500368
Peter D Phan5963d632021-07-12 09:58:55 -0500369 if self.ssh_remoteclient.ssh_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600370 self.logger.info(
371 "\n\t[Check] %s SSH connection established.\t [OK]"
372 % self.hostname
373 )
Peter D Phan733df632021-06-17 13:13:36 -0500374
Peter D Phan5963d632021-07-12 09:58:55 -0500375 # Check scp connection.
376 # If scp connection fails,
377 # continue with FFDC generation but skip scp files to local host.
378 self.ssh_remoteclient.scp_connection()
379 return True
380 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600381 self.logger.info(
382 "\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]"
383 % self.hostname
384 )
Peter D Phan5963d632021-07-12 09:58:55 -0500385 return False
386
387 def telnet_to_target_system(self):
388 r"""
389 Open a telnet connection to targeted system.
390 """
Patrick Williams20f38712022-12-08 06:18:26 -0600391 self.telnet_remoteclient = TelnetRemoteclient(
392 self.hostname, self.username, self.password
393 )
Peter D Phan5963d632021-07-12 09:58:55 -0500394 if self.telnet_remoteclient.tn_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600395 self.logger.info(
396 "\n\t[Check] %s Telnet connection established.\t [OK]"
397 % self.hostname
398 )
Peter D Phan5963d632021-07-12 09:58:55 -0500399 return True
400 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600401 self.logger.info(
402 "\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]"
403 % self.hostname
404 )
Peter D Phan5963d632021-07-12 09:58:55 -0500405 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500406
George Keishing772c9772021-06-16 23:23:42 -0500407 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500408 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500409 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500410
Peter D Phan04aca3b2021-06-21 10:37:18 -0500411 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530412 working_protocol_list List of confirmed working protocols to
413 connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500414 """
415
Patrick Williams20f38712022-12-08 06:18:26 -0600416 self.logger.info(
417 "\n\t---- Executing commands on " + self.hostname + " ----"
418 )
419 self.logger.info(
420 "\n\tWorking protocol list: %s" % working_protocol_list
421 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500422
George Keishingf5a57502021-07-22 16:43:47 -0500423 config_dict = self.ffdc_actions
424 for target_type in config_dict.keys():
425 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500426 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500427
Peter D Phane86d9a52021-07-15 10:42:25 -0500428 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
Patrick Williams20f38712022-12-08 06:18:26 -0600429 global_plugin_dict["global_log_store_path"] = self.ffdc_dir_path
George Keishingf5a57502021-07-22 16:43:47 -0500430 self.logger.info("\tSystem Type: %s" % target_type)
431 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600432 if (
433 self.remote_protocol not in working_protocol_list
434 and self.remote_protocol != "ALL"
435 ):
George Keishing6ea92b02021-07-01 11:20:50 -0500436 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500437
Patrick Williams20f38712022-12-08 06:18:26 -0600438 protocol = config_dict[target_type][k]["PROTOCOL"][0]
George Keishingf5a57502021-07-22 16:43:47 -0500439
440 if protocol not in working_protocol_list:
441 continue
442
George Keishingb7607612021-07-27 13:31:23 -0500443 if protocol in working_protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -0600444 if protocol == "SSH" or protocol == "SCP":
George Keishing12fd0652021-07-27 13:57:11 -0500445 self.protocol_ssh(protocol, target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600446 elif protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -0500447 self.protocol_telnet(target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600448 elif (
449 protocol == "REDFISH"
450 or protocol == "IPMI"
451 or protocol == "SHELL"
452 ):
George Keishing506b0582021-07-27 09:31:22 -0500453 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500454 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600455 self.logger.error(
456 "\n\tERROR: %s is not available for %s."
457 % (protocol, self.hostname)
458 )
George Keishingeafba182021-06-29 13:44:58 -0500459
Peter D Phan04aca3b2021-06-21 10:37:18 -0500460 # Close network connection after collecting all files
Patrick Williams20f38712022-12-08 06:18:26 -0600461 self.elapsed_time = time.strftime(
462 "%H:%M:%S", time.gmtime(time.time() - self.start_time)
463 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500464 if self.ssh_remoteclient:
465 self.ssh_remoteclient.ssh_remoteclient_disconnect()
466 if self.telnet_remoteclient:
467 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500468
Patrick Williams20f38712022-12-08 06:18:26 -0600469 def protocol_ssh(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500470 r"""
471 Perform actions using SSH and SCP protocols.
472
473 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500474 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500475 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500476 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500477 """
478
Patrick Williams20f38712022-12-08 06:18:26 -0600479 if protocol == "SCP":
George Keishingf5a57502021-07-22 16:43:47 -0500480 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500481 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600482 self.collect_and_copy_ffdc(
483 self.ffdc_actions[target_type][sub_type]
484 )
Peter D Phan0c669772021-06-24 13:52:42 -0500485
Patrick Williams20f38712022-12-08 06:18:26 -0600486 def protocol_telnet(self, target_type, sub_type):
Peter D Phan5963d632021-07-12 09:58:55 -0500487 r"""
488 Perform actions using telnet protocol.
489 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500490 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500491 """
Patrick Williams20f38712022-12-08 06:18:26 -0600492 self.logger.info(
493 "\n\t[Run] Executing commands on %s using %s"
494 % (self.hostname, "TELNET")
495 )
Peter D Phan5963d632021-07-12 09:58:55 -0500496 telnet_files_saved = []
497 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600498 list_of_commands = self.ffdc_actions[target_type][sub_type]["COMMANDS"]
Peter D Phan5963d632021-07-12 09:58:55 -0500499 for index, each_cmd in enumerate(list_of_commands, start=0):
500 command_txt, command_timeout = self.unpack_command(each_cmd)
Patrick Williams20f38712022-12-08 06:18:26 -0600501 result = self.telnet_remoteclient.execute_command(
502 command_txt, command_timeout
503 )
Peter D Phan5963d632021-07-12 09:58:55 -0500504 if result:
505 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600506 targ_file = self.ffdc_actions[target_type][sub_type][
507 "FILES"
508 ][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500509 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500510 targ_file = command_txt
511 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600512 "\n\t[WARN] Missing filename to store data from"
513 " telnet %s." % each_cmd
514 )
515 self.logger.warning(
516 "\t[WARN] Data will be stored in %s." % targ_file
517 )
518 targ_file_with_path = (
519 self.ffdc_dir_path + self.ffdc_prefix + targ_file
520 )
Peter D Phan5963d632021-07-12 09:58:55 -0500521 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600522 with open(targ_file_with_path, "w") as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500523 fp.write(result)
524 fp.close
525 telnet_files_saved.append(targ_file)
526 progress_counter += 1
527 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500528 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500529 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500530 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500531
Patrick Williams20f38712022-12-08 06:18:26 -0600532 def protocol_execute(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500533 r"""
George Keishing506b0582021-07-27 09:31:22 -0500534 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500535
536 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500537 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500538 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500539 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500540 """
541
Patrick Williams20f38712022-12-08 06:18:26 -0600542 self.logger.info(
543 "\n\t[Run] Executing commands to %s using %s"
544 % (self.hostname, protocol)
545 )
George Keishing506b0582021-07-27 09:31:22 -0500546 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500547 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600548 list_of_cmd = self.get_command_list(
549 self.ffdc_actions[target_type][sub_type]
550 )
George Keishingeafba182021-06-29 13:44:58 -0500551 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500552 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500553 if isinstance(each_cmd, dict):
Patrick Williams20f38712022-12-08 06:18:26 -0600554 if "plugin" in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500555 # If the error is set and plugin explicitly
556 # requested to skip execution on error..
Patrick Williams20f38712022-12-08 06:18:26 -0600557 if plugin_error_dict[
558 "exit_on_error"
559 ] and self.plugin_error_check(each_cmd["plugin"]):
560 self.logger.info(
561 "\n\t[PLUGIN-ERROR] exit_on_error: %s"
562 % plugin_error_dict["exit_on_error"]
563 )
564 self.logger.info(
565 "\t[PLUGIN-SKIP] %s" % each_cmd["plugin"][0]
566 )
George Keishing1e7b0182021-08-06 14:05:54 -0500567 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500568 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500569 # call the plugin
570 self.logger.info("\n\t[PLUGIN-START]")
Patrick Williams20f38712022-12-08 06:18:26 -0600571 result = self.execute_plugin_block(each_cmd["plugin"])
George Keishingb97a9042021-07-29 07:41:20 -0500572 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500573 else:
George Keishing2b83e042021-08-03 12:56:11 -0500574 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500575
George Keishingcaa97e62021-08-03 14:00:09 -0500576 if not plugin_call:
577 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500578 if result:
579 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600580 file_name = self.get_file_list(
581 self.ffdc_actions[target_type][sub_type]
582 )[index]
George Keishingb97a9042021-07-29 07:41:20 -0500583 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500584 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500585 continue
Patrick Williams20f38712022-12-08 06:18:26 -0600586 targ_file = self.yaml_env_and_plugin_vars_populate(
587 file_name
588 )
George Keishingeafba182021-06-29 13:44:58 -0500589 except IndexError:
Patrick Williams20f38712022-12-08 06:18:26 -0600590 targ_file = each_cmd.split("/")[-1]
George Keishing506b0582021-07-27 09:31:22 -0500591 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600592 "\n\t[WARN] Missing filename to store data from %s."
593 % each_cmd
594 )
595 self.logger.warning(
596 "\t[WARN] Data will be stored in %s." % targ_file
597 )
George Keishingeafba182021-06-29 13:44:58 -0500598
Patrick Williams20f38712022-12-08 06:18:26 -0600599 targ_file_with_path = (
600 self.ffdc_dir_path + self.ffdc_prefix + targ_file
601 )
George Keishingeafba182021-06-29 13:44:58 -0500602
603 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600604 with open(targ_file_with_path, "w") as fp:
George Keishing91308ea2021-08-10 14:43:15 -0500605 if isinstance(result, dict):
606 fp.write(json.dumps(result))
607 else:
608 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500609 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500610 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500611
612 progress_counter += 1
613 self.print_progress(progress_counter)
614
Peter D Phane86d9a52021-07-15 10:42:25 -0500615 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500616
George Keishing506b0582021-07-27 09:31:22 -0500617 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500618 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500619
Patrick Williams20f38712022-12-08 06:18:26 -0600620 def collect_and_copy_ffdc(
621 self, ffdc_actions_for_target_type, form_filename=False
622 ):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500623 r"""
624 Send commands in ffdc_config file to targeted system.
625
626 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530627 ffdc_actions_for_target_type Commands and files for the selected
628 remote host type.
629 form_filename If true, pre-pend self.target_type to
630 filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500631 """
632
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500633 # Executing commands, if any
Patrick Williams20f38712022-12-08 06:18:26 -0600634 self.ssh_execute_ffdc_commands(
635 ffdc_actions_for_target_type, form_filename
636 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500637
Peter D Phan3beb02e2021-07-06 13:25:17 -0500638 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500639 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600640 self.logger.info(
641 "\n\n\tCopying FFDC files from remote system %s.\n"
642 % self.hostname
643 )
Peter D Phan2b8052d2021-06-22 10:55:41 -0500644
Peter D Phan04aca3b2021-06-21 10:37:18 -0500645 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500646 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Patrick Williams20f38712022-12-08 06:18:26 -0600647 self.scp_ffdc(
648 self.ffdc_dir_path,
649 self.ffdc_prefix,
650 form_filename,
651 list_of_files,
652 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500653 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600654 self.logger.info(
655 "\n\n\tSkip copying FFDC files from remote system %s.\n"
656 % self.hostname
657 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500658
Patrick Williams20f38712022-12-08 06:18:26 -0600659 def get_command_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500660 r"""
661 Fetch list of commands from configuration file
662
663 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530664 ffdc_actions_for_target_type Commands and files for the selected
665 remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500666 """
667 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600668 list_of_commands = ffdc_actions_for_target_type["COMMANDS"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500669 except KeyError:
670 list_of_commands = []
671 return list_of_commands
672
Patrick Williams20f38712022-12-08 06:18:26 -0600673 def get_file_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500674 r"""
675 Fetch list of commands from configuration file
676
677 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530678 ffdc_actions_for_target_type Commands and files for the selected
679 remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500680 """
681 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600682 list_of_files = ffdc_actions_for_target_type["FILES"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500683 except KeyError:
684 list_of_files = []
685 return list_of_files
686
Patrick Williams20f38712022-12-08 06:18:26 -0600687 def unpack_command(self, command):
Peter D Phan5963d632021-07-12 09:58:55 -0500688 r"""
689 Unpack command from config file
690
691 Description of argument(s):
692 command Command from config file.
693 """
694 if isinstance(command, dict):
695 command_txt = next(iter(command))
696 command_timeout = next(iter(command.values()))
697 elif isinstance(command, str):
698 command_txt = command
699 # Default command timeout 60 seconds
700 command_timeout = 60
701
702 return command_txt, command_timeout
703
Patrick Williams20f38712022-12-08 06:18:26 -0600704 def ssh_execute_ffdc_commands(
705 self, ffdc_actions_for_target_type, form_filename=False
706 ):
Peter D Phan3beb02e2021-07-06 13:25:17 -0500707 r"""
708 Send commands in ffdc_config file to targeted system.
709
710 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530711 ffdc_actions_for_target_type Commands and files for the selected
712 remote host type.
713 form_filename If true, pre-pend self.target_type to
714 filename
Peter D Phan3beb02e2021-07-06 13:25:17 -0500715 """
Patrick Williams20f38712022-12-08 06:18:26 -0600716 self.logger.info(
717 "\n\t[Run] Executing commands on %s using %s"
718 % (self.hostname, ffdc_actions_for_target_type["PROTOCOL"][0])
719 )
Peter D Phan3beb02e2021-07-06 13:25:17 -0500720
George Keishingf5a57502021-07-22 16:43:47 -0500721 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500722 # If command list is empty, returns
723 if not list_of_commands:
724 return
725
726 progress_counter = 0
727 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500728 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500729
730 if form_filename:
731 command_txt = str(command_txt % self.target_type)
732
Patrick Williams20f38712022-12-08 06:18:26 -0600733 (
734 cmd_exit_code,
735 err,
736 response,
737 ) = self.ssh_remoteclient.execute_command(
738 command_txt, command_timeout
739 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500740
741 if cmd_exit_code:
742 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600743 "\n\t\t[WARN] %s exits with code %s."
744 % (command_txt, str(cmd_exit_code))
745 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500746 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500747
Peter D Phan3beb02e2021-07-06 13:25:17 -0500748 progress_counter += 1
749 self.print_progress(progress_counter)
750
Peter D Phane86d9a52021-07-15 10:42:25 -0500751 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500752
Patrick Williams20f38712022-12-08 06:18:26 -0600753 def group_copy(self, ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500754 r"""
755 scp group of files (wild card) from remote host.
756
757 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530758 fdc_actions_for_target_type Commands and files for the selected
759 remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500760 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500761
Peter D Phan5963d632021-07-12 09:58:55 -0500762 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600763 self.logger.info(
764 "\n\tCopying files from remote system %s via SCP.\n"
765 % self.hostname
766 )
Peter D Phan56429a62021-06-23 08:38:29 -0500767
Patrick Williams20f38712022-12-08 06:18:26 -0600768 list_of_commands = self.get_command_list(
769 ffdc_actions_for_target_type
770 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500771 # If command list is empty, returns
772 if not list_of_commands:
773 return
Peter D Phan56429a62021-06-23 08:38:29 -0500774
Peter D Phanbabf2962021-07-07 11:24:40 -0500775 for command in list_of_commands:
776 try:
George Keishingb4540e72021-08-02 13:48:46 -0500777 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500778 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500779 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500780 continue
781
Patrick Williams20f38712022-12-08 06:18:26 -0600782 (
783 cmd_exit_code,
784 err,
785 response,
786 ) = self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500787
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500788 # If file does not exist, code take no action.
789 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500790 if response:
Patrick Williams20f38712022-12-08 06:18:26 -0600791 scp_result = self.ssh_remoteclient.scp_file_from_remote(
792 response.split("\n"), self.ffdc_dir_path
793 )
Peter D Phan56429a62021-06-23 08:38:29 -0500794 if scp_result:
Patrick Williams20f38712022-12-08 06:18:26 -0600795 self.logger.info(
796 "\t\tSuccessfully copied from "
797 + self.hostname
798 + ":"
799 + command
800 )
Peter D Phan56429a62021-06-23 08:38:29 -0500801 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500802 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500803
804 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600805 self.logger.info(
806 "\n\n\tSkip copying files from remote system %s.\n"
807 % self.hostname
808 )
Peter D Phan56429a62021-06-23 08:38:29 -0500809
Patrick Williams20f38712022-12-08 06:18:26 -0600810 def scp_ffdc(
811 self,
812 targ_dir_path,
813 targ_file_prefix,
814 form_filename,
815 file_list=None,
816 quiet=None,
817 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500818 r"""
George Keishingc754b432025-04-24 14:27:14 +0530819 SCP all files in file_dict to the indicated directory on the local
820 system.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500821
822 Description of argument(s):
George Keishingc754b432025-04-24 14:27:14 +0530823 targ_dir_path The path of the directory to receive
824 the files.
George Keishinge16f1582022-12-15 07:32:21 -0600825 targ_file_prefix Prefix which will be prepended to each
Peter D Phan72ce6b82021-06-03 06:18:26 -0500826 target file's name.
George Keishingc754b432025-04-24 14:27:14 +0530827 file_dict A dictionary of files to scp from
828 targeted system to this system
Peter D Phan72ce6b82021-06-03 06:18:26 -0500829
830 """
831
Peter D Phan72ce6b82021-06-03 06:18:26 -0500832 progress_counter = 0
833 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500834 if form_filename:
835 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500836 source_file_path = filename
Patrick Williams20f38712022-12-08 06:18:26 -0600837 targ_file_path = (
838 targ_dir_path + targ_file_prefix + filename.split("/")[-1]
839 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500840
Peter D Phanbabf2962021-07-07 11:24:40 -0500841 # If source file name contains wild card, copy filename as is.
Patrick Williams20f38712022-12-08 06:18:26 -0600842 if "*" in source_file_path:
843 scp_result = self.ssh_remoteclient.scp_file_from_remote(
844 source_file_path, self.ffdc_dir_path
845 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500846 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600847 scp_result = self.ssh_remoteclient.scp_file_from_remote(
848 source_file_path, targ_file_path
849 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500850
851 if not quiet:
852 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500853 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600854 "\t\tSuccessfully copied from "
855 + self.hostname
856 + ":"
857 + source_file_path
858 + ".\n"
859 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500860 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500861 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600862 "\t\tFail to copy from "
863 + self.hostname
864 + ":"
865 + source_file_path
866 + ".\n"
867 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500868 else:
869 progress_counter += 1
870 self.print_progress(progress_counter)
871
Peter D Phan5e56f522021-12-20 13:19:41 -0600872 def set_ffdc_default_store_path(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500873 r"""
874 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
George Keishingc754b432025-04-24 14:27:14 +0530875 Collected ffdc file will be stored in dir
876 /self.location/hostname_timestr/.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500877 Individual ffdc file will have timestr_filename.
878
879 Description of class variables:
George Keishingc754b432025-04-24 14:27:14 +0530880 self.ffdc_dir_path The dir path where collected ffdc data files
881 should be put.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500882
883 self.ffdc_prefix The prefix to be given to each ffdc file name.
884
885 """
886
887 timestr = time.strftime("%Y%m%d-%H%M%S")
Patrick Williams20f38712022-12-08 06:18:26 -0600888 self.ffdc_dir_path = (
889 self.location + "/" + self.hostname + "_" + timestr + "/"
890 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500891 self.ffdc_prefix = timestr + "_"
892 self.validate_local_store(self.ffdc_dir_path)
893
Peter D Phan5e56f522021-12-20 13:19:41 -0600894 # Need to verify local store path exists prior to instantiate this class.
895 # This class method is used to share the same code between CLI input parm
896 # and Robot Framework "${EXECDIR}/logs" before referencing this class.
897 @classmethod
898 def validate_local_store(cls, dir_path):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500899 r"""
900 Ensure path exists to store FFDC files locally.
901
902 Description of variable:
903 dir_path The dir path where collected ffdc data files will be stored.
904
905 """
906
907 if not os.path.exists(dir_path):
908 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500909 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500910 except (IOError, OSError) as e:
911 # PermissionError
912 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500913 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600914 "\tERROR: os.makedirs %s failed with"
915 " PermissionError.\n" % dir_path
916 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500917 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500918 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600919 "\tERROR: os.makedirs %s failed with %s.\n"
920 % (dir_path, e.strerror)
921 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500922 sys.exit(-1)
923
924 def print_progress(self, progress):
925 r"""
926 Print activity progress +
927
928 Description of variable:
929 progress Progress counter.
930
931 """
932
933 sys.stdout.write("\r\t" + "+" * progress)
934 sys.stdout.flush()
Patrick Williams20f38712022-12-08 06:18:26 -0600935 time.sleep(0.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500936
937 def verify_redfish(self):
938 r"""
939 Verify remote host has redfish service active
940
941 """
Patrick Williams20f38712022-12-08 06:18:26 -0600942 redfish_parm = (
943 "redfishtool -r "
944 + self.hostname
George Keishing7a61aa22023-06-26 13:18:37 +0530945 + ":"
946 + self.port_https
Patrick Williams20f38712022-12-08 06:18:26 -0600947 + " -S Always raw GET /redfish/v1/"
948 )
949 return self.run_tool_cmd(redfish_parm, True)
Peter D Phan0c669772021-06-24 13:52:42 -0500950
George Keishingeafba182021-06-29 13:44:58 -0500951 def verify_ipmi(self):
952 r"""
953 Verify remote host has IPMI LAN service active
954
955 """
Patrick Williams20f38712022-12-08 06:18:26 -0600956 if self.target_type == "OPENBMC":
957 ipmi_parm = (
958 "ipmitool -I lanplus -C 17 -U "
959 + self.username
960 + " -P "
961 + self.password
962 + " -H "
963 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530964 + " -p "
965 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600966 + " power status"
967 )
George Keishing484f8242021-07-27 01:42:02 -0500968 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600969 ipmi_parm = (
970 "ipmitool -I lanplus -P "
971 + self.password
972 + " -H "
973 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530974 + " -p "
975 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600976 + " power status"
977 )
George Keishing484f8242021-07-27 01:42:02 -0500978
Patrick Williams20f38712022-12-08 06:18:26 -0600979 return self.run_tool_cmd(ipmi_parm, True)
George Keishingeafba182021-06-29 13:44:58 -0500980
Patrick Williams20f38712022-12-08 06:18:26 -0600981 def run_tool_cmd(self, parms_string, quiet=False):
George Keishingeafba182021-06-29 13:44:58 -0500982 r"""
George Keishing506b0582021-07-27 09:31:22 -0500983 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500984
985 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500986 parms_string tool command options.
987 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500988 """
989
Patrick Williams20f38712022-12-08 06:18:26 -0600990 result = subprocess.run(
991 [parms_string],
992 stdout=subprocess.PIPE,
993 stderr=subprocess.PIPE,
994 shell=True,
995 universal_newlines=True,
996 )
George Keishingeafba182021-06-29 13:44:58 -0500997
998 if result.stderr and not quiet:
Patrick Williams20f38712022-12-08 06:18:26 -0600999 self.logger.error("\n\t\tERROR with %s " % parms_string)
1000 self.logger.error("\t\t" + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -05001001
1002 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -05001003
George Keishingf5a57502021-07-22 16:43:47 -05001004 def verify_protocol(self, protocol_list):
1005 r"""
1006 Perform protocol working check.
1007
1008 Description of argument(s):
1009 protocol_list List of protocol.
1010 """
1011
1012 tmp_list = []
1013 if self.target_is_pingable():
1014 tmp_list.append("SHELL")
1015
1016 for protocol in protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -06001017 if self.remote_protocol != "ALL":
George Keishingf5a57502021-07-22 16:43:47 -05001018 if self.remote_protocol != protocol:
1019 continue
1020
1021 # Only check SSH/SCP once for both protocols
Patrick Williams20f38712022-12-08 06:18:26 -06001022 if (
1023 protocol == "SSH"
1024 or protocol == "SCP"
1025 and protocol not in tmp_list
1026 ):
George Keishingf5a57502021-07-22 16:43:47 -05001027 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -05001028 # Add only what user asked.
Patrick Williams20f38712022-12-08 06:18:26 -06001029 if self.remote_protocol != "ALL":
George Keishingaa638702021-07-26 11:48:28 -05001030 tmp_list.append(self.remote_protocol)
1031 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001032 tmp_list.append("SSH")
1033 tmp_list.append("SCP")
George Keishingf5a57502021-07-22 16:43:47 -05001034
Patrick Williams20f38712022-12-08 06:18:26 -06001035 if protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -05001036 if self.telnet_to_target_system():
1037 tmp_list.append(protocol)
1038
Patrick Williams20f38712022-12-08 06:18:26 -06001039 if protocol == "REDFISH":
George Keishingf5a57502021-07-22 16:43:47 -05001040 if self.verify_redfish():
1041 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001042 self.logger.info(
1043 "\n\t[Check] %s Redfish Service.\t\t [OK]"
1044 % self.hostname
1045 )
George Keishingf5a57502021-07-22 16:43:47 -05001046 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001047 self.logger.info(
1048 "\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]"
1049 % self.hostname
1050 )
George Keishingf5a57502021-07-22 16:43:47 -05001051
Patrick Williams20f38712022-12-08 06:18:26 -06001052 if protocol == "IPMI":
George Keishingf5a57502021-07-22 16:43:47 -05001053 if self.verify_ipmi():
1054 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001055 self.logger.info(
1056 "\n\t[Check] %s IPMI LAN Service.\t\t [OK]"
1057 % self.hostname
1058 )
George Keishingf5a57502021-07-22 16:43:47 -05001059 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001060 self.logger.info(
1061 "\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]"
1062 % self.hostname
1063 )
George Keishingf5a57502021-07-22 16:43:47 -05001064
1065 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -05001066
1067 def load_env(self):
1068 r"""
1069 Perform protocol working check.
1070
1071 """
George Keishingc754b432025-04-24 14:27:14 +05301072 # This is for the env vars a user can use in YAML to load
1073 # it at runtime.
George Keishinge1686752021-07-27 12:55:28 -05001074 # Example YAML:
1075 # -COMMANDS:
1076 # - my_command ${hostname} ${username} ${password}
Patrick Williams20f38712022-12-08 06:18:26 -06001077 os.environ["hostname"] = self.hostname
1078 os.environ["username"] = self.username
1079 os.environ["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301080 os.environ["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301081 os.environ["port_https"] = self.port_https
1082 os.environ["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001083
1084 # Append default Env.
Patrick Williams20f38712022-12-08 06:18:26 -06001085 self.env_dict["hostname"] = self.hostname
1086 self.env_dict["username"] = self.username
1087 self.env_dict["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301088 self.env_dict["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301089 self.env_dict["port_https"] = self.port_https
1090 self.env_dict["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001091
1092 try:
1093 tmp_env_dict = {}
1094 if self.env_vars:
1095 tmp_env_dict = json.loads(self.env_vars)
1096 # Export ENV vars default.
1097 for key, value in tmp_env_dict.items():
1098 os.environ[key] = value
1099 self.env_dict[key] = str(value)
1100
1101 if self.econfig:
Patrick Williams20f38712022-12-08 06:18:26 -06001102 with open(self.econfig, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -05001103 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -07001104 tmp_env_dict = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -05001105 except yaml.YAMLError as e:
1106 self.logger.error(e)
1107 sys.exit(-1)
George Keishinge1686752021-07-27 12:55:28 -05001108 # Export ENV vars.
Patrick Williams20f38712022-12-08 06:18:26 -06001109 for key, value in tmp_env_dict["env_params"].items():
George Keishinge1686752021-07-27 12:55:28 -05001110 os.environ[key] = str(value)
1111 self.env_dict[key] = str(value)
1112 except json.decoder.JSONDecodeError as e:
1113 self.logger.error("\n\tERROR: %s " % e)
1114 sys.exit(-1)
1115
1116 # This to mask the password from displaying on the console.
1117 mask_dict = self.env_dict.copy()
1118 for k, v in mask_dict.items():
1119 if k.lower().find("password") != -1:
1120 hidden_text = []
1121 hidden_text.append(v)
Patrick Williams20f38712022-12-08 06:18:26 -06001122 password_regex = (
1123 "(" + "|".join([re.escape(x) for x in hidden_text]) + ")"
1124 )
George Keishinge1686752021-07-27 12:55:28 -05001125 mask_dict[k] = re.sub(password_regex, "********", v)
1126
1127 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -05001128
1129 def execute_python_eval(self, eval_string):
1130 r"""
George Keishing9348b402021-08-13 12:22:35 -05001131 Execute qualified python function string using eval.
George Keishingb97a9042021-07-29 07:41:20 -05001132
1133 Description of argument(s):
1134 eval_string Execute the python object.
1135
1136 Example:
1137 eval(plugin.foo_func.foo_func(10))
1138 """
1139 try:
George Keishingdda48ce2021-08-12 07:02:27 -05001140 self.logger.info("\tExecuting plugin func()")
1141 self.logger.debug("\tCall func: %s" % eval_string)
George Keishingb97a9042021-07-29 07:41:20 -05001142 result = eval(eval_string)
1143 self.logger.info("\treturn: %s" % str(result))
Patrick Williams20f38712022-12-08 06:18:26 -06001144 except (
1145 ValueError,
1146 SyntaxError,
1147 NameError,
1148 AttributeError,
1149 TypeError,
1150 ) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001151 self.logger.error("\tERROR: execute_python_eval: %s" % e)
1152 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001153 plugin_error_dict["exit_on_error"] = True
George Keishing73b95d12021-08-13 14:30:52 -05001154 self.logger.info("\treturn: PLUGIN_EVAL_ERROR")
Patrick Williams20f38712022-12-08 06:18:26 -06001155 return "PLUGIN_EVAL_ERROR"
George Keishingb97a9042021-07-29 07:41:20 -05001156
1157 return result
1158
1159 def execute_plugin_block(self, plugin_cmd_list):
1160 r"""
Peter D Phan5e56f522021-12-20 13:19:41 -06001161 Pack the plugin command to qualifed python string object.
George Keishingb97a9042021-07-29 07:41:20 -05001162
1163 Description of argument(s):
1164 plugin_list_dict Plugin block read from YAML
1165 [{'plugin_name': 'plugin.foo_func.my_func'},
1166 {'plugin_args': [10]}]
1167
1168 Example:
1169 - plugin:
1170 - plugin_name: plugin.foo_func.my_func
1171 - plugin_args:
1172 - arg1
1173 - arg2
1174
1175 - plugin:
1176 - plugin_name: result = plugin.foo_func.my_func
1177 - plugin_args:
1178 - arg1
1179 - arg2
1180
1181 - plugin:
1182 - plugin_name: result1,result2 = plugin.foo_func.my_func
1183 - plugin_args:
1184 - arg1
1185 - arg2
1186 """
1187 try:
Patrick Williams20f38712022-12-08 06:18:26 -06001188 idx = self.key_index_list_dict("plugin_name", plugin_cmd_list)
1189 plugin_name = plugin_cmd_list[idx]["plugin_name"]
George Keishingb97a9042021-07-29 07:41:20 -05001190 # Equal separator means plugin function returns result.
Patrick Williams20f38712022-12-08 06:18:26 -06001191 if " = " in plugin_name:
George Keishingb97a9042021-07-29 07:41:20 -05001192 # Ex. ['result', 'plugin.foo_func.my_func']
Patrick Williams20f38712022-12-08 06:18:26 -06001193 plugin_name_args = plugin_name.split(" = ")
George Keishingb97a9042021-07-29 07:41:20 -05001194 # plugin func return data.
1195 for arg in plugin_name_args:
1196 if arg == plugin_name_args[-1]:
1197 plugin_name = arg
1198 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001199 plugin_resp = arg.split(",")
George Keishingb97a9042021-07-29 07:41:20 -05001200 # ['result1','result2']
1201 for x in plugin_resp:
1202 global_plugin_list.append(x)
1203 global_plugin_dict[x] = ""
1204
1205 # Walk the plugin args ['arg1,'arg2']
1206 # If the YAML plugin statement 'plugin_args' is not declared.
Patrick Williams20f38712022-12-08 06:18:26 -06001207 if any("plugin_args" in d for d in plugin_cmd_list):
1208 idx = self.key_index_list_dict("plugin_args", plugin_cmd_list)
1209 plugin_args = plugin_cmd_list[idx]["plugin_args"]
George Keishingb97a9042021-07-29 07:41:20 -05001210 if plugin_args:
1211 plugin_args = self.yaml_args_populate(plugin_args)
1212 else:
1213 plugin_args = []
1214 else:
1215 plugin_args = self.yaml_args_populate([])
1216
1217 # Pack the args arg1, arg2, .... argn into
1218 # "arg1","arg2","argn" string as params for function.
1219 parm_args_str = self.yaml_args_string(plugin_args)
1220 if parm_args_str:
Patrick Williams20f38712022-12-08 06:18:26 -06001221 plugin_func = plugin_name + "(" + parm_args_str + ")"
George Keishingb97a9042021-07-29 07:41:20 -05001222 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001223 plugin_func = plugin_name + "()"
George Keishingb97a9042021-07-29 07:41:20 -05001224
1225 # Execute plugin function.
1226 if global_plugin_dict:
1227 resp = self.execute_python_eval(plugin_func)
George Keishing9348b402021-08-13 12:22:35 -05001228 # Update plugin vars dict if there is any.
Patrick Williams20f38712022-12-08 06:18:26 -06001229 if resp != "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001230 self.response_args_data(resp)
George Keishingb97a9042021-07-29 07:41:20 -05001231 else:
George Keishingcaa97e62021-08-03 14:00:09 -05001232 resp = self.execute_python_eval(plugin_func)
George Keishingb97a9042021-07-29 07:41:20 -05001233 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001234 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001235 plugin_error_dict["exit_on_error"] = True
George Keishing1e7b0182021-08-06 14:05:54 -05001236 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001237 pass
1238
George Keishing73b95d12021-08-13 14:30:52 -05001239 # There is a real error executing the plugin function.
Patrick Williams20f38712022-12-08 06:18:26 -06001240 if resp == "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001241 return resp
1242
George Keishingde79a9b2021-08-12 16:14:43 -05001243 # Check if plugin_expects_return (int, string, list,dict etc)
Patrick Williams20f38712022-12-08 06:18:26 -06001244 if any("plugin_expects_return" in d for d in plugin_cmd_list):
1245 idx = self.key_index_list_dict(
1246 "plugin_expects_return", plugin_cmd_list
1247 )
1248 plugin_expects = plugin_cmd_list[idx]["plugin_expects_return"]
George Keishingde79a9b2021-08-12 16:14:43 -05001249 if plugin_expects:
1250 if resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001251 if (
1252 self.plugin_expect_type(plugin_expects, resp)
1253 == "INVALID"
1254 ):
George Keishingde79a9b2021-08-12 16:14:43 -05001255 self.logger.error("\tWARN: Plugin error check skipped")
1256 elif not self.plugin_expect_type(plugin_expects, resp):
Patrick Williams20f38712022-12-08 06:18:26 -06001257 self.logger.error(
1258 "\tERROR: Plugin expects return data: %s"
1259 % plugin_expects
1260 )
1261 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001262 elif not resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001263 self.logger.error(
1264 "\tERROR: Plugin func failed to return data"
1265 )
1266 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001267
1268 return resp
1269
George Keishingb97a9042021-07-29 07:41:20 -05001270 def response_args_data(self, plugin_resp):
1271 r"""
George Keishing9348b402021-08-13 12:22:35 -05001272 Parse the plugin function response and update plugin return variable.
George Keishingb97a9042021-07-29 07:41:20 -05001273
1274 plugin_resp Response data from plugin function.
1275 """
1276 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -05001277 resp_data = ""
George Keishing9348b402021-08-13 12:22:35 -05001278
George Keishingb97a9042021-07-29 07:41:20 -05001279 # There is nothing to update the plugin response.
Patrick Williams20f38712022-12-08 06:18:26 -06001280 if len(global_plugin_list) == 0 or plugin_resp == "None":
George Keishingb97a9042021-07-29 07:41:20 -05001281 return
1282
George Keishing5765f792021-08-02 13:08:53 -05001283 if isinstance(plugin_resp, str):
Patrick Williams20f38712022-12-08 06:18:26 -06001284 resp_data = plugin_resp.strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001285 resp_list.append(resp_data)
1286 elif isinstance(plugin_resp, bytes):
Patrick Williams20f38712022-12-08 06:18:26 -06001287 resp_data = str(plugin_resp, "UTF-8").strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001288 resp_list.append(resp_data)
1289 elif isinstance(plugin_resp, tuple):
1290 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -05001291 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -05001292 else:
1293 resp_list = list(plugin_resp)
Patrick Williams20f38712022-12-08 06:18:26 -06001294 resp_list = [x.strip("\r\n\t") for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -05001295 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -05001296 if len(global_plugin_list) == 1:
Patrick Williams20f38712022-12-08 06:18:26 -06001297 resp_list.append([x.strip("\r\n\t") for x in plugin_resp])
George Keishing5765f792021-08-02 13:08:53 -05001298 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001299 resp_list = [x.strip("\r\n\t") for x in plugin_resp]
George Keishing5765f792021-08-02 13:08:53 -05001300 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1301 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001302
George Keishing9348b402021-08-13 12:22:35 -05001303 # Iterate if there is a list of plugin return vars to update.
George Keishingb97a9042021-07-29 07:41:20 -05001304 for idx, item in enumerate(resp_list, start=0):
George Keishing9348b402021-08-13 12:22:35 -05001305 # Exit loop, done required loop.
George Keishingb97a9042021-07-29 07:41:20 -05001306 if idx >= len(global_plugin_list):
1307 break
1308 # Find the index of the return func in the list and
1309 # update the global func return dictionary.
1310 try:
1311 dict_idx = global_plugin_list[idx]
1312 global_plugin_dict[dict_idx] = item
1313 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001314 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001315 pass
1316
1317 # Done updating plugin dict irrespective of pass or failed,
George Keishing9348b402021-08-13 12:22:35 -05001318 # clear all the list element for next plugin block execute.
George Keishingb97a9042021-07-29 07:41:20 -05001319 global_plugin_list.clear()
1320
1321 def yaml_args_string(self, plugin_args):
1322 r"""
1323 Pack the args into string.
1324
1325 plugin_args arg list ['arg1','arg2,'argn']
1326 """
Patrick Williams20f38712022-12-08 06:18:26 -06001327 args_str = ""
George Keishingb97a9042021-07-29 07:41:20 -05001328 for args in plugin_args:
1329 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001330 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001331 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001332 elif args in global_plugin_type_list:
1333 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001334 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001335 args_str += '"' + str(args.strip("\r\n\t")) + '"'
George Keishingb97a9042021-07-29 07:41:20 -05001336 # Skip last list element.
1337 if args != plugin_args[-1]:
1338 args_str += ","
1339 return args_str
1340
1341 def yaml_args_populate(self, yaml_arg_list):
1342 r"""
George Keishing9348b402021-08-13 12:22:35 -05001343 Decode env and plugin vars and populate.
George Keishingb97a9042021-07-29 07:41:20 -05001344
1345 Description of argument(s):
1346 yaml_arg_list arg list read from YAML
1347
1348 Example:
1349 - plugin_args:
1350 - arg1
1351 - arg2
1352
1353 yaml_arg_list: [arg2, arg2]
1354 """
1355 # Get the env loaded keys as list ['hostname', 'username', 'password'].
1356 env_vars_list = list(self.env_dict)
1357
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"