blob: 87cb569cd92ccd051711b4cb59a478323534ca4a [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 Keishing0581cb02021-08-05 15:08:58 -050095# Hold the plugin return named declared if function returned values are list,dict.
96# Refer this name list to look up the plugin dict for eval() args function
George Keishing9348b402021-08-13 12:22:35 -050097# Example ['version']
George Keishing0581cb02021-08-05 15:08:58 -050098global_plugin_type_list = []
George Keishing9348b402021-08-13 12:22:35 -050099
100# Path where logs are to be stored or written.
Patrick Williams20f38712022-12-08 06:18:26 -0600101global_log_store_path = ""
George Keishingb97a9042021-07-29 07:41:20 -0500102
George Keishing1e7b0182021-08-06 14:05:54 -0500103# Plugin error state defaults.
104plugin_error_dict = {
Patrick Williams20f38712022-12-08 06:18:26 -0600105 "exit_on_error": False,
106 "continue_on_error": False,
George Keishing1e7b0182021-08-06 14:05:54 -0500107}
108
Peter D Phan72ce6b82021-06-03 06:18:26 -0500109
Peter D Phan5e56f522021-12-20 13:19:41 -0600110class ffdc_collector:
Peter D Phan72ce6b82021-06-03 06:18:26 -0500111 r"""
George Keishing1e7b0182021-08-06 14:05:54 -0500112 Execute commands from configuration file to collect log files.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500113 Fetch and store generated files at the specified location.
114
115 """
116
Patrick Williams20f38712022-12-08 06:18:26 -0600117 def __init__(
118 self,
119 hostname,
120 username,
121 password,
George Keishinge8a41752023-06-22 21:42:47 +0530122 port_https,
123 port_ipmi,
Patrick Williams20f38712022-12-08 06:18:26 -0600124 ffdc_config,
125 location,
126 remote_type,
127 remote_protocol,
128 env_vars,
129 econfig,
130 log_level,
131 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500132 r"""
133 Description of argument(s):
134
George Keishing8e94f8c2021-07-23 15:06:32 -0500135 hostname name/ip of the targeted (remote) system
136 username user on the targeted system with access to FFDC files
137 password password for user on targeted system
George Keishinge8a41752023-06-22 21:42:47 +0530138 port_https HTTPS port value. By default 443
139 port_ipmi IPMI port value. By default 623
George Keishing8e94f8c2021-07-23 15:06:32 -0500140 ffdc_config configuration file listing commands and files for FFDC
141 location where to store collected FFDC
142 remote_type os type of the remote host
143 remote_protocol Protocol to use to collect data
144 env_vars User define CLI env vars '{"key : "value"}'
145 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -0500146
147 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500148
149 self.hostname = hostname
150 self.username = username
151 self.password = password
George Keishinge8a41752023-06-22 21:42:47 +0530152 self.port_https = str(port_https)
153 self.port_ipmi = str(port_ipmi)
Peter D Phane86d9a52021-07-15 10:42:25 -0500154 self.ffdc_config = ffdc_config
155 self.location = location + "/" + remote_type.upper()
156 self.ssh_remoteclient = None
157 self.telnet_remoteclient = None
158 self.ffdc_dir_path = ""
159 self.ffdc_prefix = ""
160 self.target_type = remote_type.upper()
161 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -0500162 self.env_vars = env_vars
163 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -0500164 self.start_time = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600165 self.elapsed_time = ""
Peter D Phane86d9a52021-07-15 10:42:25 -0500166 self.logger = None
167
168 # Set prefix values for scp files and directory.
169 # Since the time stamp is at second granularity, these values are set here
170 # to be sure that all files for this run will have same timestamps
171 # and they will be saved in the same directory.
172 # self.location == local system for now
Peter D Phan5e56f522021-12-20 13:19:41 -0600173 self.set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500174
Peter D Phan5e56f522021-12-20 13:19:41 -0600175 # Logger for this run. Need to be after set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500176 self.script_logging(getattr(logging, log_level.upper()))
177
178 # Verify top level directory exists for storage
179 self.validate_local_store(self.location)
180
Peter D Phan72ce6b82021-06-03 06:18:26 -0500181 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -0500182 # Load default or user define YAML configuration file.
Patrick Williams20f38712022-12-08 06:18:26 -0600183 with open(self.ffdc_config, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -0500184 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -0700185 self.ffdc_actions = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -0500186 except yaml.YAMLError as e:
187 self.logger.error(e)
188 sys.exit(-1)
Peter D Phane86d9a52021-07-15 10:42:25 -0500189
190 if self.target_type not in self.ffdc_actions.keys():
191 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600192 "\n\tERROR: %s is not listed in %s.\n\n"
193 % (self.target_type, self.ffdc_config)
194 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500195 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500196 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500197 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500198
George Keishing4885b2f2021-07-21 15:22:45 -0500199 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500200 self.logger.info("\n\tENV: User define input YAML variables")
201 self.env_dict = {}
Peter D Phan5e56f522021-12-20 13:19:41 -0600202 self.load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500203
Peter D Phan72ce6b82021-06-03 06:18:26 -0500204 def verify_script_env(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500205 # Import to log version
206 import click
207 import paramiko
208
209 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500210
Patrick Williams20f38712022-12-08 06:18:26 -0600211 redfishtool_version = (
212 self.run_tool_cmd("redfishtool -V").split(" ")[2].strip("\n")
213 )
214 ipmitool_version = self.run_tool_cmd("ipmitool -V").split(" ")[2]
Peter D Phan0c669772021-06-24 13:52:42 -0500215
Peter D Phane86d9a52021-07-15 10:42:25 -0500216 self.logger.info("\n\t---- Script host environment ----")
Patrick Williams20f38712022-12-08 06:18:26 -0600217 self.logger.info(
218 "\t{:<10} {:<10}".format("Script hostname", os.uname()[1])
219 )
220 self.logger.info(
221 "\t{:<10} {:<10}".format("Script host os", platform.platform())
222 )
223 self.logger.info(
224 "\t{:<10} {:>10}".format("Python", platform.python_version())
225 )
226 self.logger.info("\t{:<10} {:>10}".format("PyYAML", yaml.__version__))
227 self.logger.info("\t{:<10} {:>10}".format("click", click.__version__))
228 self.logger.info(
229 "\t{:<10} {:>10}".format("paramiko", paramiko.__version__)
230 )
231 self.logger.info(
232 "\t{:<10} {:>9}".format("redfishtool", redfishtool_version)
233 )
234 self.logger.info(
235 "\t{:<10} {:>12}".format("ipmitool", ipmitool_version)
236 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500237
Patrick Williams20f38712022-12-08 06:18:26 -0600238 if eval(yaml.__version__.replace(".", ",")) < (5, 3, 0):
239 self.logger.error(
240 "\n\tERROR: Python or python packages do not meet minimum"
241 " version requirement."
242 )
243 self.logger.error(
244 "\tERROR: PyYAML version 5.3.0 or higher is needed.\n"
245 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500246 run_env_ok = False
247
Peter D Phane86d9a52021-07-15 10:42:25 -0500248 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500249 return run_env_ok
250
Patrick Williams20f38712022-12-08 06:18:26 -0600251 def script_logging(self, log_level_attr):
Peter D Phane86d9a52021-07-15 10:42:25 -0500252 r"""
253 Create logger
254
255 """
256 self.logger = logging.getLogger()
257 self.logger.setLevel(log_level_attr)
Patrick Williams20f38712022-12-08 06:18:26 -0600258 log_file_handler = logging.FileHandler(
259 self.ffdc_dir_path + "collector.log"
260 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500261
262 stdout_handler = logging.StreamHandler(sys.stdout)
263 self.logger.addHandler(log_file_handler)
264 self.logger.addHandler(stdout_handler)
265
266 # Turn off paramiko INFO logging
267 logging.getLogger("paramiko").setLevel(logging.WARNING)
268
Peter D Phan72ce6b82021-06-03 06:18:26 -0500269 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500270 r"""
271 Check if target system is ping-able.
272
273 """
George Keishing0662e942021-07-13 05:12:20 -0500274 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500275 if response == 0:
Patrick Williams20f38712022-12-08 06:18:26 -0600276 self.logger.info(
277 "\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname
278 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500279 return True
280 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500281 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600282 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n"
283 % self.hostname
284 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500285 sys.exit(-1)
286
Peter D Phan72ce6b82021-06-03 06:18:26 -0500287 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500288 r"""
289 Initiate FFDC Collection depending on requested protocol.
290
291 """
292
Patrick Williams20f38712022-12-08 06:18:26 -0600293 self.logger.info(
294 "\n\t---- Start communicating with %s ----" % self.hostname
295 )
Peter D Phan7610bc42021-07-06 06:31:05 -0500296 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500297
George Keishingf5a57502021-07-22 16:43:47 -0500298 # Find the list of target and protocol supported.
299 check_protocol_list = []
300 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500301
George Keishingf5a57502021-07-22 16:43:47 -0500302 for target_type in config_dict.keys():
303 if self.target_type != target_type:
304 continue
George Keishingeafba182021-06-29 13:44:58 -0500305
George Keishingf5a57502021-07-22 16:43:47 -0500306 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600307 if (
308 config_dict[target_type][k]["PROTOCOL"][0]
309 not in check_protocol_list
310 ):
311 check_protocol_list.append(
312 config_dict[target_type][k]["PROTOCOL"][0]
313 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500314
Patrick Williams20f38712022-12-08 06:18:26 -0600315 self.logger.info(
316 "\n\t %s protocol type: %s"
317 % (self.target_type, check_protocol_list)
318 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500319
George Keishingf5a57502021-07-22 16:43:47 -0500320 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500321
George Keishingf5a57502021-07-22 16:43:47 -0500322 if verified_working_protocol:
Patrick Williams20f38712022-12-08 06:18:26 -0600323 self.logger.info(
324 "\n\t---- Completed protocol pre-requisite check ----\n"
325 )
Peter D Phan0c669772021-06-24 13:52:42 -0500326
George Keishingf5a57502021-07-22 16:43:47 -0500327 # Verify top level directory exists for storage
328 self.validate_local_store(self.location)
329
Patrick Williams20f38712022-12-08 06:18:26 -0600330 if (self.remote_protocol not in verified_working_protocol) and (
331 self.remote_protocol != "ALL"
332 ):
333 self.logger.info(
334 "\n\tWorking protocol list: %s" % verified_working_protocol
335 )
George Keishingf5a57502021-07-22 16:43:47 -0500336 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600337 "\tERROR: Requested protocol %s is not in working protocol"
George Keishing7899a452023-02-15 02:46:54 -0600338 " list.\n" % self.remote_protocol
Patrick Williams20f38712022-12-08 06:18:26 -0600339 )
George Keishingf5a57502021-07-22 16:43:47 -0500340 sys.exit(-1)
341 else:
342 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500343
344 def ssh_to_target_system(self):
345 r"""
346 Open a ssh connection to targeted system.
347
348 """
349
Patrick Williams20f38712022-12-08 06:18:26 -0600350 self.ssh_remoteclient = SSHRemoteclient(
351 self.hostname, self.username, self.password
352 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500353
Peter D Phan5963d632021-07-12 09:58:55 -0500354 if self.ssh_remoteclient.ssh_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600355 self.logger.info(
356 "\n\t[Check] %s SSH connection established.\t [OK]"
357 % self.hostname
358 )
Peter D Phan733df632021-06-17 13:13:36 -0500359
Peter D Phan5963d632021-07-12 09:58:55 -0500360 # Check scp connection.
361 # If scp connection fails,
362 # continue with FFDC generation but skip scp files to local host.
363 self.ssh_remoteclient.scp_connection()
364 return True
365 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600366 self.logger.info(
367 "\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]"
368 % self.hostname
369 )
Peter D Phan5963d632021-07-12 09:58:55 -0500370 return False
371
372 def telnet_to_target_system(self):
373 r"""
374 Open a telnet connection to targeted system.
375 """
Patrick Williams20f38712022-12-08 06:18:26 -0600376 self.telnet_remoteclient = TelnetRemoteclient(
377 self.hostname, self.username, self.password
378 )
Peter D Phan5963d632021-07-12 09:58:55 -0500379 if self.telnet_remoteclient.tn_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600380 self.logger.info(
381 "\n\t[Check] %s Telnet connection established.\t [OK]"
382 % self.hostname
383 )
Peter D Phan5963d632021-07-12 09:58:55 -0500384 return True
385 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600386 self.logger.info(
387 "\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]"
388 % self.hostname
389 )
Peter D Phan5963d632021-07-12 09:58:55 -0500390 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500391
George Keishing772c9772021-06-16 23:23:42 -0500392 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500393 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500394 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500395
Peter D Phan04aca3b2021-06-21 10:37:18 -0500396 Description of argument(s):
397 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500398 """
399
Patrick Williams20f38712022-12-08 06:18:26 -0600400 self.logger.info(
401 "\n\t---- Executing commands on " + self.hostname + " ----"
402 )
403 self.logger.info(
404 "\n\tWorking protocol list: %s" % working_protocol_list
405 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500406
George Keishingf5a57502021-07-22 16:43:47 -0500407 config_dict = self.ffdc_actions
408 for target_type in config_dict.keys():
409 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500410 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500411
Peter D Phane86d9a52021-07-15 10:42:25 -0500412 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
Patrick Williams20f38712022-12-08 06:18:26 -0600413 global_plugin_dict["global_log_store_path"] = self.ffdc_dir_path
George Keishingf5a57502021-07-22 16:43:47 -0500414 self.logger.info("\tSystem Type: %s" % target_type)
415 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600416 if (
417 self.remote_protocol not in working_protocol_list
418 and self.remote_protocol != "ALL"
419 ):
George Keishing6ea92b02021-07-01 11:20:50 -0500420 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500421
Patrick Williams20f38712022-12-08 06:18:26 -0600422 protocol = config_dict[target_type][k]["PROTOCOL"][0]
George Keishingf5a57502021-07-22 16:43:47 -0500423
424 if protocol not in working_protocol_list:
425 continue
426
George Keishingb7607612021-07-27 13:31:23 -0500427 if protocol in working_protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -0600428 if protocol == "SSH" or protocol == "SCP":
George Keishing12fd0652021-07-27 13:57:11 -0500429 self.protocol_ssh(protocol, target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600430 elif protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -0500431 self.protocol_telnet(target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600432 elif (
433 protocol == "REDFISH"
434 or protocol == "IPMI"
435 or protocol == "SHELL"
436 ):
George Keishing506b0582021-07-27 09:31:22 -0500437 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500438 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600439 self.logger.error(
440 "\n\tERROR: %s is not available for %s."
441 % (protocol, self.hostname)
442 )
George Keishingeafba182021-06-29 13:44:58 -0500443
Peter D Phan04aca3b2021-06-21 10:37:18 -0500444 # Close network connection after collecting all files
Patrick Williams20f38712022-12-08 06:18:26 -0600445 self.elapsed_time = time.strftime(
446 "%H:%M:%S", time.gmtime(time.time() - self.start_time)
447 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500448 if self.ssh_remoteclient:
449 self.ssh_remoteclient.ssh_remoteclient_disconnect()
450 if self.telnet_remoteclient:
451 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500452
Patrick Williams20f38712022-12-08 06:18:26 -0600453 def protocol_ssh(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500454 r"""
455 Perform actions using SSH and SCP protocols.
456
457 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500458 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500459 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500460 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500461 """
462
Patrick Williams20f38712022-12-08 06:18:26 -0600463 if protocol == "SCP":
George Keishingf5a57502021-07-22 16:43:47 -0500464 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500465 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600466 self.collect_and_copy_ffdc(
467 self.ffdc_actions[target_type][sub_type]
468 )
Peter D Phan0c669772021-06-24 13:52:42 -0500469
Patrick Williams20f38712022-12-08 06:18:26 -0600470 def protocol_telnet(self, target_type, sub_type):
Peter D Phan5963d632021-07-12 09:58:55 -0500471 r"""
472 Perform actions using telnet protocol.
473 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500474 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500475 """
Patrick Williams20f38712022-12-08 06:18:26 -0600476 self.logger.info(
477 "\n\t[Run] Executing commands on %s using %s"
478 % (self.hostname, "TELNET")
479 )
Peter D Phan5963d632021-07-12 09:58:55 -0500480 telnet_files_saved = []
481 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600482 list_of_commands = self.ffdc_actions[target_type][sub_type]["COMMANDS"]
Peter D Phan5963d632021-07-12 09:58:55 -0500483 for index, each_cmd in enumerate(list_of_commands, start=0):
484 command_txt, command_timeout = self.unpack_command(each_cmd)
Patrick Williams20f38712022-12-08 06:18:26 -0600485 result = self.telnet_remoteclient.execute_command(
486 command_txt, command_timeout
487 )
Peter D Phan5963d632021-07-12 09:58:55 -0500488 if result:
489 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600490 targ_file = self.ffdc_actions[target_type][sub_type][
491 "FILES"
492 ][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500493 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500494 targ_file = command_txt
495 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600496 "\n\t[WARN] Missing filename to store data from"
497 " telnet %s." % each_cmd
498 )
499 self.logger.warning(
500 "\t[WARN] Data will be stored in %s." % targ_file
501 )
502 targ_file_with_path = (
503 self.ffdc_dir_path + self.ffdc_prefix + targ_file
504 )
Peter D Phan5963d632021-07-12 09:58:55 -0500505 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600506 with open(targ_file_with_path, "w") as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500507 fp.write(result)
508 fp.close
509 telnet_files_saved.append(targ_file)
510 progress_counter += 1
511 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500512 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500513 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500514 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500515
Patrick Williams20f38712022-12-08 06:18:26 -0600516 def protocol_execute(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500517 r"""
George Keishing506b0582021-07-27 09:31:22 -0500518 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500519
520 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500521 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500522 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500523 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500524 """
525
Patrick Williams20f38712022-12-08 06:18:26 -0600526 self.logger.info(
527 "\n\t[Run] Executing commands to %s using %s"
528 % (self.hostname, protocol)
529 )
George Keishing506b0582021-07-27 09:31:22 -0500530 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500531 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600532 list_of_cmd = self.get_command_list(
533 self.ffdc_actions[target_type][sub_type]
534 )
George Keishingeafba182021-06-29 13:44:58 -0500535 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500536 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500537 if isinstance(each_cmd, dict):
Patrick Williams20f38712022-12-08 06:18:26 -0600538 if "plugin" in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500539 # If the error is set and plugin explicitly
540 # requested to skip execution on error..
Patrick Williams20f38712022-12-08 06:18:26 -0600541 if plugin_error_dict[
542 "exit_on_error"
543 ] and self.plugin_error_check(each_cmd["plugin"]):
544 self.logger.info(
545 "\n\t[PLUGIN-ERROR] exit_on_error: %s"
546 % plugin_error_dict["exit_on_error"]
547 )
548 self.logger.info(
549 "\t[PLUGIN-SKIP] %s" % each_cmd["plugin"][0]
550 )
George Keishing1e7b0182021-08-06 14:05:54 -0500551 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500552 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500553 # call the plugin
554 self.logger.info("\n\t[PLUGIN-START]")
Patrick Williams20f38712022-12-08 06:18:26 -0600555 result = self.execute_plugin_block(each_cmd["plugin"])
George Keishingb97a9042021-07-29 07:41:20 -0500556 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500557 else:
George Keishing2b83e042021-08-03 12:56:11 -0500558 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500559
George Keishingcaa97e62021-08-03 14:00:09 -0500560 if not plugin_call:
561 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500562 if result:
563 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600564 file_name = self.get_file_list(
565 self.ffdc_actions[target_type][sub_type]
566 )[index]
George Keishingb97a9042021-07-29 07:41:20 -0500567 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500568 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500569 continue
Patrick Williams20f38712022-12-08 06:18:26 -0600570 targ_file = self.yaml_env_and_plugin_vars_populate(
571 file_name
572 )
George Keishingeafba182021-06-29 13:44:58 -0500573 except IndexError:
Patrick Williams20f38712022-12-08 06:18:26 -0600574 targ_file = each_cmd.split("/")[-1]
George Keishing506b0582021-07-27 09:31:22 -0500575 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600576 "\n\t[WARN] Missing filename to store data from %s."
577 % each_cmd
578 )
579 self.logger.warning(
580 "\t[WARN] Data will be stored in %s." % targ_file
581 )
George Keishingeafba182021-06-29 13:44:58 -0500582
Patrick Williams20f38712022-12-08 06:18:26 -0600583 targ_file_with_path = (
584 self.ffdc_dir_path + self.ffdc_prefix + targ_file
585 )
George Keishingeafba182021-06-29 13:44:58 -0500586
587 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600588 with open(targ_file_with_path, "w") as fp:
George Keishing91308ea2021-08-10 14:43:15 -0500589 if isinstance(result, dict):
590 fp.write(json.dumps(result))
591 else:
592 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500593 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500594 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500595
596 progress_counter += 1
597 self.print_progress(progress_counter)
598
Peter D Phane86d9a52021-07-15 10:42:25 -0500599 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500600
George Keishing506b0582021-07-27 09:31:22 -0500601 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500602 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500603
Patrick Williams20f38712022-12-08 06:18:26 -0600604 def collect_and_copy_ffdc(
605 self, ffdc_actions_for_target_type, form_filename=False
606 ):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500607 r"""
608 Send commands in ffdc_config file to targeted system.
609
610 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500611 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500612 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500613 """
614
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500615 # Executing commands, if any
Patrick Williams20f38712022-12-08 06:18:26 -0600616 self.ssh_execute_ffdc_commands(
617 ffdc_actions_for_target_type, form_filename
618 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500619
Peter D Phan3beb02e2021-07-06 13:25:17 -0500620 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500621 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600622 self.logger.info(
623 "\n\n\tCopying FFDC files from remote system %s.\n"
624 % self.hostname
625 )
Peter D Phan2b8052d2021-06-22 10:55:41 -0500626
Peter D Phan04aca3b2021-06-21 10:37:18 -0500627 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500628 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Patrick Williams20f38712022-12-08 06:18:26 -0600629 self.scp_ffdc(
630 self.ffdc_dir_path,
631 self.ffdc_prefix,
632 form_filename,
633 list_of_files,
634 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500635 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600636 self.logger.info(
637 "\n\n\tSkip copying FFDC files from remote system %s.\n"
638 % self.hostname
639 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500640
Patrick Williams20f38712022-12-08 06:18:26 -0600641 def get_command_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500642 r"""
643 Fetch list of commands from configuration file
644
645 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500646 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500647 """
648 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600649 list_of_commands = ffdc_actions_for_target_type["COMMANDS"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500650 except KeyError:
651 list_of_commands = []
652 return list_of_commands
653
Patrick Williams20f38712022-12-08 06:18:26 -0600654 def get_file_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500655 r"""
656 Fetch list of commands from configuration file
657
658 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500659 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500660 """
661 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600662 list_of_files = ffdc_actions_for_target_type["FILES"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500663 except KeyError:
664 list_of_files = []
665 return list_of_files
666
Patrick Williams20f38712022-12-08 06:18:26 -0600667 def unpack_command(self, command):
Peter D Phan5963d632021-07-12 09:58:55 -0500668 r"""
669 Unpack command from config file
670
671 Description of argument(s):
672 command Command from config file.
673 """
674 if isinstance(command, dict):
675 command_txt = next(iter(command))
676 command_timeout = next(iter(command.values()))
677 elif isinstance(command, str):
678 command_txt = command
679 # Default command timeout 60 seconds
680 command_timeout = 60
681
682 return command_txt, command_timeout
683
Patrick Williams20f38712022-12-08 06:18:26 -0600684 def ssh_execute_ffdc_commands(
685 self, ffdc_actions_for_target_type, form_filename=False
686 ):
Peter D Phan3beb02e2021-07-06 13:25:17 -0500687 r"""
688 Send commands in ffdc_config file to targeted system.
689
690 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500691 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500692 form_filename if true, pre-pend self.target_type to filename
693 """
Patrick Williams20f38712022-12-08 06:18:26 -0600694 self.logger.info(
695 "\n\t[Run] Executing commands on %s using %s"
696 % (self.hostname, ffdc_actions_for_target_type["PROTOCOL"][0])
697 )
Peter D Phan3beb02e2021-07-06 13:25:17 -0500698
George Keishingf5a57502021-07-22 16:43:47 -0500699 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500700 # If command list is empty, returns
701 if not list_of_commands:
702 return
703
704 progress_counter = 0
705 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500706 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500707
708 if form_filename:
709 command_txt = str(command_txt % self.target_type)
710
Patrick Williams20f38712022-12-08 06:18:26 -0600711 (
712 cmd_exit_code,
713 err,
714 response,
715 ) = self.ssh_remoteclient.execute_command(
716 command_txt, command_timeout
717 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500718
719 if cmd_exit_code:
720 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600721 "\n\t\t[WARN] %s exits with code %s."
722 % (command_txt, str(cmd_exit_code))
723 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500724 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500725
Peter D Phan3beb02e2021-07-06 13:25:17 -0500726 progress_counter += 1
727 self.print_progress(progress_counter)
728
Peter D Phane86d9a52021-07-15 10:42:25 -0500729 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500730
Patrick Williams20f38712022-12-08 06:18:26 -0600731 def group_copy(self, ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500732 r"""
733 scp group of files (wild card) from remote host.
734
735 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500736 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500737 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500738
Peter D Phan5963d632021-07-12 09:58:55 -0500739 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600740 self.logger.info(
741 "\n\tCopying files from remote system %s via SCP.\n"
742 % self.hostname
743 )
Peter D Phan56429a62021-06-23 08:38:29 -0500744
Patrick Williams20f38712022-12-08 06:18:26 -0600745 list_of_commands = self.get_command_list(
746 ffdc_actions_for_target_type
747 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500748 # If command list is empty, returns
749 if not list_of_commands:
750 return
Peter D Phan56429a62021-06-23 08:38:29 -0500751
Peter D Phanbabf2962021-07-07 11:24:40 -0500752 for command in list_of_commands:
753 try:
George Keishingb4540e72021-08-02 13:48:46 -0500754 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500755 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500756 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500757 continue
758
Patrick Williams20f38712022-12-08 06:18:26 -0600759 (
760 cmd_exit_code,
761 err,
762 response,
763 ) = self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500764
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500765 # If file does not exist, code take no action.
766 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500767 if response:
Patrick Williams20f38712022-12-08 06:18:26 -0600768 scp_result = self.ssh_remoteclient.scp_file_from_remote(
769 response.split("\n"), self.ffdc_dir_path
770 )
Peter D Phan56429a62021-06-23 08:38:29 -0500771 if scp_result:
Patrick Williams20f38712022-12-08 06:18:26 -0600772 self.logger.info(
773 "\t\tSuccessfully copied from "
774 + self.hostname
775 + ":"
776 + command
777 )
Peter D Phan56429a62021-06-23 08:38:29 -0500778 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500779 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500780
781 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600782 self.logger.info(
783 "\n\n\tSkip copying files from remote system %s.\n"
784 % self.hostname
785 )
Peter D Phan56429a62021-06-23 08:38:29 -0500786
Patrick Williams20f38712022-12-08 06:18:26 -0600787 def scp_ffdc(
788 self,
789 targ_dir_path,
790 targ_file_prefix,
791 form_filename,
792 file_list=None,
793 quiet=None,
794 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500795 r"""
796 SCP all files in file_dict to the indicated directory on the local system.
797
798 Description of argument(s):
799 targ_dir_path The path of the directory to receive the files.
George Keishinge16f1582022-12-15 07:32:21 -0600800 targ_file_prefix Prefix which will be prepended to each
Peter D Phan72ce6b82021-06-03 06:18:26 -0500801 target file's name.
802 file_dict A dictionary of files to scp from targeted system to this system
803
804 """
805
Peter D Phan72ce6b82021-06-03 06:18:26 -0500806 progress_counter = 0
807 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500808 if form_filename:
809 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500810 source_file_path = filename
Patrick Williams20f38712022-12-08 06:18:26 -0600811 targ_file_path = (
812 targ_dir_path + targ_file_prefix + filename.split("/")[-1]
813 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500814
Peter D Phanbabf2962021-07-07 11:24:40 -0500815 # If source file name contains wild card, copy filename as is.
Patrick Williams20f38712022-12-08 06:18:26 -0600816 if "*" in source_file_path:
817 scp_result = self.ssh_remoteclient.scp_file_from_remote(
818 source_file_path, self.ffdc_dir_path
819 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500820 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600821 scp_result = self.ssh_remoteclient.scp_file_from_remote(
822 source_file_path, targ_file_path
823 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500824
825 if not quiet:
826 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500827 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600828 "\t\tSuccessfully copied from "
829 + self.hostname
830 + ":"
831 + source_file_path
832 + ".\n"
833 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500834 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500835 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600836 "\t\tFail to copy from "
837 + self.hostname
838 + ":"
839 + source_file_path
840 + ".\n"
841 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500842 else:
843 progress_counter += 1
844 self.print_progress(progress_counter)
845
Peter D Phan5e56f522021-12-20 13:19:41 -0600846 def set_ffdc_default_store_path(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500847 r"""
848 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
849 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
850 Individual ffdc file will have timestr_filename.
851
852 Description of class variables:
853 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
854
855 self.ffdc_prefix The prefix to be given to each ffdc file name.
856
857 """
858
859 timestr = time.strftime("%Y%m%d-%H%M%S")
Patrick Williams20f38712022-12-08 06:18:26 -0600860 self.ffdc_dir_path = (
861 self.location + "/" + self.hostname + "_" + timestr + "/"
862 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500863 self.ffdc_prefix = timestr + "_"
864 self.validate_local_store(self.ffdc_dir_path)
865
Peter D Phan5e56f522021-12-20 13:19:41 -0600866 # Need to verify local store path exists prior to instantiate this class.
867 # This class method is used to share the same code between CLI input parm
868 # and Robot Framework "${EXECDIR}/logs" before referencing this class.
869 @classmethod
870 def validate_local_store(cls, dir_path):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500871 r"""
872 Ensure path exists to store FFDC files locally.
873
874 Description of variable:
875 dir_path The dir path where collected ffdc data files will be stored.
876
877 """
878
879 if not os.path.exists(dir_path):
880 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500881 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500882 except (IOError, OSError) as e:
883 # PermissionError
884 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500885 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600886 "\tERROR: os.makedirs %s failed with"
887 " PermissionError.\n" % dir_path
888 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500889 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500890 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600891 "\tERROR: os.makedirs %s failed with %s.\n"
892 % (dir_path, e.strerror)
893 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500894 sys.exit(-1)
895
896 def print_progress(self, progress):
897 r"""
898 Print activity progress +
899
900 Description of variable:
901 progress Progress counter.
902
903 """
904
905 sys.stdout.write("\r\t" + "+" * progress)
906 sys.stdout.flush()
Patrick Williams20f38712022-12-08 06:18:26 -0600907 time.sleep(0.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500908
909 def verify_redfish(self):
910 r"""
911 Verify remote host has redfish service active
912
913 """
Patrick Williams20f38712022-12-08 06:18:26 -0600914 redfish_parm = (
915 "redfishtool -r "
916 + self.hostname
917 + " -S Always raw GET /redfish/v1/"
918 )
919 return self.run_tool_cmd(redfish_parm, True)
Peter D Phan0c669772021-06-24 13:52:42 -0500920
George Keishingeafba182021-06-29 13:44:58 -0500921 def verify_ipmi(self):
922 r"""
923 Verify remote host has IPMI LAN service active
924
925 """
Patrick Williams20f38712022-12-08 06:18:26 -0600926 if self.target_type == "OPENBMC":
927 ipmi_parm = (
928 "ipmitool -I lanplus -C 17 -U "
929 + self.username
930 + " -P "
931 + self.password
932 + " -H "
933 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530934 + " -p "
935 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600936 + " power status"
937 )
George Keishing484f8242021-07-27 01:42:02 -0500938 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600939 ipmi_parm = (
940 "ipmitool -I lanplus -P "
941 + self.password
942 + " -H "
943 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530944 + " -p "
945 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600946 + " power status"
947 )
George Keishing484f8242021-07-27 01:42:02 -0500948
Patrick Williams20f38712022-12-08 06:18:26 -0600949 return self.run_tool_cmd(ipmi_parm, True)
George Keishingeafba182021-06-29 13:44:58 -0500950
Patrick Williams20f38712022-12-08 06:18:26 -0600951 def run_tool_cmd(self, parms_string, quiet=False):
George Keishingeafba182021-06-29 13:44:58 -0500952 r"""
George Keishing506b0582021-07-27 09:31:22 -0500953 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500954
955 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500956 parms_string tool command options.
957 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500958 """
959
Patrick Williams20f38712022-12-08 06:18:26 -0600960 result = subprocess.run(
961 [parms_string],
962 stdout=subprocess.PIPE,
963 stderr=subprocess.PIPE,
964 shell=True,
965 universal_newlines=True,
966 )
George Keishingeafba182021-06-29 13:44:58 -0500967
968 if result.stderr and not quiet:
Patrick Williams20f38712022-12-08 06:18:26 -0600969 self.logger.error("\n\t\tERROR with %s " % parms_string)
970 self.logger.error("\t\t" + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500971
972 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500973
George Keishingf5a57502021-07-22 16:43:47 -0500974 def verify_protocol(self, protocol_list):
975 r"""
976 Perform protocol working check.
977
978 Description of argument(s):
979 protocol_list List of protocol.
980 """
981
982 tmp_list = []
983 if self.target_is_pingable():
984 tmp_list.append("SHELL")
985
986 for protocol in protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -0600987 if self.remote_protocol != "ALL":
George Keishingf5a57502021-07-22 16:43:47 -0500988 if self.remote_protocol != protocol:
989 continue
990
991 # Only check SSH/SCP once for both protocols
Patrick Williams20f38712022-12-08 06:18:26 -0600992 if (
993 protocol == "SSH"
994 or protocol == "SCP"
995 and protocol not in tmp_list
996 ):
George Keishingf5a57502021-07-22 16:43:47 -0500997 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -0500998 # Add only what user asked.
Patrick Williams20f38712022-12-08 06:18:26 -0600999 if self.remote_protocol != "ALL":
George Keishingaa638702021-07-26 11:48:28 -05001000 tmp_list.append(self.remote_protocol)
1001 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001002 tmp_list.append("SSH")
1003 tmp_list.append("SCP")
George Keishingf5a57502021-07-22 16:43:47 -05001004
Patrick Williams20f38712022-12-08 06:18:26 -06001005 if protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -05001006 if self.telnet_to_target_system():
1007 tmp_list.append(protocol)
1008
Patrick Williams20f38712022-12-08 06:18:26 -06001009 if protocol == "REDFISH":
George Keishingf5a57502021-07-22 16:43:47 -05001010 if self.verify_redfish():
1011 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001012 self.logger.info(
1013 "\n\t[Check] %s Redfish Service.\t\t [OK]"
1014 % self.hostname
1015 )
George Keishingf5a57502021-07-22 16:43:47 -05001016 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001017 self.logger.info(
1018 "\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]"
1019 % self.hostname
1020 )
George Keishingf5a57502021-07-22 16:43:47 -05001021
Patrick Williams20f38712022-12-08 06:18:26 -06001022 if protocol == "IPMI":
George Keishingf5a57502021-07-22 16:43:47 -05001023 if self.verify_ipmi():
1024 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001025 self.logger.info(
1026 "\n\t[Check] %s IPMI LAN Service.\t\t [OK]"
1027 % self.hostname
1028 )
George Keishingf5a57502021-07-22 16:43:47 -05001029 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001030 self.logger.info(
1031 "\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]"
1032 % self.hostname
1033 )
George Keishingf5a57502021-07-22 16:43:47 -05001034
1035 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -05001036
1037 def load_env(self):
1038 r"""
1039 Perform protocol working check.
1040
1041 """
1042 # This is for the env vars a user can use in YAML to load it at runtime.
1043 # Example YAML:
1044 # -COMMANDS:
1045 # - my_command ${hostname} ${username} ${password}
Patrick Williams20f38712022-12-08 06:18:26 -06001046 os.environ["hostname"] = self.hostname
1047 os.environ["username"] = self.username
1048 os.environ["password"] = self.password
George Keishinge8a41752023-06-22 21:42:47 +05301049 os.environ["port_https"] = self.port_https
1050 os.environ["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001051
1052 # Append default Env.
Patrick Williams20f38712022-12-08 06:18:26 -06001053 self.env_dict["hostname"] = self.hostname
1054 self.env_dict["username"] = self.username
1055 self.env_dict["password"] = self.password
George Keishinge8a41752023-06-22 21:42:47 +05301056 self.env_dict["port_https"] = self.port_https
1057 self.env_dict["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001058
1059 try:
1060 tmp_env_dict = {}
1061 if self.env_vars:
1062 tmp_env_dict = json.loads(self.env_vars)
1063 # Export ENV vars default.
1064 for key, value in tmp_env_dict.items():
1065 os.environ[key] = value
1066 self.env_dict[key] = str(value)
1067
1068 if self.econfig:
Patrick Williams20f38712022-12-08 06:18:26 -06001069 with open(self.econfig, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -05001070 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -07001071 tmp_env_dict = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -05001072 except yaml.YAMLError as e:
1073 self.logger.error(e)
1074 sys.exit(-1)
George Keishinge1686752021-07-27 12:55:28 -05001075 # Export ENV vars.
Patrick Williams20f38712022-12-08 06:18:26 -06001076 for key, value in tmp_env_dict["env_params"].items():
George Keishinge1686752021-07-27 12:55:28 -05001077 os.environ[key] = str(value)
1078 self.env_dict[key] = str(value)
1079 except json.decoder.JSONDecodeError as e:
1080 self.logger.error("\n\tERROR: %s " % e)
1081 sys.exit(-1)
1082
1083 # This to mask the password from displaying on the console.
1084 mask_dict = self.env_dict.copy()
1085 for k, v in mask_dict.items():
1086 if k.lower().find("password") != -1:
1087 hidden_text = []
1088 hidden_text.append(v)
Patrick Williams20f38712022-12-08 06:18:26 -06001089 password_regex = (
1090 "(" + "|".join([re.escape(x) for x in hidden_text]) + ")"
1091 )
George Keishinge1686752021-07-27 12:55:28 -05001092 mask_dict[k] = re.sub(password_regex, "********", v)
1093
1094 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -05001095
1096 def execute_python_eval(self, eval_string):
1097 r"""
George Keishing9348b402021-08-13 12:22:35 -05001098 Execute qualified python function string using eval.
George Keishingb97a9042021-07-29 07:41:20 -05001099
1100 Description of argument(s):
1101 eval_string Execute the python object.
1102
1103 Example:
1104 eval(plugin.foo_func.foo_func(10))
1105 """
1106 try:
George Keishingdda48ce2021-08-12 07:02:27 -05001107 self.logger.info("\tExecuting plugin func()")
1108 self.logger.debug("\tCall func: %s" % eval_string)
George Keishingb97a9042021-07-29 07:41:20 -05001109 result = eval(eval_string)
1110 self.logger.info("\treturn: %s" % str(result))
Patrick Williams20f38712022-12-08 06:18:26 -06001111 except (
1112 ValueError,
1113 SyntaxError,
1114 NameError,
1115 AttributeError,
1116 TypeError,
1117 ) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001118 self.logger.error("\tERROR: execute_python_eval: %s" % e)
1119 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001120 plugin_error_dict["exit_on_error"] = True
George Keishing73b95d12021-08-13 14:30:52 -05001121 self.logger.info("\treturn: PLUGIN_EVAL_ERROR")
Patrick Williams20f38712022-12-08 06:18:26 -06001122 return "PLUGIN_EVAL_ERROR"
George Keishingb97a9042021-07-29 07:41:20 -05001123
1124 return result
1125
1126 def execute_plugin_block(self, plugin_cmd_list):
1127 r"""
Peter D Phan5e56f522021-12-20 13:19:41 -06001128 Pack the plugin command to qualifed python string object.
George Keishingb97a9042021-07-29 07:41:20 -05001129
1130 Description of argument(s):
1131 plugin_list_dict Plugin block read from YAML
1132 [{'plugin_name': 'plugin.foo_func.my_func'},
1133 {'plugin_args': [10]}]
1134
1135 Example:
1136 - plugin:
1137 - plugin_name: plugin.foo_func.my_func
1138 - plugin_args:
1139 - arg1
1140 - arg2
1141
1142 - plugin:
1143 - plugin_name: result = plugin.foo_func.my_func
1144 - plugin_args:
1145 - arg1
1146 - arg2
1147
1148 - plugin:
1149 - plugin_name: result1,result2 = plugin.foo_func.my_func
1150 - plugin_args:
1151 - arg1
1152 - arg2
1153 """
1154 try:
Patrick Williams20f38712022-12-08 06:18:26 -06001155 idx = self.key_index_list_dict("plugin_name", plugin_cmd_list)
1156 plugin_name = plugin_cmd_list[idx]["plugin_name"]
George Keishingb97a9042021-07-29 07:41:20 -05001157 # Equal separator means plugin function returns result.
Patrick Williams20f38712022-12-08 06:18:26 -06001158 if " = " in plugin_name:
George Keishingb97a9042021-07-29 07:41:20 -05001159 # Ex. ['result', 'plugin.foo_func.my_func']
Patrick Williams20f38712022-12-08 06:18:26 -06001160 plugin_name_args = plugin_name.split(" = ")
George Keishingb97a9042021-07-29 07:41:20 -05001161 # plugin func return data.
1162 for arg in plugin_name_args:
1163 if arg == plugin_name_args[-1]:
1164 plugin_name = arg
1165 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001166 plugin_resp = arg.split(",")
George Keishingb97a9042021-07-29 07:41:20 -05001167 # ['result1','result2']
1168 for x in plugin_resp:
1169 global_plugin_list.append(x)
1170 global_plugin_dict[x] = ""
1171
1172 # Walk the plugin args ['arg1,'arg2']
1173 # If the YAML plugin statement 'plugin_args' is not declared.
Patrick Williams20f38712022-12-08 06:18:26 -06001174 if any("plugin_args" in d for d in plugin_cmd_list):
1175 idx = self.key_index_list_dict("plugin_args", plugin_cmd_list)
1176 plugin_args = plugin_cmd_list[idx]["plugin_args"]
George Keishingb97a9042021-07-29 07:41:20 -05001177 if plugin_args:
1178 plugin_args = self.yaml_args_populate(plugin_args)
1179 else:
1180 plugin_args = []
1181 else:
1182 plugin_args = self.yaml_args_populate([])
1183
1184 # Pack the args arg1, arg2, .... argn into
1185 # "arg1","arg2","argn" string as params for function.
1186 parm_args_str = self.yaml_args_string(plugin_args)
1187 if parm_args_str:
Patrick Williams20f38712022-12-08 06:18:26 -06001188 plugin_func = plugin_name + "(" + parm_args_str + ")"
George Keishingb97a9042021-07-29 07:41:20 -05001189 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001190 plugin_func = plugin_name + "()"
George Keishingb97a9042021-07-29 07:41:20 -05001191
1192 # Execute plugin function.
1193 if global_plugin_dict:
1194 resp = self.execute_python_eval(plugin_func)
George Keishing9348b402021-08-13 12:22:35 -05001195 # Update plugin vars dict if there is any.
Patrick Williams20f38712022-12-08 06:18:26 -06001196 if resp != "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001197 self.response_args_data(resp)
George Keishingb97a9042021-07-29 07:41:20 -05001198 else:
George Keishingcaa97e62021-08-03 14:00:09 -05001199 resp = self.execute_python_eval(plugin_func)
George Keishingb97a9042021-07-29 07:41:20 -05001200 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001201 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001202 plugin_error_dict["exit_on_error"] = True
George Keishing1e7b0182021-08-06 14:05:54 -05001203 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001204 pass
1205
George Keishing73b95d12021-08-13 14:30:52 -05001206 # There is a real error executing the plugin function.
Patrick Williams20f38712022-12-08 06:18:26 -06001207 if resp == "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001208 return resp
1209
George Keishingde79a9b2021-08-12 16:14:43 -05001210 # Check if plugin_expects_return (int, string, list,dict etc)
Patrick Williams20f38712022-12-08 06:18:26 -06001211 if any("plugin_expects_return" in d for d in plugin_cmd_list):
1212 idx = self.key_index_list_dict(
1213 "plugin_expects_return", plugin_cmd_list
1214 )
1215 plugin_expects = plugin_cmd_list[idx]["plugin_expects_return"]
George Keishingde79a9b2021-08-12 16:14:43 -05001216 if plugin_expects:
1217 if resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001218 if (
1219 self.plugin_expect_type(plugin_expects, resp)
1220 == "INVALID"
1221 ):
George Keishingde79a9b2021-08-12 16:14:43 -05001222 self.logger.error("\tWARN: Plugin error check skipped")
1223 elif not self.plugin_expect_type(plugin_expects, resp):
Patrick Williams20f38712022-12-08 06:18:26 -06001224 self.logger.error(
1225 "\tERROR: Plugin expects return data: %s"
1226 % plugin_expects
1227 )
1228 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001229 elif not resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001230 self.logger.error(
1231 "\tERROR: Plugin func failed to return data"
1232 )
1233 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001234
1235 return resp
1236
George Keishingb97a9042021-07-29 07:41:20 -05001237 def response_args_data(self, plugin_resp):
1238 r"""
George Keishing9348b402021-08-13 12:22:35 -05001239 Parse the plugin function response and update plugin return variable.
George Keishingb97a9042021-07-29 07:41:20 -05001240
1241 plugin_resp Response data from plugin function.
1242 """
1243 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -05001244 resp_data = ""
George Keishing9348b402021-08-13 12:22:35 -05001245
George Keishingb97a9042021-07-29 07:41:20 -05001246 # There is nothing to update the plugin response.
Patrick Williams20f38712022-12-08 06:18:26 -06001247 if len(global_plugin_list) == 0 or plugin_resp == "None":
George Keishingb97a9042021-07-29 07:41:20 -05001248 return
1249
George Keishing5765f792021-08-02 13:08:53 -05001250 if isinstance(plugin_resp, str):
Patrick Williams20f38712022-12-08 06:18:26 -06001251 resp_data = plugin_resp.strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001252 resp_list.append(resp_data)
1253 elif isinstance(plugin_resp, bytes):
Patrick Williams20f38712022-12-08 06:18:26 -06001254 resp_data = str(plugin_resp, "UTF-8").strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001255 resp_list.append(resp_data)
1256 elif isinstance(plugin_resp, tuple):
1257 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -05001258 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -05001259 else:
1260 resp_list = list(plugin_resp)
Patrick Williams20f38712022-12-08 06:18:26 -06001261 resp_list = [x.strip("\r\n\t") for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -05001262 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -05001263 if len(global_plugin_list) == 1:
Patrick Williams20f38712022-12-08 06:18:26 -06001264 resp_list.append([x.strip("\r\n\t") for x in plugin_resp])
George Keishing5765f792021-08-02 13:08:53 -05001265 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001266 resp_list = [x.strip("\r\n\t") for x in plugin_resp]
George Keishing5765f792021-08-02 13:08:53 -05001267 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1268 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001269
George Keishing9348b402021-08-13 12:22:35 -05001270 # Iterate if there is a list of plugin return vars to update.
George Keishingb97a9042021-07-29 07:41:20 -05001271 for idx, item in enumerate(resp_list, start=0):
George Keishing9348b402021-08-13 12:22:35 -05001272 # Exit loop, done required loop.
George Keishingb97a9042021-07-29 07:41:20 -05001273 if idx >= len(global_plugin_list):
1274 break
1275 # Find the index of the return func in the list and
1276 # update the global func return dictionary.
1277 try:
1278 dict_idx = global_plugin_list[idx]
1279 global_plugin_dict[dict_idx] = item
1280 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001281 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001282 pass
1283
1284 # Done updating plugin dict irrespective of pass or failed,
George Keishing9348b402021-08-13 12:22:35 -05001285 # clear all the list element for next plugin block execute.
George Keishingb97a9042021-07-29 07:41:20 -05001286 global_plugin_list.clear()
1287
1288 def yaml_args_string(self, plugin_args):
1289 r"""
1290 Pack the args into string.
1291
1292 plugin_args arg list ['arg1','arg2,'argn']
1293 """
Patrick Williams20f38712022-12-08 06:18:26 -06001294 args_str = ""
George Keishingb97a9042021-07-29 07:41:20 -05001295 for args in plugin_args:
1296 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001297 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001298 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001299 elif args in global_plugin_type_list:
1300 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001301 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001302 args_str += '"' + str(args.strip("\r\n\t")) + '"'
George Keishingb97a9042021-07-29 07:41:20 -05001303 # Skip last list element.
1304 if args != plugin_args[-1]:
1305 args_str += ","
1306 return args_str
1307
1308 def yaml_args_populate(self, yaml_arg_list):
1309 r"""
George Keishing9348b402021-08-13 12:22:35 -05001310 Decode env and plugin vars and populate.
George Keishingb97a9042021-07-29 07:41:20 -05001311
1312 Description of argument(s):
1313 yaml_arg_list arg list read from YAML
1314
1315 Example:
1316 - plugin_args:
1317 - arg1
1318 - arg2
1319
1320 yaml_arg_list: [arg2, arg2]
1321 """
1322 # Get the env loaded keys as list ['hostname', 'username', 'password'].
1323 env_vars_list = list(self.env_dict)
1324
1325 if isinstance(yaml_arg_list, list):
1326 tmp_list = []
1327 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001328 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001329 tmp_list.append(arg)
1330 continue
1331 elif isinstance(arg, str):
1332 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1333 tmp_list.append(arg_str)
1334 else:
1335 tmp_list.append(arg)
1336
1337 # return populated list.
1338 return tmp_list
1339
1340 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1341 r"""
George Keishing9348b402021-08-13 12:22:35 -05001342 Update ${MY_VAR} and plugin vars.
George Keishingb97a9042021-07-29 07:41:20 -05001343
1344 Description of argument(s):
George Keishing9348b402021-08-13 12:22:35 -05001345 yaml_arg_str arg string read from YAML.
George Keishingb97a9042021-07-29 07:41:20 -05001346
1347 Example:
1348 - cat ${MY_VAR}
1349 - ls -AX my_plugin_var
1350 """
George Keishing9348b402021-08-13 12:22:35 -05001351 # Parse the string for env vars ${env_vars}.
George Keishingb97a9042021-07-29 07:41:20 -05001352 try:
1353 # Example, list of matching env vars ['username', 'password', 'hostname']
1354 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
Patrick Williams20f38712022-12-08 06:18:26 -06001355 var_name_regex = "\\$\\{([^\\}]+)\\}"
George Keishingb97a9042021-07-29 07:41:20 -05001356 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1357 for var in env_var_names_list:
1358 env_var = os.environ[var]
Patrick Williams20f38712022-12-08 06:18:26 -06001359 env_replace = "${" + var + "}"
George Keishingb97a9042021-07-29 07:41:20 -05001360 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1361 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001362 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001363 pass
1364
1365 # Parse the string for plugin vars.
1366 try:
1367 # Example, list of plugin vars ['my_username', 'my_data']
1368 plugin_var_name_list = global_plugin_dict.keys()
1369 for var in plugin_var_name_list:
George Keishing9348b402021-08-13 12:22:35 -05001370 # skip env var list already populated above code block list.
George Keishing0581cb02021-08-05 15:08:58 -05001371 if var in env_var_names_list:
1372 continue
George Keishing9348b402021-08-13 12:22:35 -05001373 # If this plugin var exist but empty in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001374 # This is either a YAML plugin statement incorrectly used or
George Keishing9348b402021-08-13 12:22:35 -05001375 # user added a plugin var which is not going to be populated.
George Keishing0581cb02021-08-05 15:08:58 -05001376 if yaml_arg_str in global_plugin_dict:
1377 if isinstance(global_plugin_dict[var], (list, dict)):
1378 # List data type or dict can't be replaced, use directly
1379 # in eval function call.
1380 global_plugin_type_list.append(var)
1381 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001382 yaml_arg_str = yaml_arg_str.replace(
1383 str(var), str(global_plugin_dict[var])
1384 )
George Keishing0581cb02021-08-05 15:08:58 -05001385 # Just a string like filename or command.
1386 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001387 yaml_arg_str = yaml_arg_str.replace(
1388 str(var), str(global_plugin_dict[var])
1389 )
George Keishingb97a9042021-07-29 07:41:20 -05001390 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001391 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001392 pass
1393
1394 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001395
1396 def plugin_error_check(self, plugin_dict):
1397 r"""
1398 Plugin error dict processing.
1399
1400 Description of argument(s):
1401 plugin_dict Dictionary of plugin error.
1402 """
Patrick Williams20f38712022-12-08 06:18:26 -06001403 if any("plugin_error" in d for d in plugin_dict):
George Keishing1e7b0182021-08-06 14:05:54 -05001404 for d in plugin_dict:
Patrick Williams20f38712022-12-08 06:18:26 -06001405 if "plugin_error" in d:
1406 value = d["plugin_error"]
George Keishing1e7b0182021-08-06 14:05:54 -05001407 # Reference if the error is set or not by plugin.
1408 return plugin_error_dict[value]
George Keishingde79a9b2021-08-12 16:14:43 -05001409
1410 def key_index_list_dict(self, key, list_dict):
1411 r"""
1412 Iterate list of dictionary and return index if the key match is found.
1413
1414 Description of argument(s):
1415 key Valid Key in a dict.
1416 list_dict list of dictionary.
1417 """
1418 for i, d in enumerate(list_dict):
1419 if key in d.keys():
1420 return i
1421
1422 def plugin_expect_type(self, type, data):
1423 r"""
1424 Plugin expect directive type check.
1425 """
Patrick Williams20f38712022-12-08 06:18:26 -06001426 if type == "int":
George Keishingde79a9b2021-08-12 16:14:43 -05001427 return isinstance(data, int)
Patrick Williams20f38712022-12-08 06:18:26 -06001428 elif type == "float":
George Keishingde79a9b2021-08-12 16:14:43 -05001429 return isinstance(data, float)
Patrick Williams20f38712022-12-08 06:18:26 -06001430 elif type == "str":
George Keishingde79a9b2021-08-12 16:14:43 -05001431 return isinstance(data, str)
Patrick Williams20f38712022-12-08 06:18:26 -06001432 elif type == "list":
George Keishingde79a9b2021-08-12 16:14:43 -05001433 return isinstance(data, list)
Patrick Williams20f38712022-12-08 06:18:26 -06001434 elif type == "dict":
George Keishingde79a9b2021-08-12 16:14:43 -05001435 return isinstance(data, dict)
Patrick Williams20f38712022-12-08 06:18:26 -06001436 elif type == "tuple":
George Keishingde79a9b2021-08-12 16:14:43 -05001437 return isinstance(data, tuple)
1438 else:
1439 self.logger.info("\tInvalid data type requested: %s" % type)
Patrick Williams20f38712022-12-08 06:18:26 -06001440 return "INVALID"