blob: a484d30cedb97b0dd09b5a5da3caa764dc40c483 [file] [log] [blame]
Peter D Phan72ce6b82021-06-03 06:18:26 -05001#!/usr/bin/env python
2
3r"""
4See class prolog below for details.
5"""
6
7import os
George Keishing0813e712021-07-26 08:29:20 -05008import re
Peter D Phan72ce6b82021-06-03 06:18:26 -05009import sys
10import yaml
George Keishing4885b2f2021-07-21 15:22:45 -050011import json
Peter D Phan72ce6b82021-06-03 06:18:26 -050012import time
Peter D Phane86d9a52021-07-15 10:42:25 -050013import logging
Peter D Phan72ce6b82021-06-03 06:18:26 -050014import platform
15from errno import EACCES, EPERM
Peter D Phan0c669772021-06-24 13:52:42 -050016import subprocess
Peter D Phan72ce6b82021-06-03 06:18:26 -050017from ssh_utility import SSHRemoteclient
Peter D Phan5963d632021-07-12 09:58:55 -050018from telnet_utility import TelnetRemoteclient
Peter D Phan72ce6b82021-06-03 06:18:26 -050019
George Keishingb97a9042021-07-29 07:41:20 -050020r"""
21User define plugins python functions.
22
23It will imports files from directory plugins
24
25plugins
26├── file1.py
27└── file2.py
28
29Example how to define in YAML:
30 - plugin:
31 - plugin_name: plugin.foo_func.foo_func_yaml
32 - plugin_args:
33 - arg1
34 - arg2
35"""
George Keishingcfbc9052021-08-10 07:41:11 -050036abs_path = os.path.abspath(os.path.dirname(sys.argv[0]))
37plugin_dir = abs_path + '/plugins'
George Keishingb97a9042021-07-29 07:41:20 -050038try:
39 for module in os.listdir(plugin_dir):
40 if module == '__init__.py' or module[-3:] != '.py':
41 continue
42 plugin_module = "plugins." + module[:-3]
43 # To access the module plugin.<module name>.<function>
44 # Example: plugin.foo_func.foo_func_yaml()
45 try:
46 plugin = __import__(plugin_module, globals(), locals(), [], 0)
47 except Exception as e:
48 print("PLUGIN: Module import failed: %s" % module)
49 pass
50except FileNotFoundError as e:
51 print("PLUGIN: %s" % e)
52 pass
53
54r"""
55This is for plugin functions returning data or responses to the caller
56in YAML plugin setup.
57
58Example:
59
60 - plugin:
61 - plugin_name: version = plugin.ssh_execution.ssh_execute_cmd
62 - plugin_args:
63 - ${hostname}
64 - ${username}
65 - ${password}
66 - "cat /etc/os-release | grep VERSION_ID | awk -F'=' '{print $2}'"
67 - plugin:
68 - plugin_name: plugin.print_vars.print_vars
69 - plugin_args:
70 - version
71
72where first plugin "version" var is used by another plugin in the YAML
73block or plugin
74
75"""
76global global_log_store_path
77global global_plugin_dict
78global global_plugin_list
George Keishing9348b402021-08-13 12:22:35 -050079
George Keishing0581cb02021-08-05 15:08:58 -050080# Hold the plugin return values in dict and plugin return vars in list.
George Keishing9348b402021-08-13 12:22:35 -050081# Dict is to reference and update vars processing in parser where as
82# list is for current vars from the plugin block which needs processing.
George Keishingb97a9042021-07-29 07:41:20 -050083global_plugin_dict = {}
84global_plugin_list = []
George Keishing9348b402021-08-13 12:22:35 -050085
George Keishing0581cb02021-08-05 15:08:58 -050086# Hold the plugin return named declared if function returned values are list,dict.
87# Refer this name list to look up the plugin dict for eval() args function
George Keishing9348b402021-08-13 12:22:35 -050088# Example ['version']
George Keishing0581cb02021-08-05 15:08:58 -050089global_plugin_type_list = []
George Keishing9348b402021-08-13 12:22:35 -050090
91# Path where logs are to be stored or written.
George Keishingb97a9042021-07-29 07:41:20 -050092global_log_store_path = ''
93
George Keishing1e7b0182021-08-06 14:05:54 -050094# Plugin error state defaults.
95plugin_error_dict = {
96 'exit_on_error': False,
97 'continue_on_error': False,
98}
99
Peter D Phan72ce6b82021-06-03 06:18:26 -0500100
101class FFDCCollector:
102
103 r"""
George Keishing1e7b0182021-08-06 14:05:54 -0500104 Execute commands from configuration file to collect log files.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500105 Fetch and store generated files at the specified location.
106
107 """
108
Peter D Phan0c669772021-06-24 13:52:42 -0500109 def __init__(self,
110 hostname,
111 username,
112 password,
113 ffdc_config,
114 location,
115 remote_type,
Peter D Phane86d9a52021-07-15 10:42:25 -0500116 remote_protocol,
George Keishing4885b2f2021-07-21 15:22:45 -0500117 env_vars,
George Keishing8e94f8c2021-07-23 15:06:32 -0500118 econfig,
Peter D Phane86d9a52021-07-15 10:42:25 -0500119 log_level):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500120 r"""
121 Description of argument(s):
122
George Keishing8e94f8c2021-07-23 15:06:32 -0500123 hostname name/ip of the targeted (remote) system
124 username user on the targeted system with access to FFDC files
125 password password for user on targeted system
126 ffdc_config configuration file listing commands and files for FFDC
127 location where to store collected FFDC
128 remote_type os type of the remote host
129 remote_protocol Protocol to use to collect data
130 env_vars User define CLI env vars '{"key : "value"}'
131 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -0500132
133 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500134
135 self.hostname = hostname
136 self.username = username
137 self.password = password
138 self.ffdc_config = ffdc_config
139 self.location = location + "/" + remote_type.upper()
140 self.ssh_remoteclient = None
141 self.telnet_remoteclient = None
142 self.ffdc_dir_path = ""
143 self.ffdc_prefix = ""
144 self.target_type = remote_type.upper()
145 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -0500146 self.env_vars = env_vars
147 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -0500148 self.start_time = 0
149 self.elapsed_time = ''
150 self.logger = None
151
152 # Set prefix values for scp files and directory.
153 # Since the time stamp is at second granularity, these values are set here
154 # to be sure that all files for this run will have same timestamps
155 # and they will be saved in the same directory.
156 # self.location == local system for now
157 self.set_ffdc_defaults()
158
159 # Logger for this run. Need to be after set_ffdc_defaults()
160 self.script_logging(getattr(logging, log_level.upper()))
161
162 # Verify top level directory exists for storage
163 self.validate_local_store(self.location)
164
Peter D Phan72ce6b82021-06-03 06:18:26 -0500165 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -0500166 # Load default or user define YAML configuration file.
167 with open(self.ffdc_config, 'r') as file:
168 self.ffdc_actions = yaml.load(file, Loader=yaml.FullLoader)
169
170 if self.target_type not in self.ffdc_actions.keys():
171 self.logger.error(
172 "\n\tERROR: %s is not listed in %s.\n\n" % (self.target_type, self.ffdc_config))
173 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500174 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500175 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500176
George Keishing4885b2f2021-07-21 15:22:45 -0500177 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500178 self.logger.info("\n\tENV: User define input YAML variables")
179 self.env_dict = {}
George Keishinge1686752021-07-27 12:55:28 -0500180 self. load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500181
Peter D Phan72ce6b82021-06-03 06:18:26 -0500182 def verify_script_env(self):
183
184 # Import to log version
185 import click
186 import paramiko
187
188 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500189
George Keishing506b0582021-07-27 09:31:22 -0500190 redfishtool_version = self.run_tool_cmd('redfishtool -V').split(' ')[2].strip('\n')
191 ipmitool_version = self.run_tool_cmd('ipmitool -V').split(' ')[2]
Peter D Phan0c669772021-06-24 13:52:42 -0500192
Peter D Phane86d9a52021-07-15 10:42:25 -0500193 self.logger.info("\n\t---- Script host environment ----")
194 self.logger.info("\t{:<10} {:<10}".format('Script hostname', os.uname()[1]))
195 self.logger.info("\t{:<10} {:<10}".format('Script host os', platform.platform()))
196 self.logger.info("\t{:<10} {:>10}".format('Python', platform.python_version()))
197 self.logger.info("\t{:<10} {:>10}".format('PyYAML', yaml.__version__))
198 self.logger.info("\t{:<10} {:>10}".format('click', click.__version__))
199 self.logger.info("\t{:<10} {:>10}".format('paramiko', paramiko.__version__))
200 self.logger.info("\t{:<10} {:>9}".format('redfishtool', redfishtool_version))
201 self.logger.info("\t{:<10} {:>12}".format('ipmitool', ipmitool_version))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500202
Peter D Phan8462faf2021-06-16 12:24:15 -0500203 if eval(yaml.__version__.replace('.', ',')) < (5, 4, 1):
Peter D Phane86d9a52021-07-15 10:42:25 -0500204 self.logger.error("\n\tERROR: Python or python packages do not meet minimum version requirement.")
205 self.logger.error("\tERROR: PyYAML version 5.4.1 or higher is needed.\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500206 run_env_ok = False
207
Peter D Phane86d9a52021-07-15 10:42:25 -0500208 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500209 return run_env_ok
210
Peter D Phane86d9a52021-07-15 10:42:25 -0500211 def script_logging(self,
212 log_level_attr):
213 r"""
214 Create logger
215
216 """
217 self.logger = logging.getLogger()
218 self.logger.setLevel(log_level_attr)
219 log_file_handler = logging.FileHandler(self.ffdc_dir_path + "collector.log")
220
221 stdout_handler = logging.StreamHandler(sys.stdout)
222 self.logger.addHandler(log_file_handler)
223 self.logger.addHandler(stdout_handler)
224
225 # Turn off paramiko INFO logging
226 logging.getLogger("paramiko").setLevel(logging.WARNING)
227
Peter D Phan72ce6b82021-06-03 06:18:26 -0500228 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500229 r"""
230 Check if target system is ping-able.
231
232 """
George Keishing0662e942021-07-13 05:12:20 -0500233 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500234 if response == 0:
Peter D Phane86d9a52021-07-15 10:42:25 -0500235 self.logger.info("\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500236 return True
237 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500238 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500239 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500240 sys.exit(-1)
241
Peter D Phan72ce6b82021-06-03 06:18:26 -0500242 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500243 r"""
244 Initiate FFDC Collection depending on requested protocol.
245
246 """
247
Peter D Phane86d9a52021-07-15 10:42:25 -0500248 self.logger.info("\n\t---- Start communicating with %s ----" % self.hostname)
Peter D Phan7610bc42021-07-06 06:31:05 -0500249 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500250
George Keishingf5a57502021-07-22 16:43:47 -0500251 # Find the list of target and protocol supported.
252 check_protocol_list = []
253 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500254
George Keishingf5a57502021-07-22 16:43:47 -0500255 for target_type in config_dict.keys():
256 if self.target_type != target_type:
257 continue
George Keishingeafba182021-06-29 13:44:58 -0500258
George Keishingf5a57502021-07-22 16:43:47 -0500259 for k, v in config_dict[target_type].items():
260 if config_dict[target_type][k]['PROTOCOL'][0] not in check_protocol_list:
261 check_protocol_list.append(config_dict[target_type][k]['PROTOCOL'][0])
Peter D Phanbff617a2021-07-22 08:41:35 -0500262
George Keishingf5a57502021-07-22 16:43:47 -0500263 self.logger.info("\n\t %s protocol type: %s" % (self.target_type, check_protocol_list))
Peter D Phanbff617a2021-07-22 08:41:35 -0500264
George Keishingf5a57502021-07-22 16:43:47 -0500265 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500266
George Keishingf5a57502021-07-22 16:43:47 -0500267 if verified_working_protocol:
Peter D Phane86d9a52021-07-15 10:42:25 -0500268 self.logger.info("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500269
George Keishingf5a57502021-07-22 16:43:47 -0500270 # Verify top level directory exists for storage
271 self.validate_local_store(self.location)
272
273 if ((self.remote_protocol not in verified_working_protocol) and (self.remote_protocol != 'ALL')):
274 self.logger.info("\n\tWorking protocol list: %s" % verified_working_protocol)
275 self.logger.error(
276 '\tERROR: Requested protocol %s is not in working protocol list.\n'
277 % self.remote_protocol)
278 sys.exit(-1)
279 else:
280 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500281
282 def ssh_to_target_system(self):
283 r"""
284 Open a ssh connection to targeted system.
285
286 """
287
Peter D Phan5963d632021-07-12 09:58:55 -0500288 self.ssh_remoteclient = SSHRemoteclient(self.hostname,
289 self.username,
290 self.password)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500291
Peter D Phan5963d632021-07-12 09:58:55 -0500292 if self.ssh_remoteclient.ssh_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500293 self.logger.info("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500294
Peter D Phan5963d632021-07-12 09:58:55 -0500295 # Check scp connection.
296 # If scp connection fails,
297 # continue with FFDC generation but skip scp files to local host.
298 self.ssh_remoteclient.scp_connection()
299 return True
300 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500301 self.logger.info("\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500302 return False
303
304 def telnet_to_target_system(self):
305 r"""
306 Open a telnet connection to targeted system.
307 """
308 self.telnet_remoteclient = TelnetRemoteclient(self.hostname,
309 self.username,
310 self.password)
311 if self.telnet_remoteclient.tn_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500312 self.logger.info("\n\t[Check] %s Telnet connection established.\t [OK]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500313 return True
314 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500315 self.logger.info("\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500316 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500317
George Keishing772c9772021-06-16 23:23:42 -0500318 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500319 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500320 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500321
Peter D Phan04aca3b2021-06-21 10:37:18 -0500322 Description of argument(s):
323 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500324 """
325
Peter D Phane86d9a52021-07-15 10:42:25 -0500326 self.logger.info("\n\t---- Executing commands on " + self.hostname + " ----")
327 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500328
George Keishingf5a57502021-07-22 16:43:47 -0500329 config_dict = self.ffdc_actions
330 for target_type in config_dict.keys():
331 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500332 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500333
Peter D Phane86d9a52021-07-15 10:42:25 -0500334 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
George Keishingb97a9042021-07-29 07:41:20 -0500335 global_plugin_dict['global_log_store_path'] = self.ffdc_dir_path
George Keishingf5a57502021-07-22 16:43:47 -0500336 self.logger.info("\tSystem Type: %s" % target_type)
337 for k, v in config_dict[target_type].items():
Peter D Phan72ce6b82021-06-03 06:18:26 -0500338
George Keishingf5a57502021-07-22 16:43:47 -0500339 if self.remote_protocol not in working_protocol_list \
George Keishing6ea92b02021-07-01 11:20:50 -0500340 and self.remote_protocol != 'ALL':
341 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500342
George Keishingf5a57502021-07-22 16:43:47 -0500343 protocol = config_dict[target_type][k]['PROTOCOL'][0]
344
345 if protocol not in working_protocol_list:
346 continue
347
George Keishingb7607612021-07-27 13:31:23 -0500348 if protocol in working_protocol_list:
349 if protocol == 'SSH' or protocol == 'SCP':
George Keishing12fd0652021-07-27 13:57:11 -0500350 self.protocol_ssh(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500351 elif protocol == 'TELNET':
George Keishingf5a57502021-07-22 16:43:47 -0500352 self.protocol_telnet(target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500353 elif protocol == 'REDFISH' or protocol == 'IPMI' or protocol == 'SHELL':
George Keishing506b0582021-07-27 09:31:22 -0500354 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500355 else:
356 self.logger.error("\n\tERROR: %s is not available for %s." % (protocol, self.hostname))
George Keishingeafba182021-06-29 13:44:58 -0500357
Peter D Phan04aca3b2021-06-21 10:37:18 -0500358 # Close network connection after collecting all files
Peter D Phan7610bc42021-07-06 06:31:05 -0500359 self.elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - self.start_time))
Peter D Phanbff617a2021-07-22 08:41:35 -0500360 if self.ssh_remoteclient:
361 self.ssh_remoteclient.ssh_remoteclient_disconnect()
362 if self.telnet_remoteclient:
363 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500364
Peter D Phan0c669772021-06-24 13:52:42 -0500365 def protocol_ssh(self,
George Keishing12fd0652021-07-27 13:57:11 -0500366 protocol,
George Keishingf5a57502021-07-22 16:43:47 -0500367 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500368 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500369 r"""
370 Perform actions using SSH and SCP protocols.
371
372 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500373 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500374 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500375 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500376 """
377
George Keishing12fd0652021-07-27 13:57:11 -0500378 if protocol == 'SCP':
George Keishingf5a57502021-07-22 16:43:47 -0500379 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500380 else:
George Keishingf5a57502021-07-22 16:43:47 -0500381 self.collect_and_copy_ffdc(self.ffdc_actions[target_type][sub_type])
Peter D Phan0c669772021-06-24 13:52:42 -0500382
Peter D Phan5963d632021-07-12 09:58:55 -0500383 def protocol_telnet(self,
George Keishingf5a57502021-07-22 16:43:47 -0500384 target_type,
Peter D Phan5963d632021-07-12 09:58:55 -0500385 sub_type):
386 r"""
387 Perform actions using telnet protocol.
388 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500389 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500390 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500391 self.logger.info("\n\t[Run] Executing commands on %s using %s" % (self.hostname, 'TELNET'))
Peter D Phan5963d632021-07-12 09:58:55 -0500392 telnet_files_saved = []
393 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500394 list_of_commands = self.ffdc_actions[target_type][sub_type]['COMMANDS']
Peter D Phan5963d632021-07-12 09:58:55 -0500395 for index, each_cmd in enumerate(list_of_commands, start=0):
396 command_txt, command_timeout = self.unpack_command(each_cmd)
397 result = self.telnet_remoteclient.execute_command(command_txt, command_timeout)
398 if result:
399 try:
George Keishingf5a57502021-07-22 16:43:47 -0500400 targ_file = self.ffdc_actions[target_type][sub_type]['FILES'][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500401 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500402 targ_file = command_txt
403 self.logger.warning(
404 "\n\t[WARN] Missing filename to store data from telnet %s." % each_cmd)
405 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan5963d632021-07-12 09:58:55 -0500406 targ_file_with_path = (self.ffdc_dir_path
407 + self.ffdc_prefix
408 + targ_file)
409 # Creates a new file
Peter D Phanb76e1752021-08-03 12:50:05 -0500410 with open(targ_file_with_path, 'w') as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500411 fp.write(result)
412 fp.close
413 telnet_files_saved.append(targ_file)
414 progress_counter += 1
415 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500416 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500417 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500418 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500419
George Keishing506b0582021-07-27 09:31:22 -0500420 def protocol_execute(self,
421 protocol,
George Keishingf5a57502021-07-22 16:43:47 -0500422 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500423 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500424 r"""
George Keishing506b0582021-07-27 09:31:22 -0500425 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500426
427 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500428 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500429 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500430 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500431 """
432
George Keishing506b0582021-07-27 09:31:22 -0500433 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, protocol))
434 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500435 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500436 list_of_cmd = self.get_command_list(self.ffdc_actions[target_type][sub_type])
George Keishingeafba182021-06-29 13:44:58 -0500437 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500438 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500439 if isinstance(each_cmd, dict):
440 if 'plugin' in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500441 # If the error is set and plugin explicitly
442 # requested to skip execution on error..
443 if plugin_error_dict['exit_on_error'] and \
444 self.plugin_error_check(each_cmd['plugin']):
445 self.logger.info("\n\t[PLUGIN-ERROR] exit_on_error: %s" %
446 plugin_error_dict['exit_on_error'])
447 self.logger.info("\t[PLUGIN-SKIP] %s" %
448 each_cmd['plugin'][0])
449 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500450 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500451 # call the plugin
452 self.logger.info("\n\t[PLUGIN-START]")
George Keishingcaa97e62021-08-03 14:00:09 -0500453 result = self.execute_plugin_block(each_cmd['plugin'])
George Keishingb97a9042021-07-29 07:41:20 -0500454 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500455 else:
George Keishing2b83e042021-08-03 12:56:11 -0500456 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500457
George Keishingcaa97e62021-08-03 14:00:09 -0500458 if not plugin_call:
459 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500460 if result:
461 try:
George Keishingcaa97e62021-08-03 14:00:09 -0500462 file_name = self.get_file_list(self.ffdc_actions[target_type][sub_type])[index]
George Keishingb97a9042021-07-29 07:41:20 -0500463 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500464 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500465 continue
George Keishing0581cb02021-08-05 15:08:58 -0500466 targ_file = self.yaml_env_and_plugin_vars_populate(file_name)
George Keishingeafba182021-06-29 13:44:58 -0500467 except IndexError:
George Keishing6ea92b02021-07-01 11:20:50 -0500468 targ_file = each_cmd.split('/')[-1]
George Keishing506b0582021-07-27 09:31:22 -0500469 self.logger.warning(
470 "\n\t[WARN] Missing filename to store data from %s." % each_cmd)
Peter D Phane86d9a52021-07-15 10:42:25 -0500471 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500472
473 targ_file_with_path = (self.ffdc_dir_path
474 + self.ffdc_prefix
475 + targ_file)
476
477 # Creates a new file
478 with open(targ_file_with_path, 'w') as fp:
George Keishing91308ea2021-08-10 14:43:15 -0500479 if isinstance(result, dict):
480 fp.write(json.dumps(result))
481 else:
482 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500483 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500484 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500485
486 progress_counter += 1
487 self.print_progress(progress_counter)
488
Peter D Phane86d9a52021-07-15 10:42:25 -0500489 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500490
George Keishing506b0582021-07-27 09:31:22 -0500491 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500492 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500493
Peter D Phan04aca3b2021-06-21 10:37:18 -0500494 def collect_and_copy_ffdc(self,
George Keishingf5a57502021-07-22 16:43:47 -0500495 ffdc_actions_for_target_type,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500496 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500497 r"""
498 Send commands in ffdc_config file to targeted system.
499
500 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500501 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500502 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500503 """
504
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500505 # Executing commands, if any
George Keishingf5a57502021-07-22 16:43:47 -0500506 self.ssh_execute_ffdc_commands(ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500507 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500508
Peter D Phan3beb02e2021-07-06 13:25:17 -0500509 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500510 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500511 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500512
Peter D Phan04aca3b2021-06-21 10:37:18 -0500513 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500514 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500515 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500516 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500517 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500518
Peter D Phanbabf2962021-07-07 11:24:40 -0500519 def get_command_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500520 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500521 r"""
522 Fetch list of commands from configuration file
523
524 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500525 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500526 """
527 try:
George Keishingf5a57502021-07-22 16:43:47 -0500528 list_of_commands = ffdc_actions_for_target_type['COMMANDS']
Peter D Phanbabf2962021-07-07 11:24:40 -0500529 except KeyError:
530 list_of_commands = []
531 return list_of_commands
532
533 def get_file_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500534 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500535 r"""
536 Fetch list of commands from configuration file
537
538 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500539 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500540 """
541 try:
George Keishingf5a57502021-07-22 16:43:47 -0500542 list_of_files = ffdc_actions_for_target_type['FILES']
Peter D Phanbabf2962021-07-07 11:24:40 -0500543 except KeyError:
544 list_of_files = []
545 return list_of_files
546
Peter D Phan5963d632021-07-12 09:58:55 -0500547 def unpack_command(self,
548 command):
549 r"""
550 Unpack command from config file
551
552 Description of argument(s):
553 command Command from config file.
554 """
555 if isinstance(command, dict):
556 command_txt = next(iter(command))
557 command_timeout = next(iter(command.values()))
558 elif isinstance(command, str):
559 command_txt = command
560 # Default command timeout 60 seconds
561 command_timeout = 60
562
563 return command_txt, command_timeout
564
Peter D Phan3beb02e2021-07-06 13:25:17 -0500565 def ssh_execute_ffdc_commands(self,
George Keishingf5a57502021-07-22 16:43:47 -0500566 ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500567 form_filename=False):
568 r"""
569 Send commands in ffdc_config file to targeted system.
570
571 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500572 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500573 form_filename if true, pre-pend self.target_type to filename
574 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500575 self.logger.info("\n\t[Run] Executing commands on %s using %s"
George Keishingf5a57502021-07-22 16:43:47 -0500576 % (self.hostname, ffdc_actions_for_target_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500577
George Keishingf5a57502021-07-22 16:43:47 -0500578 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500579 # If command list is empty, returns
580 if not list_of_commands:
581 return
582
583 progress_counter = 0
584 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500585 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500586
587 if form_filename:
588 command_txt = str(command_txt % self.target_type)
589
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500590 cmd_exit_code, err, response = \
591 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
592
593 if cmd_exit_code:
594 self.logger.warning(
595 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
596 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500597
Peter D Phan3beb02e2021-07-06 13:25:17 -0500598 progress_counter += 1
599 self.print_progress(progress_counter)
600
Peter D Phane86d9a52021-07-15 10:42:25 -0500601 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500602
Peter D Phan56429a62021-06-23 08:38:29 -0500603 def group_copy(self,
George Keishingf5a57502021-07-22 16:43:47 -0500604 ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500605 r"""
606 scp group of files (wild card) from remote host.
607
608 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500609 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500610 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500611
Peter D Phan5963d632021-07-12 09:58:55 -0500612 if self.ssh_remoteclient.scpclient:
George Keishing12fd0652021-07-27 13:57:11 -0500613 self.logger.info("\n\tCopying files from remote system %s via SCP.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500614
George Keishingf5a57502021-07-22 16:43:47 -0500615 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phanbabf2962021-07-07 11:24:40 -0500616 # If command list is empty, returns
617 if not list_of_commands:
618 return
Peter D Phan56429a62021-06-23 08:38:29 -0500619
Peter D Phanbabf2962021-07-07 11:24:40 -0500620 for command in list_of_commands:
621 try:
George Keishingb4540e72021-08-02 13:48:46 -0500622 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500623 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500624 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500625 continue
626
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500627 cmd_exit_code, err, response = \
628 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500629
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500630 # If file does not exist, code take no action.
631 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500632 if response:
George Keishinga56e87b2021-08-06 00:24:19 -0500633 scp_result = \
634 self.ssh_remoteclient.scp_file_from_remote(response.split('\n'),
635 self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500636 if scp_result:
George Keishinga56e87b2021-08-06 00:24:19 -0500637 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + command)
Peter D Phan56429a62021-06-23 08:38:29 -0500638 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500639 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500640
641 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500642 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500643
Peter D Phan72ce6b82021-06-03 06:18:26 -0500644 def scp_ffdc(self,
645 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500646 targ_file_prefix,
647 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500648 file_list=None,
649 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500650 r"""
651 SCP all files in file_dict to the indicated directory on the local system.
652
653 Description of argument(s):
654 targ_dir_path The path of the directory to receive the files.
655 targ_file_prefix Prefix which will be pre-pended to each
656 target file's name.
657 file_dict A dictionary of files to scp from targeted system to this system
658
659 """
660
Peter D Phan72ce6b82021-06-03 06:18:26 -0500661 progress_counter = 0
662 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500663 if form_filename:
664 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500665 source_file_path = filename
666 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
667
Peter D Phanbabf2962021-07-07 11:24:40 -0500668 # If source file name contains wild card, copy filename as is.
669 if '*' in source_file_path:
Peter D Phan5963d632021-07-12 09:58:55 -0500670 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500671 else:
Peter D Phan5963d632021-07-12 09:58:55 -0500672 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500673
674 if not quiet:
675 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500676 self.logger.info(
677 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500678 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500679 self.logger.info(
680 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500681 else:
682 progress_counter += 1
683 self.print_progress(progress_counter)
684
Peter D Phan72ce6b82021-06-03 06:18:26 -0500685 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500686 r"""
687 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
688 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
689 Individual ffdc file will have timestr_filename.
690
691 Description of class variables:
692 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
693
694 self.ffdc_prefix The prefix to be given to each ffdc file name.
695
696 """
697
698 timestr = time.strftime("%Y%m%d-%H%M%S")
699 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
700 self.ffdc_prefix = timestr + "_"
701 self.validate_local_store(self.ffdc_dir_path)
702
703 def validate_local_store(self, dir_path):
704 r"""
705 Ensure path exists to store FFDC files locally.
706
707 Description of variable:
708 dir_path The dir path where collected ffdc data files will be stored.
709
710 """
711
712 if not os.path.exists(dir_path):
713 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500714 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500715 except (IOError, OSError) as e:
716 # PermissionError
717 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500718 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500719 '\tERROR: os.makedirs %s failed with PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500720 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500721 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500722 '\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500723 sys.exit(-1)
724
725 def print_progress(self, progress):
726 r"""
727 Print activity progress +
728
729 Description of variable:
730 progress Progress counter.
731
732 """
733
734 sys.stdout.write("\r\t" + "+" * progress)
735 sys.stdout.flush()
736 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500737
738 def verify_redfish(self):
739 r"""
740 Verify remote host has redfish service active
741
742 """
George Keishing506b0582021-07-27 09:31:22 -0500743 redfish_parm = 'redfishtool -r ' \
Peter D Phan0c669772021-06-24 13:52:42 -0500744 + self.hostname + ' -S Always raw GET /redfish/v1/'
George Keishing506b0582021-07-27 09:31:22 -0500745 return(self.run_tool_cmd(redfish_parm, True))
Peter D Phan0c669772021-06-24 13:52:42 -0500746
George Keishingeafba182021-06-29 13:44:58 -0500747 def verify_ipmi(self):
748 r"""
749 Verify remote host has IPMI LAN service active
750
751 """
George Keishing484f8242021-07-27 01:42:02 -0500752 if self.target_type == 'OPENBMC':
753 ipmi_parm = 'ipmitool -I lanplus -C 17 -U ' + self.username + ' -P ' \
754 + self.password + ' -H ' + self.hostname + ' power status'
755 else:
756 ipmi_parm = 'ipmitool -I lanplus -P ' \
757 + self.password + ' -H ' + self.hostname + ' power status'
758
George Keishing506b0582021-07-27 09:31:22 -0500759 return(self.run_tool_cmd(ipmi_parm, True))
George Keishingeafba182021-06-29 13:44:58 -0500760
George Keishing506b0582021-07-27 09:31:22 -0500761 def run_tool_cmd(self,
George Keishingeafba182021-06-29 13:44:58 -0500762 parms_string,
763 quiet=False):
764 r"""
George Keishing506b0582021-07-27 09:31:22 -0500765 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500766
767 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500768 parms_string tool command options.
769 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500770 """
771
George Keishing484f8242021-07-27 01:42:02 -0500772 result = subprocess.run([parms_string],
George Keishingeafba182021-06-29 13:44:58 -0500773 stdout=subprocess.PIPE,
774 stderr=subprocess.PIPE,
775 shell=True,
776 universal_newlines=True)
777
778 if result.stderr and not quiet:
George Keishing484f8242021-07-27 01:42:02 -0500779 self.logger.error('\n\t\tERROR with %s ' % parms_string)
Peter D Phane86d9a52021-07-15 10:42:25 -0500780 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500781
782 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500783
George Keishingf5a57502021-07-22 16:43:47 -0500784 def verify_protocol(self, protocol_list):
785 r"""
786 Perform protocol working check.
787
788 Description of argument(s):
789 protocol_list List of protocol.
790 """
791
792 tmp_list = []
793 if self.target_is_pingable():
794 tmp_list.append("SHELL")
795
796 for protocol in protocol_list:
797 if self.remote_protocol != 'ALL':
798 if self.remote_protocol != protocol:
799 continue
800
801 # Only check SSH/SCP once for both protocols
802 if protocol == 'SSH' or protocol == 'SCP' and protocol not in tmp_list:
803 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -0500804 # Add only what user asked.
805 if self.remote_protocol != 'ALL':
806 tmp_list.append(self.remote_protocol)
807 else:
808 tmp_list.append('SSH')
809 tmp_list.append('SCP')
George Keishingf5a57502021-07-22 16:43:47 -0500810
811 if protocol == 'TELNET':
812 if self.telnet_to_target_system():
813 tmp_list.append(protocol)
814
815 if protocol == 'REDFISH':
816 if self.verify_redfish():
817 tmp_list.append(protocol)
818 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
819 else:
820 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
821
822 if protocol == 'IPMI':
823 if self.verify_ipmi():
824 tmp_list.append(protocol)
825 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
826 else:
827 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
828
829 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -0500830
831 def load_env(self):
832 r"""
833 Perform protocol working check.
834
835 """
836 # This is for the env vars a user can use in YAML to load it at runtime.
837 # Example YAML:
838 # -COMMANDS:
839 # - my_command ${hostname} ${username} ${password}
840 os.environ['hostname'] = self.hostname
841 os.environ['username'] = self.username
842 os.environ['password'] = self.password
843
844 # Append default Env.
845 self.env_dict['hostname'] = self.hostname
846 self.env_dict['username'] = self.username
847 self.env_dict['password'] = self.password
848
849 try:
850 tmp_env_dict = {}
851 if self.env_vars:
852 tmp_env_dict = json.loads(self.env_vars)
853 # Export ENV vars default.
854 for key, value in tmp_env_dict.items():
855 os.environ[key] = value
856 self.env_dict[key] = str(value)
857
858 if self.econfig:
859 with open(self.econfig, 'r') as file:
860 tmp_env_dict = yaml.load(file, Loader=yaml.FullLoader)
861 # Export ENV vars.
862 for key, value in tmp_env_dict['env_params'].items():
863 os.environ[key] = str(value)
864 self.env_dict[key] = str(value)
865 except json.decoder.JSONDecodeError as e:
866 self.logger.error("\n\tERROR: %s " % e)
867 sys.exit(-1)
868
869 # This to mask the password from displaying on the console.
870 mask_dict = self.env_dict.copy()
871 for k, v in mask_dict.items():
872 if k.lower().find("password") != -1:
873 hidden_text = []
874 hidden_text.append(v)
875 password_regex = '(' +\
876 '|'.join([re.escape(x) for x in hidden_text]) + ')'
877 mask_dict[k] = re.sub(password_regex, "********", v)
878
879 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -0500880
881 def execute_python_eval(self, eval_string):
882 r"""
George Keishing9348b402021-08-13 12:22:35 -0500883 Execute qualified python function string using eval.
George Keishingb97a9042021-07-29 07:41:20 -0500884
885 Description of argument(s):
886 eval_string Execute the python object.
887
888 Example:
889 eval(plugin.foo_func.foo_func(10))
890 """
891 try:
George Keishingdda48ce2021-08-12 07:02:27 -0500892 self.logger.info("\tExecuting plugin func()")
893 self.logger.debug("\tCall func: %s" % eval_string)
George Keishingb97a9042021-07-29 07:41:20 -0500894 result = eval(eval_string)
895 self.logger.info("\treturn: %s" % str(result))
896 except (ValueError, SyntaxError, NameError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -0500897 self.logger.error("\tERROR: execute_python_eval: %s" % e)
898 # Set the plugin error state.
899 plugin_error_dict['exit_on_error'] = True
George Keishingb97a9042021-07-29 07:41:20 -0500900 pass
901
902 return result
903
904 def execute_plugin_block(self, plugin_cmd_list):
905 r"""
906 Pack the plugin command to quailifed python string object.
907
908 Description of argument(s):
909 plugin_list_dict Plugin block read from YAML
910 [{'plugin_name': 'plugin.foo_func.my_func'},
911 {'plugin_args': [10]}]
912
913 Example:
914 - plugin:
915 - plugin_name: plugin.foo_func.my_func
916 - plugin_args:
917 - arg1
918 - arg2
919
920 - plugin:
921 - plugin_name: result = plugin.foo_func.my_func
922 - plugin_args:
923 - arg1
924 - arg2
925
926 - plugin:
927 - plugin_name: result1,result2 = plugin.foo_func.my_func
928 - plugin_args:
929 - arg1
930 - arg2
931 """
932 try:
933 plugin_name = plugin_cmd_list[0]['plugin_name']
934 # Equal separator means plugin function returns result.
935 if ' = ' in plugin_name:
936 # Ex. ['result', 'plugin.foo_func.my_func']
937 plugin_name_args = plugin_name.split(' = ')
938 # plugin func return data.
939 for arg in plugin_name_args:
940 if arg == plugin_name_args[-1]:
941 plugin_name = arg
942 else:
943 plugin_resp = arg.split(',')
944 # ['result1','result2']
945 for x in plugin_resp:
946 global_plugin_list.append(x)
947 global_plugin_dict[x] = ""
948
949 # Walk the plugin args ['arg1,'arg2']
950 # If the YAML plugin statement 'plugin_args' is not declared.
951 if any('plugin_args' in d for d in plugin_cmd_list):
George Keishingde79a9b2021-08-12 16:14:43 -0500952 idx = self.key_index_list_dict('plugin_args', plugin_cmd_list)
953 plugin_args = plugin_cmd_list[idx]['plugin_args']
George Keishingb97a9042021-07-29 07:41:20 -0500954 if plugin_args:
955 plugin_args = self.yaml_args_populate(plugin_args)
956 else:
957 plugin_args = []
958 else:
959 plugin_args = self.yaml_args_populate([])
960
961 # Pack the args arg1, arg2, .... argn into
962 # "arg1","arg2","argn" string as params for function.
963 parm_args_str = self.yaml_args_string(plugin_args)
964 if parm_args_str:
965 plugin_func = plugin_name + '(' + parm_args_str + ')'
966 else:
967 plugin_func = plugin_name + '()'
968
969 # Execute plugin function.
970 if global_plugin_dict:
971 resp = self.execute_python_eval(plugin_func)
George Keishing9348b402021-08-13 12:22:35 -0500972 # Update plugin vars dict if there is any.
George Keishingb97a9042021-07-29 07:41:20 -0500973 self.response_args_data(resp)
974 else:
George Keishingcaa97e62021-08-03 14:00:09 -0500975 resp = self.execute_python_eval(plugin_func)
George Keishingb97a9042021-07-29 07:41:20 -0500976 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -0500977 # Set the plugin error state.
978 plugin_error_dict['exit_on_error'] = True
979 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -0500980 pass
981
George Keishingde79a9b2021-08-12 16:14:43 -0500982 # Check if plugin_expects_return (int, string, list,dict etc)
983 if any('plugin_expects_return' in d for d in plugin_cmd_list):
984 idx = self.key_index_list_dict('plugin_expects_return', plugin_cmd_list)
985 plugin_expects = plugin_cmd_list[idx]['plugin_expects_return']
986 if plugin_expects:
987 if resp:
988 if self.plugin_expect_type(plugin_expects, resp) == 'INVALID':
989 self.logger.error("\tWARN: Plugin error check skipped")
990 elif not self.plugin_expect_type(plugin_expects, resp):
991 self.logger.error("\tERROR: Plugin expects return data: %s"
992 % plugin_expects)
993 plugin_error_dict['exit_on_error'] = True
994 elif not resp:
995 self.logger.error("\tERROR: Plugin func failed to return data")
996 plugin_error_dict['exit_on_error'] = True
997
998 return resp
999
George Keishingb97a9042021-07-29 07:41:20 -05001000 def response_args_data(self, plugin_resp):
1001 r"""
George Keishing9348b402021-08-13 12:22:35 -05001002 Parse the plugin function response and update plugin return variable.
George Keishingb97a9042021-07-29 07:41:20 -05001003
1004 plugin_resp Response data from plugin function.
1005 """
1006 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -05001007 resp_data = ""
George Keishing9348b402021-08-13 12:22:35 -05001008
George Keishingb97a9042021-07-29 07:41:20 -05001009 # There is nothing to update the plugin response.
1010 if len(global_plugin_list) == 0 or plugin_resp == 'None':
1011 return
1012
George Keishing5765f792021-08-02 13:08:53 -05001013 if isinstance(plugin_resp, str):
1014 resp_data = plugin_resp.strip('\r\n\t')
1015 resp_list.append(resp_data)
1016 elif isinstance(plugin_resp, bytes):
1017 resp_data = str(plugin_resp, 'UTF-8').strip('\r\n\t')
1018 resp_list.append(resp_data)
1019 elif isinstance(plugin_resp, tuple):
1020 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -05001021 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -05001022 else:
1023 resp_list = list(plugin_resp)
1024 resp_list = [x.strip('\r\n\t') for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -05001025 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -05001026 if len(global_plugin_list) == 1:
1027 resp_list.append([x.strip('\r\n\t') for x in plugin_resp])
1028 else:
1029 resp_list = [x.strip('\r\n\t') for x in plugin_resp]
1030 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1031 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001032
George Keishing9348b402021-08-13 12:22:35 -05001033 # Iterate if there is a list of plugin return vars to update.
George Keishingb97a9042021-07-29 07:41:20 -05001034 for idx, item in enumerate(resp_list, start=0):
George Keishing9348b402021-08-13 12:22:35 -05001035 # Exit loop, done required loop.
George Keishingb97a9042021-07-29 07:41:20 -05001036 if idx >= len(global_plugin_list):
1037 break
1038 # Find the index of the return func in the list and
1039 # update the global func return dictionary.
1040 try:
1041 dict_idx = global_plugin_list[idx]
1042 global_plugin_dict[dict_idx] = item
1043 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001044 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001045 pass
1046
1047 # Done updating plugin dict irrespective of pass or failed,
George Keishing9348b402021-08-13 12:22:35 -05001048 # clear all the list element for next plugin block execute.
George Keishingb97a9042021-07-29 07:41:20 -05001049 global_plugin_list.clear()
1050
1051 def yaml_args_string(self, plugin_args):
1052 r"""
1053 Pack the args into string.
1054
1055 plugin_args arg list ['arg1','arg2,'argn']
1056 """
1057 args_str = ''
1058 for args in plugin_args:
1059 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001060 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001061 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001062 elif args in global_plugin_type_list:
1063 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001064 else:
1065 args_str += '"' + str(args.strip('\r\n\t')) + '"'
1066 # Skip last list element.
1067 if args != plugin_args[-1]:
1068 args_str += ","
1069 return args_str
1070
1071 def yaml_args_populate(self, yaml_arg_list):
1072 r"""
George Keishing9348b402021-08-13 12:22:35 -05001073 Decode env and plugin vars and populate.
George Keishingb97a9042021-07-29 07:41:20 -05001074
1075 Description of argument(s):
1076 yaml_arg_list arg list read from YAML
1077
1078 Example:
1079 - plugin_args:
1080 - arg1
1081 - arg2
1082
1083 yaml_arg_list: [arg2, arg2]
1084 """
1085 # Get the env loaded keys as list ['hostname', 'username', 'password'].
1086 env_vars_list = list(self.env_dict)
1087
1088 if isinstance(yaml_arg_list, list):
1089 tmp_list = []
1090 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001091 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001092 tmp_list.append(arg)
1093 continue
1094 elif isinstance(arg, str):
1095 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1096 tmp_list.append(arg_str)
1097 else:
1098 tmp_list.append(arg)
1099
1100 # return populated list.
1101 return tmp_list
1102
1103 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1104 r"""
George Keishing9348b402021-08-13 12:22:35 -05001105 Update ${MY_VAR} and plugin vars.
George Keishingb97a9042021-07-29 07:41:20 -05001106
1107 Description of argument(s):
George Keishing9348b402021-08-13 12:22:35 -05001108 yaml_arg_str arg string read from YAML.
George Keishingb97a9042021-07-29 07:41:20 -05001109
1110 Example:
1111 - cat ${MY_VAR}
1112 - ls -AX my_plugin_var
1113 """
George Keishing9348b402021-08-13 12:22:35 -05001114 # Parse the string for env vars ${env_vars}.
George Keishingb97a9042021-07-29 07:41:20 -05001115 try:
1116 # Example, list of matching env vars ['username', 'password', 'hostname']
1117 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
1118 var_name_regex = '\\$\\{([^\\}]+)\\}'
1119 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1120 for var in env_var_names_list:
1121 env_var = os.environ[var]
1122 env_replace = '${' + var + '}'
1123 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1124 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001125 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001126 pass
1127
1128 # Parse the string for plugin vars.
1129 try:
1130 # Example, list of plugin vars ['my_username', 'my_data']
1131 plugin_var_name_list = global_plugin_dict.keys()
1132 for var in plugin_var_name_list:
George Keishing9348b402021-08-13 12:22:35 -05001133 # skip env var list already populated above code block list.
George Keishing0581cb02021-08-05 15:08:58 -05001134 if var in env_var_names_list:
1135 continue
George Keishing9348b402021-08-13 12:22:35 -05001136 # If this plugin var exist but empty in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001137 # This is either a YAML plugin statement incorrectly used or
George Keishing9348b402021-08-13 12:22:35 -05001138 # user added a plugin var which is not going to be populated.
George Keishing0581cb02021-08-05 15:08:58 -05001139 if yaml_arg_str in global_plugin_dict:
1140 if isinstance(global_plugin_dict[var], (list, dict)):
1141 # List data type or dict can't be replaced, use directly
1142 # in eval function call.
1143 global_plugin_type_list.append(var)
1144 else:
1145 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
1146 # Just a string like filename or command.
1147 else:
George Keishingb97a9042021-07-29 07:41:20 -05001148 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
1149 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001150 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001151 pass
1152
1153 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001154
1155 def plugin_error_check(self, plugin_dict):
1156 r"""
1157 Plugin error dict processing.
1158
1159 Description of argument(s):
1160 plugin_dict Dictionary of plugin error.
1161 """
1162 if any('plugin_error' in d for d in plugin_dict):
1163 for d in plugin_dict:
1164 if 'plugin_error' in d:
1165 value = d['plugin_error']
1166 # Reference if the error is set or not by plugin.
1167 return plugin_error_dict[value]
George Keishingde79a9b2021-08-12 16:14:43 -05001168
1169 def key_index_list_dict(self, key, list_dict):
1170 r"""
1171 Iterate list of dictionary and return index if the key match is found.
1172
1173 Description of argument(s):
1174 key Valid Key in a dict.
1175 list_dict list of dictionary.
1176 """
1177 for i, d in enumerate(list_dict):
1178 if key in d.keys():
1179 return i
1180
1181 def plugin_expect_type(self, type, data):
1182 r"""
1183 Plugin expect directive type check.
1184 """
1185 if type == 'int':
1186 return isinstance(data, int)
1187 elif type == 'float':
1188 return isinstance(data, float)
1189 elif type == 'str':
1190 return isinstance(data, str)
1191 elif type == 'list':
1192 return isinstance(data, list)
1193 elif type == 'dict':
1194 return isinstance(data, dict)
1195 elif type == 'tuple':
1196 return isinstance(data, tuple)
1197 else:
1198 self.logger.info("\tInvalid data type requested: %s" % type)
1199 return 'INVALID'