blob: c6ea801a2c110c41b25c28c4c32879b7de790091 [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 Keishing7a61aa22023-06-26 13:18:37 +0530122 port_ssh,
George Keishinge8a41752023-06-22 21:42:47 +0530123 port_https,
124 port_ipmi,
Patrick Williams20f38712022-12-08 06:18:26 -0600125 ffdc_config,
126 location,
127 remote_type,
128 remote_protocol,
129 env_vars,
130 econfig,
131 log_level,
132 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500133 r"""
134 Description of argument(s):
135
George Keishing8e94f8c2021-07-23 15:06:32 -0500136 hostname name/ip of the targeted (remote) system
137 username user on the targeted system with access to FFDC files
138 password password for user on targeted system
George Keishing7a61aa22023-06-26 13:18:37 +0530139 port_ssh SSH port value. By default 22
George Keishinge8a41752023-06-22 21:42:47 +0530140 port_https HTTPS port value. By default 443
141 port_ipmi IPMI port value. By default 623
George Keishing8e94f8c2021-07-23 15:06:32 -0500142 ffdc_config configuration file listing commands and files for FFDC
143 location where to store collected FFDC
144 remote_type os type of the remote host
145 remote_protocol Protocol to use to collect data
146 env_vars User define CLI env vars '{"key : "value"}'
147 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -0500148
149 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500150
151 self.hostname = hostname
152 self.username = username
153 self.password = password
George Keishing7a61aa22023-06-26 13:18:37 +0530154 self.port_ssh = str(port_ssh)
George Keishinge8a41752023-06-22 21:42:47 +0530155 self.port_https = str(port_https)
156 self.port_ipmi = str(port_ipmi)
Peter D Phane86d9a52021-07-15 10:42:25 -0500157 self.ffdc_config = ffdc_config
158 self.location = location + "/" + remote_type.upper()
159 self.ssh_remoteclient = None
160 self.telnet_remoteclient = None
161 self.ffdc_dir_path = ""
162 self.ffdc_prefix = ""
163 self.target_type = remote_type.upper()
164 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -0500165 self.env_vars = env_vars
166 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -0500167 self.start_time = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600168 self.elapsed_time = ""
Peter D Phane86d9a52021-07-15 10:42:25 -0500169 self.logger = None
170
171 # Set prefix values for scp files and directory.
172 # Since the time stamp is at second granularity, these values are set here
173 # to be sure that all files for this run will have same timestamps
174 # and they will be saved in the same directory.
175 # self.location == local system for now
Peter D Phan5e56f522021-12-20 13:19:41 -0600176 self.set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500177
Peter D Phan5e56f522021-12-20 13:19:41 -0600178 # Logger for this run. Need to be after set_ffdc_default_store_path()
Peter D Phane86d9a52021-07-15 10:42:25 -0500179 self.script_logging(getattr(logging, log_level.upper()))
180
181 # Verify top level directory exists for storage
182 self.validate_local_store(self.location)
183
Peter D Phan72ce6b82021-06-03 06:18:26 -0500184 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -0500185 # Load default or user define YAML configuration file.
Patrick Williams20f38712022-12-08 06:18:26 -0600186 with open(self.ffdc_config, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -0500187 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -0700188 self.ffdc_actions = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -0500189 except yaml.YAMLError as e:
190 self.logger.error(e)
191 sys.exit(-1)
Peter D Phane86d9a52021-07-15 10:42:25 -0500192
193 if self.target_type not in self.ffdc_actions.keys():
194 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600195 "\n\tERROR: %s is not listed in %s.\n\n"
196 % (self.target_type, self.ffdc_config)
197 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500198 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500199 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500200 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500201
George Keishing4885b2f2021-07-21 15:22:45 -0500202 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500203 self.logger.info("\n\tENV: User define input YAML variables")
204 self.env_dict = {}
Peter D Phan5e56f522021-12-20 13:19:41 -0600205 self.load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500206
Peter D Phan72ce6b82021-06-03 06:18:26 -0500207 def verify_script_env(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500208 # Import to log version
209 import click
210 import paramiko
211
212 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500213
George Keishingd805bc02025-02-28 12:17:13 +0530214 try:
215 redfishtool_version = (
216 self.run_tool_cmd("redfishtool -V").split(" ")[2].strip("\n")
217 )
218 except Exception as e:
219 self.logger.error("\tEXCEPTION redfishtool: %s", e)
220 redfishtool_version = "Not Installed (optional)"
221
222 try:
223 ipmitool_version = self.run_tool_cmd("ipmitool -V").split(" ")[2]
224 except Exception as e:
225 self.logger.error("\tEXCEPTION ipmitool: %s", e)
226 ipmitool_version = "Not Installed (optional)"
Peter D Phan0c669772021-06-24 13:52:42 -0500227
Peter D Phane86d9a52021-07-15 10:42:25 -0500228 self.logger.info("\n\t---- Script host environment ----")
Patrick Williams20f38712022-12-08 06:18:26 -0600229 self.logger.info(
230 "\t{:<10} {:<10}".format("Script hostname", os.uname()[1])
231 )
232 self.logger.info(
233 "\t{:<10} {:<10}".format("Script host os", platform.platform())
234 )
235 self.logger.info(
236 "\t{:<10} {:>10}".format("Python", platform.python_version())
237 )
238 self.logger.info("\t{:<10} {:>10}".format("PyYAML", yaml.__version__))
239 self.logger.info("\t{:<10} {:>10}".format("click", click.__version__))
240 self.logger.info(
241 "\t{:<10} {:>10}".format("paramiko", paramiko.__version__)
242 )
243 self.logger.info(
244 "\t{:<10} {:>9}".format("redfishtool", redfishtool_version)
245 )
246 self.logger.info(
247 "\t{:<10} {:>12}".format("ipmitool", ipmitool_version)
248 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500249
Patrick Williams20f38712022-12-08 06:18:26 -0600250 if eval(yaml.__version__.replace(".", ",")) < (5, 3, 0):
251 self.logger.error(
252 "\n\tERROR: Python or python packages do not meet minimum"
253 " version requirement."
254 )
255 self.logger.error(
256 "\tERROR: PyYAML version 5.3.0 or higher is needed.\n"
257 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500258 run_env_ok = False
259
Peter D Phane86d9a52021-07-15 10:42:25 -0500260 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500261 return run_env_ok
262
Patrick Williams20f38712022-12-08 06:18:26 -0600263 def script_logging(self, log_level_attr):
Peter D Phane86d9a52021-07-15 10:42:25 -0500264 r"""
265 Create logger
266
267 """
268 self.logger = logging.getLogger()
269 self.logger.setLevel(log_level_attr)
Patrick Williams20f38712022-12-08 06:18:26 -0600270 log_file_handler = logging.FileHandler(
271 self.ffdc_dir_path + "collector.log"
272 )
Peter D Phane86d9a52021-07-15 10:42:25 -0500273
274 stdout_handler = logging.StreamHandler(sys.stdout)
275 self.logger.addHandler(log_file_handler)
276 self.logger.addHandler(stdout_handler)
277
278 # Turn off paramiko INFO logging
279 logging.getLogger("paramiko").setLevel(logging.WARNING)
280
Peter D Phan72ce6b82021-06-03 06:18:26 -0500281 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500282 r"""
283 Check if target system is ping-able.
284
285 """
George Keishing0662e942021-07-13 05:12:20 -0500286 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500287 if response == 0:
Patrick Williams20f38712022-12-08 06:18:26 -0600288 self.logger.info(
289 "\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname
290 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500291 return True
292 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500293 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600294 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n"
295 % self.hostname
296 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500297 sys.exit(-1)
298
Peter D Phan72ce6b82021-06-03 06:18:26 -0500299 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500300 r"""
301 Initiate FFDC Collection depending on requested protocol.
302
303 """
304
Patrick Williams20f38712022-12-08 06:18:26 -0600305 self.logger.info(
306 "\n\t---- Start communicating with %s ----" % self.hostname
307 )
Peter D Phan7610bc42021-07-06 06:31:05 -0500308 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500309
George Keishingf5a57502021-07-22 16:43:47 -0500310 # Find the list of target and protocol supported.
311 check_protocol_list = []
312 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500313
George Keishingf5a57502021-07-22 16:43:47 -0500314 for target_type in config_dict.keys():
315 if self.target_type != target_type:
316 continue
George Keishingeafba182021-06-29 13:44:58 -0500317
George Keishingf5a57502021-07-22 16:43:47 -0500318 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600319 if (
320 config_dict[target_type][k]["PROTOCOL"][0]
321 not in check_protocol_list
322 ):
323 check_protocol_list.append(
324 config_dict[target_type][k]["PROTOCOL"][0]
325 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500326
Patrick Williams20f38712022-12-08 06:18:26 -0600327 self.logger.info(
328 "\n\t %s protocol type: %s"
329 % (self.target_type, check_protocol_list)
330 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500331
George Keishingf5a57502021-07-22 16:43:47 -0500332 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500333
George Keishingf5a57502021-07-22 16:43:47 -0500334 if verified_working_protocol:
Patrick Williams20f38712022-12-08 06:18:26 -0600335 self.logger.info(
336 "\n\t---- Completed protocol pre-requisite check ----\n"
337 )
Peter D Phan0c669772021-06-24 13:52:42 -0500338
George Keishingf5a57502021-07-22 16:43:47 -0500339 # Verify top level directory exists for storage
340 self.validate_local_store(self.location)
341
Patrick Williams20f38712022-12-08 06:18:26 -0600342 if (self.remote_protocol not in verified_working_protocol) and (
343 self.remote_protocol != "ALL"
344 ):
345 self.logger.info(
346 "\n\tWorking protocol list: %s" % verified_working_protocol
347 )
George Keishingf5a57502021-07-22 16:43:47 -0500348 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600349 "\tERROR: Requested protocol %s is not in working protocol"
George Keishing7899a452023-02-15 02:46:54 -0600350 " list.\n" % self.remote_protocol
Patrick Williams20f38712022-12-08 06:18:26 -0600351 )
George Keishingf5a57502021-07-22 16:43:47 -0500352 sys.exit(-1)
353 else:
354 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500355
356 def ssh_to_target_system(self):
357 r"""
358 Open a ssh connection to targeted system.
359
360 """
361
Patrick Williams20f38712022-12-08 06:18:26 -0600362 self.ssh_remoteclient = SSHRemoteclient(
George Keishing7a61aa22023-06-26 13:18:37 +0530363 self.hostname, self.username, self.password, self.port_ssh
Patrick Williams20f38712022-12-08 06:18:26 -0600364 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500365
Peter D Phan5963d632021-07-12 09:58:55 -0500366 if self.ssh_remoteclient.ssh_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600367 self.logger.info(
368 "\n\t[Check] %s SSH connection established.\t [OK]"
369 % self.hostname
370 )
Peter D Phan733df632021-06-17 13:13:36 -0500371
Peter D Phan5963d632021-07-12 09:58:55 -0500372 # Check scp connection.
373 # If scp connection fails,
374 # continue with FFDC generation but skip scp files to local host.
375 self.ssh_remoteclient.scp_connection()
376 return True
377 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600378 self.logger.info(
379 "\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]"
380 % self.hostname
381 )
Peter D Phan5963d632021-07-12 09:58:55 -0500382 return False
383
384 def telnet_to_target_system(self):
385 r"""
386 Open a telnet connection to targeted system.
387 """
Patrick Williams20f38712022-12-08 06:18:26 -0600388 self.telnet_remoteclient = TelnetRemoteclient(
389 self.hostname, self.username, self.password
390 )
Peter D Phan5963d632021-07-12 09:58:55 -0500391 if self.telnet_remoteclient.tn_remoteclient_login():
Patrick Williams20f38712022-12-08 06:18:26 -0600392 self.logger.info(
393 "\n\t[Check] %s Telnet connection established.\t [OK]"
394 % self.hostname
395 )
Peter D Phan5963d632021-07-12 09:58:55 -0500396 return True
397 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600398 self.logger.info(
399 "\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]"
400 % self.hostname
401 )
Peter D Phan5963d632021-07-12 09:58:55 -0500402 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500403
George Keishing772c9772021-06-16 23:23:42 -0500404 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500405 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500406 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500407
Peter D Phan04aca3b2021-06-21 10:37:18 -0500408 Description of argument(s):
409 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500410 """
411
Patrick Williams20f38712022-12-08 06:18:26 -0600412 self.logger.info(
413 "\n\t---- Executing commands on " + self.hostname + " ----"
414 )
415 self.logger.info(
416 "\n\tWorking protocol list: %s" % working_protocol_list
417 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500418
George Keishingf5a57502021-07-22 16:43:47 -0500419 config_dict = self.ffdc_actions
420 for target_type in config_dict.keys():
421 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500422 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500423
Peter D Phane86d9a52021-07-15 10:42:25 -0500424 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
Patrick Williams20f38712022-12-08 06:18:26 -0600425 global_plugin_dict["global_log_store_path"] = self.ffdc_dir_path
George Keishingf5a57502021-07-22 16:43:47 -0500426 self.logger.info("\tSystem Type: %s" % target_type)
427 for k, v in config_dict[target_type].items():
Patrick Williams20f38712022-12-08 06:18:26 -0600428 if (
429 self.remote_protocol not in working_protocol_list
430 and self.remote_protocol != "ALL"
431 ):
George Keishing6ea92b02021-07-01 11:20:50 -0500432 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500433
Patrick Williams20f38712022-12-08 06:18:26 -0600434 protocol = config_dict[target_type][k]["PROTOCOL"][0]
George Keishingf5a57502021-07-22 16:43:47 -0500435
436 if protocol not in working_protocol_list:
437 continue
438
George Keishingb7607612021-07-27 13:31:23 -0500439 if protocol in working_protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -0600440 if protocol == "SSH" or protocol == "SCP":
George Keishing12fd0652021-07-27 13:57:11 -0500441 self.protocol_ssh(protocol, target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600442 elif protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -0500443 self.protocol_telnet(target_type, k)
Patrick Williams20f38712022-12-08 06:18:26 -0600444 elif (
445 protocol == "REDFISH"
446 or protocol == "IPMI"
447 or protocol == "SHELL"
448 ):
George Keishing506b0582021-07-27 09:31:22 -0500449 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500450 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600451 self.logger.error(
452 "\n\tERROR: %s is not available for %s."
453 % (protocol, self.hostname)
454 )
George Keishingeafba182021-06-29 13:44:58 -0500455
Peter D Phan04aca3b2021-06-21 10:37:18 -0500456 # Close network connection after collecting all files
Patrick Williams20f38712022-12-08 06:18:26 -0600457 self.elapsed_time = time.strftime(
458 "%H:%M:%S", time.gmtime(time.time() - self.start_time)
459 )
Peter D Phanbff617a2021-07-22 08:41:35 -0500460 if self.ssh_remoteclient:
461 self.ssh_remoteclient.ssh_remoteclient_disconnect()
462 if self.telnet_remoteclient:
463 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500464
Patrick Williams20f38712022-12-08 06:18:26 -0600465 def protocol_ssh(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500466 r"""
467 Perform actions using SSH and SCP protocols.
468
469 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500470 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500471 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500472 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500473 """
474
Patrick Williams20f38712022-12-08 06:18:26 -0600475 if protocol == "SCP":
George Keishingf5a57502021-07-22 16:43:47 -0500476 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500477 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600478 self.collect_and_copy_ffdc(
479 self.ffdc_actions[target_type][sub_type]
480 )
Peter D Phan0c669772021-06-24 13:52:42 -0500481
Patrick Williams20f38712022-12-08 06:18:26 -0600482 def protocol_telnet(self, target_type, sub_type):
Peter D Phan5963d632021-07-12 09:58:55 -0500483 r"""
484 Perform actions using telnet protocol.
485 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500486 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500487 """
Patrick Williams20f38712022-12-08 06:18:26 -0600488 self.logger.info(
489 "\n\t[Run] Executing commands on %s using %s"
490 % (self.hostname, "TELNET")
491 )
Peter D Phan5963d632021-07-12 09:58:55 -0500492 telnet_files_saved = []
493 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600494 list_of_commands = self.ffdc_actions[target_type][sub_type]["COMMANDS"]
Peter D Phan5963d632021-07-12 09:58:55 -0500495 for index, each_cmd in enumerate(list_of_commands, start=0):
496 command_txt, command_timeout = self.unpack_command(each_cmd)
Patrick Williams20f38712022-12-08 06:18:26 -0600497 result = self.telnet_remoteclient.execute_command(
498 command_txt, command_timeout
499 )
Peter D Phan5963d632021-07-12 09:58:55 -0500500 if result:
501 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600502 targ_file = self.ffdc_actions[target_type][sub_type][
503 "FILES"
504 ][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500505 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500506 targ_file = command_txt
507 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600508 "\n\t[WARN] Missing filename to store data from"
509 " telnet %s." % each_cmd
510 )
511 self.logger.warning(
512 "\t[WARN] Data will be stored in %s." % targ_file
513 )
514 targ_file_with_path = (
515 self.ffdc_dir_path + self.ffdc_prefix + targ_file
516 )
Peter D Phan5963d632021-07-12 09:58:55 -0500517 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600518 with open(targ_file_with_path, "w") as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500519 fp.write(result)
520 fp.close
521 telnet_files_saved.append(targ_file)
522 progress_counter += 1
523 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500524 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500525 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500526 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500527
Patrick Williams20f38712022-12-08 06:18:26 -0600528 def protocol_execute(self, protocol, target_type, sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500529 r"""
George Keishing506b0582021-07-27 09:31:22 -0500530 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500531
532 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500533 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500534 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500535 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500536 """
537
Patrick Williams20f38712022-12-08 06:18:26 -0600538 self.logger.info(
539 "\n\t[Run] Executing commands to %s using %s"
540 % (self.hostname, protocol)
541 )
George Keishing506b0582021-07-27 09:31:22 -0500542 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500543 progress_counter = 0
Patrick Williams20f38712022-12-08 06:18:26 -0600544 list_of_cmd = self.get_command_list(
545 self.ffdc_actions[target_type][sub_type]
546 )
George Keishingeafba182021-06-29 13:44:58 -0500547 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500548 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500549 if isinstance(each_cmd, dict):
Patrick Williams20f38712022-12-08 06:18:26 -0600550 if "plugin" in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500551 # If the error is set and plugin explicitly
552 # requested to skip execution on error..
Patrick Williams20f38712022-12-08 06:18:26 -0600553 if plugin_error_dict[
554 "exit_on_error"
555 ] and self.plugin_error_check(each_cmd["plugin"]):
556 self.logger.info(
557 "\n\t[PLUGIN-ERROR] exit_on_error: %s"
558 % plugin_error_dict["exit_on_error"]
559 )
560 self.logger.info(
561 "\t[PLUGIN-SKIP] %s" % each_cmd["plugin"][0]
562 )
George Keishing1e7b0182021-08-06 14:05:54 -0500563 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500564 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500565 # call the plugin
566 self.logger.info("\n\t[PLUGIN-START]")
Patrick Williams20f38712022-12-08 06:18:26 -0600567 result = self.execute_plugin_block(each_cmd["plugin"])
George Keishingb97a9042021-07-29 07:41:20 -0500568 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500569 else:
George Keishing2b83e042021-08-03 12:56:11 -0500570 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500571
George Keishingcaa97e62021-08-03 14:00:09 -0500572 if not plugin_call:
573 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500574 if result:
575 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600576 file_name = self.get_file_list(
577 self.ffdc_actions[target_type][sub_type]
578 )[index]
George Keishingb97a9042021-07-29 07:41:20 -0500579 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500580 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500581 continue
Patrick Williams20f38712022-12-08 06:18:26 -0600582 targ_file = self.yaml_env_and_plugin_vars_populate(
583 file_name
584 )
George Keishingeafba182021-06-29 13:44:58 -0500585 except IndexError:
Patrick Williams20f38712022-12-08 06:18:26 -0600586 targ_file = each_cmd.split("/")[-1]
George Keishing506b0582021-07-27 09:31:22 -0500587 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600588 "\n\t[WARN] Missing filename to store data from %s."
589 % each_cmd
590 )
591 self.logger.warning(
592 "\t[WARN] Data will be stored in %s." % targ_file
593 )
George Keishingeafba182021-06-29 13:44:58 -0500594
Patrick Williams20f38712022-12-08 06:18:26 -0600595 targ_file_with_path = (
596 self.ffdc_dir_path + self.ffdc_prefix + targ_file
597 )
George Keishingeafba182021-06-29 13:44:58 -0500598
599 # Creates a new file
Patrick Williams20f38712022-12-08 06:18:26 -0600600 with open(targ_file_with_path, "w") as fp:
George Keishing91308ea2021-08-10 14:43:15 -0500601 if isinstance(result, dict):
602 fp.write(json.dumps(result))
603 else:
604 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500605 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500606 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500607
608 progress_counter += 1
609 self.print_progress(progress_counter)
610
Peter D Phane86d9a52021-07-15 10:42:25 -0500611 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500612
George Keishing506b0582021-07-27 09:31:22 -0500613 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500614 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500615
Patrick Williams20f38712022-12-08 06:18:26 -0600616 def collect_and_copy_ffdc(
617 self, ffdc_actions_for_target_type, form_filename=False
618 ):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500619 r"""
620 Send commands in ffdc_config file to targeted system.
621
622 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500623 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500624 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500625 """
626
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500627 # Executing commands, if any
Patrick Williams20f38712022-12-08 06:18:26 -0600628 self.ssh_execute_ffdc_commands(
629 ffdc_actions_for_target_type, form_filename
630 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500631
Peter D Phan3beb02e2021-07-06 13:25:17 -0500632 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500633 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600634 self.logger.info(
635 "\n\n\tCopying FFDC files from remote system %s.\n"
636 % self.hostname
637 )
Peter D Phan2b8052d2021-06-22 10:55:41 -0500638
Peter D Phan04aca3b2021-06-21 10:37:18 -0500639 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500640 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Patrick Williams20f38712022-12-08 06:18:26 -0600641 self.scp_ffdc(
642 self.ffdc_dir_path,
643 self.ffdc_prefix,
644 form_filename,
645 list_of_files,
646 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500647 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600648 self.logger.info(
649 "\n\n\tSkip copying FFDC files from remote system %s.\n"
650 % self.hostname
651 )
Peter D Phan04aca3b2021-06-21 10:37:18 -0500652
Patrick Williams20f38712022-12-08 06:18:26 -0600653 def get_command_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500654 r"""
655 Fetch list of commands from configuration file
656
657 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500658 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500659 """
660 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600661 list_of_commands = ffdc_actions_for_target_type["COMMANDS"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500662 except KeyError:
663 list_of_commands = []
664 return list_of_commands
665
Patrick Williams20f38712022-12-08 06:18:26 -0600666 def get_file_list(self, ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500667 r"""
668 Fetch list of commands from configuration file
669
670 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500671 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500672 """
673 try:
Patrick Williams20f38712022-12-08 06:18:26 -0600674 list_of_files = ffdc_actions_for_target_type["FILES"]
Peter D Phanbabf2962021-07-07 11:24:40 -0500675 except KeyError:
676 list_of_files = []
677 return list_of_files
678
Patrick Williams20f38712022-12-08 06:18:26 -0600679 def unpack_command(self, command):
Peter D Phan5963d632021-07-12 09:58:55 -0500680 r"""
681 Unpack command from config file
682
683 Description of argument(s):
684 command Command from config file.
685 """
686 if isinstance(command, dict):
687 command_txt = next(iter(command))
688 command_timeout = next(iter(command.values()))
689 elif isinstance(command, str):
690 command_txt = command
691 # Default command timeout 60 seconds
692 command_timeout = 60
693
694 return command_txt, command_timeout
695
Patrick Williams20f38712022-12-08 06:18:26 -0600696 def ssh_execute_ffdc_commands(
697 self, ffdc_actions_for_target_type, form_filename=False
698 ):
Peter D Phan3beb02e2021-07-06 13:25:17 -0500699 r"""
700 Send commands in ffdc_config file to targeted system.
701
702 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500703 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500704 form_filename if true, pre-pend self.target_type to filename
705 """
Patrick Williams20f38712022-12-08 06:18:26 -0600706 self.logger.info(
707 "\n\t[Run] Executing commands on %s using %s"
708 % (self.hostname, ffdc_actions_for_target_type["PROTOCOL"][0])
709 )
Peter D Phan3beb02e2021-07-06 13:25:17 -0500710
George Keishingf5a57502021-07-22 16:43:47 -0500711 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500712 # If command list is empty, returns
713 if not list_of_commands:
714 return
715
716 progress_counter = 0
717 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500718 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500719
720 if form_filename:
721 command_txt = str(command_txt % self.target_type)
722
Patrick Williams20f38712022-12-08 06:18:26 -0600723 (
724 cmd_exit_code,
725 err,
726 response,
727 ) = self.ssh_remoteclient.execute_command(
728 command_txt, command_timeout
729 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500730
731 if cmd_exit_code:
732 self.logger.warning(
Patrick Williams20f38712022-12-08 06:18:26 -0600733 "\n\t\t[WARN] %s exits with code %s."
734 % (command_txt, str(cmd_exit_code))
735 )
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500736 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500737
Peter D Phan3beb02e2021-07-06 13:25:17 -0500738 progress_counter += 1
739 self.print_progress(progress_counter)
740
Peter D Phane86d9a52021-07-15 10:42:25 -0500741 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500742
Patrick Williams20f38712022-12-08 06:18:26 -0600743 def group_copy(self, ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500744 r"""
745 scp group of files (wild card) from remote host.
746
747 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500748 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500749 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500750
Peter D Phan5963d632021-07-12 09:58:55 -0500751 if self.ssh_remoteclient.scpclient:
Patrick Williams20f38712022-12-08 06:18:26 -0600752 self.logger.info(
753 "\n\tCopying files from remote system %s via SCP.\n"
754 % self.hostname
755 )
Peter D Phan56429a62021-06-23 08:38:29 -0500756
Patrick Williams20f38712022-12-08 06:18:26 -0600757 list_of_commands = self.get_command_list(
758 ffdc_actions_for_target_type
759 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500760 # If command list is empty, returns
761 if not list_of_commands:
762 return
Peter D Phan56429a62021-06-23 08:38:29 -0500763
Peter D Phanbabf2962021-07-07 11:24:40 -0500764 for command in list_of_commands:
765 try:
George Keishingb4540e72021-08-02 13:48:46 -0500766 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500767 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500768 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500769 continue
770
Patrick Williams20f38712022-12-08 06:18:26 -0600771 (
772 cmd_exit_code,
773 err,
774 response,
775 ) = self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500776
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500777 # If file does not exist, code take no action.
778 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500779 if response:
Patrick Williams20f38712022-12-08 06:18:26 -0600780 scp_result = self.ssh_remoteclient.scp_file_from_remote(
781 response.split("\n"), self.ffdc_dir_path
782 )
Peter D Phan56429a62021-06-23 08:38:29 -0500783 if scp_result:
Patrick Williams20f38712022-12-08 06:18:26 -0600784 self.logger.info(
785 "\t\tSuccessfully copied from "
786 + self.hostname
787 + ":"
788 + command
789 )
Peter D Phan56429a62021-06-23 08:38:29 -0500790 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500791 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500792
793 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600794 self.logger.info(
795 "\n\n\tSkip copying files from remote system %s.\n"
796 % self.hostname
797 )
Peter D Phan56429a62021-06-23 08:38:29 -0500798
Patrick Williams20f38712022-12-08 06:18:26 -0600799 def scp_ffdc(
800 self,
801 targ_dir_path,
802 targ_file_prefix,
803 form_filename,
804 file_list=None,
805 quiet=None,
806 ):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500807 r"""
808 SCP all files in file_dict to the indicated directory on the local system.
809
810 Description of argument(s):
811 targ_dir_path The path of the directory to receive the files.
George Keishinge16f1582022-12-15 07:32:21 -0600812 targ_file_prefix Prefix which will be prepended to each
Peter D Phan72ce6b82021-06-03 06:18:26 -0500813 target file's name.
814 file_dict A dictionary of files to scp from targeted system to this system
815
816 """
817
Peter D Phan72ce6b82021-06-03 06:18:26 -0500818 progress_counter = 0
819 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500820 if form_filename:
821 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500822 source_file_path = filename
Patrick Williams20f38712022-12-08 06:18:26 -0600823 targ_file_path = (
824 targ_dir_path + targ_file_prefix + filename.split("/")[-1]
825 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500826
Peter D Phanbabf2962021-07-07 11:24:40 -0500827 # If source file name contains wild card, copy filename as is.
Patrick Williams20f38712022-12-08 06:18:26 -0600828 if "*" in source_file_path:
829 scp_result = self.ssh_remoteclient.scp_file_from_remote(
830 source_file_path, self.ffdc_dir_path
831 )
Peter D Phanbabf2962021-07-07 11:24:40 -0500832 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600833 scp_result = self.ssh_remoteclient.scp_file_from_remote(
834 source_file_path, targ_file_path
835 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500836
837 if not quiet:
838 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500839 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600840 "\t\tSuccessfully copied from "
841 + self.hostname
842 + ":"
843 + source_file_path
844 + ".\n"
845 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500846 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500847 self.logger.info(
Patrick Williams20f38712022-12-08 06:18:26 -0600848 "\t\tFail to copy from "
849 + self.hostname
850 + ":"
851 + source_file_path
852 + ".\n"
853 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500854 else:
855 progress_counter += 1
856 self.print_progress(progress_counter)
857
Peter D Phan5e56f522021-12-20 13:19:41 -0600858 def set_ffdc_default_store_path(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500859 r"""
860 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
861 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
862 Individual ffdc file will have timestr_filename.
863
864 Description of class variables:
865 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
866
867 self.ffdc_prefix The prefix to be given to each ffdc file name.
868
869 """
870
871 timestr = time.strftime("%Y%m%d-%H%M%S")
Patrick Williams20f38712022-12-08 06:18:26 -0600872 self.ffdc_dir_path = (
873 self.location + "/" + self.hostname + "_" + timestr + "/"
874 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500875 self.ffdc_prefix = timestr + "_"
876 self.validate_local_store(self.ffdc_dir_path)
877
Peter D Phan5e56f522021-12-20 13:19:41 -0600878 # Need to verify local store path exists prior to instantiate this class.
879 # This class method is used to share the same code between CLI input parm
880 # and Robot Framework "${EXECDIR}/logs" before referencing this class.
881 @classmethod
882 def validate_local_store(cls, dir_path):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500883 r"""
884 Ensure path exists to store FFDC files locally.
885
886 Description of variable:
887 dir_path The dir path where collected ffdc data files will be stored.
888
889 """
890
891 if not os.path.exists(dir_path):
892 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500893 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500894 except (IOError, OSError) as e:
895 # PermissionError
896 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500897 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600898 "\tERROR: os.makedirs %s failed with"
899 " PermissionError.\n" % dir_path
900 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500901 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500902 self.logger.error(
Patrick Williams20f38712022-12-08 06:18:26 -0600903 "\tERROR: os.makedirs %s failed with %s.\n"
904 % (dir_path, e.strerror)
905 )
Peter D Phan72ce6b82021-06-03 06:18:26 -0500906 sys.exit(-1)
907
908 def print_progress(self, progress):
909 r"""
910 Print activity progress +
911
912 Description of variable:
913 progress Progress counter.
914
915 """
916
917 sys.stdout.write("\r\t" + "+" * progress)
918 sys.stdout.flush()
Patrick Williams20f38712022-12-08 06:18:26 -0600919 time.sleep(0.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500920
921 def verify_redfish(self):
922 r"""
923 Verify remote host has redfish service active
924
925 """
Patrick Williams20f38712022-12-08 06:18:26 -0600926 redfish_parm = (
927 "redfishtool -r "
928 + self.hostname
George Keishing7a61aa22023-06-26 13:18:37 +0530929 + ":"
930 + self.port_https
Patrick Williams20f38712022-12-08 06:18:26 -0600931 + " -S Always raw GET /redfish/v1/"
932 )
933 return self.run_tool_cmd(redfish_parm, True)
Peter D Phan0c669772021-06-24 13:52:42 -0500934
George Keishingeafba182021-06-29 13:44:58 -0500935 def verify_ipmi(self):
936 r"""
937 Verify remote host has IPMI LAN service active
938
939 """
Patrick Williams20f38712022-12-08 06:18:26 -0600940 if self.target_type == "OPENBMC":
941 ipmi_parm = (
942 "ipmitool -I lanplus -C 17 -U "
943 + self.username
944 + " -P "
945 + self.password
946 + " -H "
947 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530948 + " -p "
949 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600950 + " power status"
951 )
George Keishing484f8242021-07-27 01:42:02 -0500952 else:
Patrick Williams20f38712022-12-08 06:18:26 -0600953 ipmi_parm = (
954 "ipmitool -I lanplus -P "
955 + self.password
956 + " -H "
957 + self.hostname
George Keishinge8a41752023-06-22 21:42:47 +0530958 + " -p "
959 + str(self.port_ipmi)
Patrick Williams20f38712022-12-08 06:18:26 -0600960 + " power status"
961 )
George Keishing484f8242021-07-27 01:42:02 -0500962
Patrick Williams20f38712022-12-08 06:18:26 -0600963 return self.run_tool_cmd(ipmi_parm, True)
George Keishingeafba182021-06-29 13:44:58 -0500964
Patrick Williams20f38712022-12-08 06:18:26 -0600965 def run_tool_cmd(self, parms_string, quiet=False):
George Keishingeafba182021-06-29 13:44:58 -0500966 r"""
George Keishing506b0582021-07-27 09:31:22 -0500967 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500968
969 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500970 parms_string tool command options.
971 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500972 """
973
Patrick Williams20f38712022-12-08 06:18:26 -0600974 result = subprocess.run(
975 [parms_string],
976 stdout=subprocess.PIPE,
977 stderr=subprocess.PIPE,
978 shell=True,
979 universal_newlines=True,
980 )
George Keishingeafba182021-06-29 13:44:58 -0500981
982 if result.stderr and not quiet:
Patrick Williams20f38712022-12-08 06:18:26 -0600983 self.logger.error("\n\t\tERROR with %s " % parms_string)
984 self.logger.error("\t\t" + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500985
986 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500987
George Keishingf5a57502021-07-22 16:43:47 -0500988 def verify_protocol(self, protocol_list):
989 r"""
990 Perform protocol working check.
991
992 Description of argument(s):
993 protocol_list List of protocol.
994 """
995
996 tmp_list = []
997 if self.target_is_pingable():
998 tmp_list.append("SHELL")
999
1000 for protocol in protocol_list:
Patrick Williams20f38712022-12-08 06:18:26 -06001001 if self.remote_protocol != "ALL":
George Keishingf5a57502021-07-22 16:43:47 -05001002 if self.remote_protocol != protocol:
1003 continue
1004
1005 # Only check SSH/SCP once for both protocols
Patrick Williams20f38712022-12-08 06:18:26 -06001006 if (
1007 protocol == "SSH"
1008 or protocol == "SCP"
1009 and protocol not in tmp_list
1010 ):
George Keishingf5a57502021-07-22 16:43:47 -05001011 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -05001012 # Add only what user asked.
Patrick Williams20f38712022-12-08 06:18:26 -06001013 if self.remote_protocol != "ALL":
George Keishingaa638702021-07-26 11:48:28 -05001014 tmp_list.append(self.remote_protocol)
1015 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001016 tmp_list.append("SSH")
1017 tmp_list.append("SCP")
George Keishingf5a57502021-07-22 16:43:47 -05001018
Patrick Williams20f38712022-12-08 06:18:26 -06001019 if protocol == "TELNET":
George Keishingf5a57502021-07-22 16:43:47 -05001020 if self.telnet_to_target_system():
1021 tmp_list.append(protocol)
1022
Patrick Williams20f38712022-12-08 06:18:26 -06001023 if protocol == "REDFISH":
George Keishingf5a57502021-07-22 16:43:47 -05001024 if self.verify_redfish():
1025 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001026 self.logger.info(
1027 "\n\t[Check] %s Redfish Service.\t\t [OK]"
1028 % self.hostname
1029 )
George Keishingf5a57502021-07-22 16:43:47 -05001030 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001031 self.logger.info(
1032 "\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]"
1033 % self.hostname
1034 )
George Keishingf5a57502021-07-22 16:43:47 -05001035
Patrick Williams20f38712022-12-08 06:18:26 -06001036 if protocol == "IPMI":
George Keishingf5a57502021-07-22 16:43:47 -05001037 if self.verify_ipmi():
1038 tmp_list.append(protocol)
Patrick Williams20f38712022-12-08 06:18:26 -06001039 self.logger.info(
1040 "\n\t[Check] %s IPMI LAN Service.\t\t [OK]"
1041 % self.hostname
1042 )
George Keishingf5a57502021-07-22 16:43:47 -05001043 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001044 self.logger.info(
1045 "\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]"
1046 % self.hostname
1047 )
George Keishingf5a57502021-07-22 16:43:47 -05001048
1049 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -05001050
1051 def load_env(self):
1052 r"""
1053 Perform protocol working check.
1054
1055 """
1056 # This is for the env vars a user can use in YAML to load it at runtime.
1057 # Example YAML:
1058 # -COMMANDS:
1059 # - my_command ${hostname} ${username} ${password}
Patrick Williams20f38712022-12-08 06:18:26 -06001060 os.environ["hostname"] = self.hostname
1061 os.environ["username"] = self.username
1062 os.environ["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301063 os.environ["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301064 os.environ["port_https"] = self.port_https
1065 os.environ["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001066
1067 # Append default Env.
Patrick Williams20f38712022-12-08 06:18:26 -06001068 self.env_dict["hostname"] = self.hostname
1069 self.env_dict["username"] = self.username
1070 self.env_dict["password"] = self.password
George Keishing7a61aa22023-06-26 13:18:37 +05301071 self.env_dict["port_ssh"] = self.port_ssh
George Keishinge8a41752023-06-22 21:42:47 +05301072 self.env_dict["port_https"] = self.port_https
1073 self.env_dict["port_ipmi"] = self.port_ipmi
George Keishinge1686752021-07-27 12:55:28 -05001074
1075 try:
1076 tmp_env_dict = {}
1077 if self.env_vars:
1078 tmp_env_dict = json.loads(self.env_vars)
1079 # Export ENV vars default.
1080 for key, value in tmp_env_dict.items():
1081 os.environ[key] = value
1082 self.env_dict[key] = str(value)
1083
1084 if self.econfig:
Patrick Williams20f38712022-12-08 06:18:26 -06001085 with open(self.econfig, "r") as file:
George Keishinge9b23d32021-08-13 12:57:58 -05001086 try:
Yunyun Linf87cc0a2022-06-08 16:57:04 -07001087 tmp_env_dict = yaml.load(file, Loader=yaml.SafeLoader)
George Keishinge9b23d32021-08-13 12:57:58 -05001088 except yaml.YAMLError as e:
1089 self.logger.error(e)
1090 sys.exit(-1)
George Keishinge1686752021-07-27 12:55:28 -05001091 # Export ENV vars.
Patrick Williams20f38712022-12-08 06:18:26 -06001092 for key, value in tmp_env_dict["env_params"].items():
George Keishinge1686752021-07-27 12:55:28 -05001093 os.environ[key] = str(value)
1094 self.env_dict[key] = str(value)
1095 except json.decoder.JSONDecodeError as e:
1096 self.logger.error("\n\tERROR: %s " % e)
1097 sys.exit(-1)
1098
1099 # This to mask the password from displaying on the console.
1100 mask_dict = self.env_dict.copy()
1101 for k, v in mask_dict.items():
1102 if k.lower().find("password") != -1:
1103 hidden_text = []
1104 hidden_text.append(v)
Patrick Williams20f38712022-12-08 06:18:26 -06001105 password_regex = (
1106 "(" + "|".join([re.escape(x) for x in hidden_text]) + ")"
1107 )
George Keishinge1686752021-07-27 12:55:28 -05001108 mask_dict[k] = re.sub(password_regex, "********", v)
1109
1110 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -05001111
1112 def execute_python_eval(self, eval_string):
1113 r"""
George Keishing9348b402021-08-13 12:22:35 -05001114 Execute qualified python function string using eval.
George Keishingb97a9042021-07-29 07:41:20 -05001115
1116 Description of argument(s):
1117 eval_string Execute the python object.
1118
1119 Example:
1120 eval(plugin.foo_func.foo_func(10))
1121 """
1122 try:
George Keishingdda48ce2021-08-12 07:02:27 -05001123 self.logger.info("\tExecuting plugin func()")
1124 self.logger.debug("\tCall func: %s" % eval_string)
George Keishingb97a9042021-07-29 07:41:20 -05001125 result = eval(eval_string)
1126 self.logger.info("\treturn: %s" % str(result))
Patrick Williams20f38712022-12-08 06:18:26 -06001127 except (
1128 ValueError,
1129 SyntaxError,
1130 NameError,
1131 AttributeError,
1132 TypeError,
1133 ) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001134 self.logger.error("\tERROR: execute_python_eval: %s" % e)
1135 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001136 plugin_error_dict["exit_on_error"] = True
George Keishing73b95d12021-08-13 14:30:52 -05001137 self.logger.info("\treturn: PLUGIN_EVAL_ERROR")
Patrick Williams20f38712022-12-08 06:18:26 -06001138 return "PLUGIN_EVAL_ERROR"
George Keishingb97a9042021-07-29 07:41:20 -05001139
1140 return result
1141
1142 def execute_plugin_block(self, plugin_cmd_list):
1143 r"""
Peter D Phan5e56f522021-12-20 13:19:41 -06001144 Pack the plugin command to qualifed python string object.
George Keishingb97a9042021-07-29 07:41:20 -05001145
1146 Description of argument(s):
1147 plugin_list_dict Plugin block read from YAML
1148 [{'plugin_name': 'plugin.foo_func.my_func'},
1149 {'plugin_args': [10]}]
1150
1151 Example:
1152 - plugin:
1153 - plugin_name: plugin.foo_func.my_func
1154 - plugin_args:
1155 - arg1
1156 - arg2
1157
1158 - plugin:
1159 - plugin_name: result = plugin.foo_func.my_func
1160 - plugin_args:
1161 - arg1
1162 - arg2
1163
1164 - plugin:
1165 - plugin_name: result1,result2 = plugin.foo_func.my_func
1166 - plugin_args:
1167 - arg1
1168 - arg2
1169 """
1170 try:
Patrick Williams20f38712022-12-08 06:18:26 -06001171 idx = self.key_index_list_dict("plugin_name", plugin_cmd_list)
1172 plugin_name = plugin_cmd_list[idx]["plugin_name"]
George Keishingb97a9042021-07-29 07:41:20 -05001173 # Equal separator means plugin function returns result.
Patrick Williams20f38712022-12-08 06:18:26 -06001174 if " = " in plugin_name:
George Keishingb97a9042021-07-29 07:41:20 -05001175 # Ex. ['result', 'plugin.foo_func.my_func']
Patrick Williams20f38712022-12-08 06:18:26 -06001176 plugin_name_args = plugin_name.split(" = ")
George Keishingb97a9042021-07-29 07:41:20 -05001177 # plugin func return data.
1178 for arg in plugin_name_args:
1179 if arg == plugin_name_args[-1]:
1180 plugin_name = arg
1181 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001182 plugin_resp = arg.split(",")
George Keishingb97a9042021-07-29 07:41:20 -05001183 # ['result1','result2']
1184 for x in plugin_resp:
1185 global_plugin_list.append(x)
1186 global_plugin_dict[x] = ""
1187
1188 # Walk the plugin args ['arg1,'arg2']
1189 # If the YAML plugin statement 'plugin_args' is not declared.
Patrick Williams20f38712022-12-08 06:18:26 -06001190 if any("plugin_args" in d for d in plugin_cmd_list):
1191 idx = self.key_index_list_dict("plugin_args", plugin_cmd_list)
1192 plugin_args = plugin_cmd_list[idx]["plugin_args"]
George Keishingb97a9042021-07-29 07:41:20 -05001193 if plugin_args:
1194 plugin_args = self.yaml_args_populate(plugin_args)
1195 else:
1196 plugin_args = []
1197 else:
1198 plugin_args = self.yaml_args_populate([])
1199
1200 # Pack the args arg1, arg2, .... argn into
1201 # "arg1","arg2","argn" string as params for function.
1202 parm_args_str = self.yaml_args_string(plugin_args)
1203 if parm_args_str:
Patrick Williams20f38712022-12-08 06:18:26 -06001204 plugin_func = plugin_name + "(" + parm_args_str + ")"
George Keishingb97a9042021-07-29 07:41:20 -05001205 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001206 plugin_func = plugin_name + "()"
George Keishingb97a9042021-07-29 07:41:20 -05001207
1208 # Execute plugin function.
1209 if global_plugin_dict:
1210 resp = self.execute_python_eval(plugin_func)
George Keishing9348b402021-08-13 12:22:35 -05001211 # Update plugin vars dict if there is any.
Patrick Williams20f38712022-12-08 06:18:26 -06001212 if resp != "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001213 self.response_args_data(resp)
George Keishingb97a9042021-07-29 07:41:20 -05001214 else:
George Keishingcaa97e62021-08-03 14:00:09 -05001215 resp = self.execute_python_eval(plugin_func)
George Keishingb97a9042021-07-29 07:41:20 -05001216 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001217 # Set the plugin error state.
Patrick Williams20f38712022-12-08 06:18:26 -06001218 plugin_error_dict["exit_on_error"] = True
George Keishing1e7b0182021-08-06 14:05:54 -05001219 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001220 pass
1221
George Keishing73b95d12021-08-13 14:30:52 -05001222 # There is a real error executing the plugin function.
Patrick Williams20f38712022-12-08 06:18:26 -06001223 if resp == "PLUGIN_EVAL_ERROR":
George Keishing73b95d12021-08-13 14:30:52 -05001224 return resp
1225
George Keishingde79a9b2021-08-12 16:14:43 -05001226 # Check if plugin_expects_return (int, string, list,dict etc)
Patrick Williams20f38712022-12-08 06:18:26 -06001227 if any("plugin_expects_return" in d for d in plugin_cmd_list):
1228 idx = self.key_index_list_dict(
1229 "plugin_expects_return", plugin_cmd_list
1230 )
1231 plugin_expects = plugin_cmd_list[idx]["plugin_expects_return"]
George Keishingde79a9b2021-08-12 16:14:43 -05001232 if plugin_expects:
1233 if resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001234 if (
1235 self.plugin_expect_type(plugin_expects, resp)
1236 == "INVALID"
1237 ):
George Keishingde79a9b2021-08-12 16:14:43 -05001238 self.logger.error("\tWARN: Plugin error check skipped")
1239 elif not self.plugin_expect_type(plugin_expects, resp):
Patrick Williams20f38712022-12-08 06:18:26 -06001240 self.logger.error(
1241 "\tERROR: Plugin expects return data: %s"
1242 % plugin_expects
1243 )
1244 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001245 elif not resp:
Patrick Williams20f38712022-12-08 06:18:26 -06001246 self.logger.error(
1247 "\tERROR: Plugin func failed to return data"
1248 )
1249 plugin_error_dict["exit_on_error"] = True
George Keishingde79a9b2021-08-12 16:14:43 -05001250
1251 return resp
1252
George Keishingb97a9042021-07-29 07:41:20 -05001253 def response_args_data(self, plugin_resp):
1254 r"""
George Keishing9348b402021-08-13 12:22:35 -05001255 Parse the plugin function response and update plugin return variable.
George Keishingb97a9042021-07-29 07:41:20 -05001256
1257 plugin_resp Response data from plugin function.
1258 """
1259 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -05001260 resp_data = ""
George Keishing9348b402021-08-13 12:22:35 -05001261
George Keishingb97a9042021-07-29 07:41:20 -05001262 # There is nothing to update the plugin response.
Patrick Williams20f38712022-12-08 06:18:26 -06001263 if len(global_plugin_list) == 0 or plugin_resp == "None":
George Keishingb97a9042021-07-29 07:41:20 -05001264 return
1265
George Keishing5765f792021-08-02 13:08:53 -05001266 if isinstance(plugin_resp, str):
Patrick Williams20f38712022-12-08 06:18:26 -06001267 resp_data = plugin_resp.strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001268 resp_list.append(resp_data)
1269 elif isinstance(plugin_resp, bytes):
Patrick Williams20f38712022-12-08 06:18:26 -06001270 resp_data = str(plugin_resp, "UTF-8").strip("\r\n\t")
George Keishing5765f792021-08-02 13:08:53 -05001271 resp_list.append(resp_data)
1272 elif isinstance(plugin_resp, tuple):
1273 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -05001274 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -05001275 else:
1276 resp_list = list(plugin_resp)
Patrick Williams20f38712022-12-08 06:18:26 -06001277 resp_list = [x.strip("\r\n\t") for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -05001278 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -05001279 if len(global_plugin_list) == 1:
Patrick Williams20f38712022-12-08 06:18:26 -06001280 resp_list.append([x.strip("\r\n\t") for x in plugin_resp])
George Keishing5765f792021-08-02 13:08:53 -05001281 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001282 resp_list = [x.strip("\r\n\t") for x in plugin_resp]
George Keishing5765f792021-08-02 13:08:53 -05001283 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1284 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001285
George Keishing9348b402021-08-13 12:22:35 -05001286 # Iterate if there is a list of plugin return vars to update.
George Keishingb97a9042021-07-29 07:41:20 -05001287 for idx, item in enumerate(resp_list, start=0):
George Keishing9348b402021-08-13 12:22:35 -05001288 # Exit loop, done required loop.
George Keishingb97a9042021-07-29 07:41:20 -05001289 if idx >= len(global_plugin_list):
1290 break
1291 # Find the index of the return func in the list and
1292 # update the global func return dictionary.
1293 try:
1294 dict_idx = global_plugin_list[idx]
1295 global_plugin_dict[dict_idx] = item
1296 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001297 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001298 pass
1299
1300 # Done updating plugin dict irrespective of pass or failed,
George Keishing9348b402021-08-13 12:22:35 -05001301 # clear all the list element for next plugin block execute.
George Keishingb97a9042021-07-29 07:41:20 -05001302 global_plugin_list.clear()
1303
1304 def yaml_args_string(self, plugin_args):
1305 r"""
1306 Pack the args into string.
1307
1308 plugin_args arg list ['arg1','arg2,'argn']
1309 """
Patrick Williams20f38712022-12-08 06:18:26 -06001310 args_str = ""
George Keishingb97a9042021-07-29 07:41:20 -05001311 for args in plugin_args:
1312 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001313 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001314 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001315 elif args in global_plugin_type_list:
1316 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001317 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001318 args_str += '"' + str(args.strip("\r\n\t")) + '"'
George Keishingb97a9042021-07-29 07:41:20 -05001319 # Skip last list element.
1320 if args != plugin_args[-1]:
1321 args_str += ","
1322 return args_str
1323
1324 def yaml_args_populate(self, yaml_arg_list):
1325 r"""
George Keishing9348b402021-08-13 12:22:35 -05001326 Decode env and plugin vars and populate.
George Keishingb97a9042021-07-29 07:41:20 -05001327
1328 Description of argument(s):
1329 yaml_arg_list arg list read from YAML
1330
1331 Example:
1332 - plugin_args:
1333 - arg1
1334 - arg2
1335
1336 yaml_arg_list: [arg2, arg2]
1337 """
1338 # Get the env loaded keys as list ['hostname', 'username', 'password'].
1339 env_vars_list = list(self.env_dict)
1340
1341 if isinstance(yaml_arg_list, list):
1342 tmp_list = []
1343 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001344 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001345 tmp_list.append(arg)
1346 continue
1347 elif isinstance(arg, str):
1348 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1349 tmp_list.append(arg_str)
1350 else:
1351 tmp_list.append(arg)
1352
1353 # return populated list.
1354 return tmp_list
1355
1356 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1357 r"""
George Keishing9348b402021-08-13 12:22:35 -05001358 Update ${MY_VAR} and plugin vars.
George Keishingb97a9042021-07-29 07:41:20 -05001359
1360 Description of argument(s):
George Keishing9348b402021-08-13 12:22:35 -05001361 yaml_arg_str arg string read from YAML.
George Keishingb97a9042021-07-29 07:41:20 -05001362
1363 Example:
1364 - cat ${MY_VAR}
1365 - ls -AX my_plugin_var
1366 """
George Keishing9348b402021-08-13 12:22:35 -05001367 # Parse the string for env vars ${env_vars}.
George Keishingb97a9042021-07-29 07:41:20 -05001368 try:
1369 # Example, list of matching env vars ['username', 'password', 'hostname']
1370 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
Patrick Williams20f38712022-12-08 06:18:26 -06001371 var_name_regex = "\\$\\{([^\\}]+)\\}"
George Keishingb97a9042021-07-29 07:41:20 -05001372 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1373 for var in env_var_names_list:
1374 env_var = os.environ[var]
Patrick Williams20f38712022-12-08 06:18:26 -06001375 env_replace = "${" + var + "}"
George Keishingb97a9042021-07-29 07:41:20 -05001376 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1377 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001378 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001379 pass
1380
1381 # Parse the string for plugin vars.
1382 try:
1383 # Example, list of plugin vars ['my_username', 'my_data']
1384 plugin_var_name_list = global_plugin_dict.keys()
1385 for var in plugin_var_name_list:
George Keishing9348b402021-08-13 12:22:35 -05001386 # skip env var list already populated above code block list.
George Keishing0581cb02021-08-05 15:08:58 -05001387 if var in env_var_names_list:
1388 continue
George Keishing9348b402021-08-13 12:22:35 -05001389 # If this plugin var exist but empty in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001390 # This is either a YAML plugin statement incorrectly used or
George Keishing9348b402021-08-13 12:22:35 -05001391 # user added a plugin var which is not going to be populated.
George Keishing0581cb02021-08-05 15:08:58 -05001392 if yaml_arg_str in global_plugin_dict:
1393 if isinstance(global_plugin_dict[var], (list, dict)):
1394 # List data type or dict can't be replaced, use directly
1395 # in eval function call.
1396 global_plugin_type_list.append(var)
1397 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001398 yaml_arg_str = yaml_arg_str.replace(
1399 str(var), str(global_plugin_dict[var])
1400 )
George Keishing0581cb02021-08-05 15:08:58 -05001401 # Just a string like filename or command.
1402 else:
Patrick Williams20f38712022-12-08 06:18:26 -06001403 yaml_arg_str = yaml_arg_str.replace(
1404 str(var), str(global_plugin_dict[var])
1405 )
George Keishingb97a9042021-07-29 07:41:20 -05001406 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001407 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001408 pass
1409
1410 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001411
1412 def plugin_error_check(self, plugin_dict):
1413 r"""
1414 Plugin error dict processing.
1415
1416 Description of argument(s):
1417 plugin_dict Dictionary of plugin error.
1418 """
Patrick Williams20f38712022-12-08 06:18:26 -06001419 if any("plugin_error" in d for d in plugin_dict):
George Keishing1e7b0182021-08-06 14:05:54 -05001420 for d in plugin_dict:
Patrick Williams20f38712022-12-08 06:18:26 -06001421 if "plugin_error" in d:
1422 value = d["plugin_error"]
George Keishing1e7b0182021-08-06 14:05:54 -05001423 # Reference if the error is set or not by plugin.
1424 return plugin_error_dict[value]
George Keishingde79a9b2021-08-12 16:14:43 -05001425
1426 def key_index_list_dict(self, key, list_dict):
1427 r"""
1428 Iterate list of dictionary and return index if the key match is found.
1429
1430 Description of argument(s):
1431 key Valid Key in a dict.
1432 list_dict list of dictionary.
1433 """
1434 for i, d in enumerate(list_dict):
1435 if key in d.keys():
1436 return i
1437
1438 def plugin_expect_type(self, type, data):
1439 r"""
1440 Plugin expect directive type check.
1441 """
Patrick Williams20f38712022-12-08 06:18:26 -06001442 if type == "int":
George Keishingde79a9b2021-08-12 16:14:43 -05001443 return isinstance(data, int)
Patrick Williams20f38712022-12-08 06:18:26 -06001444 elif type == "float":
George Keishingde79a9b2021-08-12 16:14:43 -05001445 return isinstance(data, float)
Patrick Williams20f38712022-12-08 06:18:26 -06001446 elif type == "str":
George Keishingde79a9b2021-08-12 16:14:43 -05001447 return isinstance(data, str)
Patrick Williams20f38712022-12-08 06:18:26 -06001448 elif type == "list":
George Keishingde79a9b2021-08-12 16:14:43 -05001449 return isinstance(data, list)
Patrick Williams20f38712022-12-08 06:18:26 -06001450 elif type == "dict":
George Keishingde79a9b2021-08-12 16:14:43 -05001451 return isinstance(data, dict)
Patrick Williams20f38712022-12-08 06:18:26 -06001452 elif type == "tuple":
George Keishingde79a9b2021-08-12 16:14:43 -05001453 return isinstance(data, tuple)
1454 else:
1455 self.logger.info("\tInvalid data type requested: %s" % type)
Patrick Williams20f38712022-12-08 06:18:26 -06001456 return "INVALID"