blob: 95d4fa79d47b54671aa0fc300410dfb84a035280 [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 Keishing0581cb02021-08-05 15:08:58 -050079# Hold the plugin return values in dict and plugin return vars in list.
George Keishingb97a9042021-07-29 07:41:20 -050080global_plugin_dict = {}
81global_plugin_list = []
George Keishing0581cb02021-08-05 15:08:58 -050082# Hold the plugin return named declared if function returned values are list,dict.
83# Refer this name list to look up the plugin dict for eval() args function
84# Example [ 'version']
85global_plugin_type_list = []
George Keishingb97a9042021-07-29 07:41:20 -050086global_log_store_path = ''
87
George Keishing1e7b0182021-08-06 14:05:54 -050088# Plugin error state defaults.
89plugin_error_dict = {
90 'exit_on_error': False,
91 'continue_on_error': False,
92}
93
Peter D Phan72ce6b82021-06-03 06:18:26 -050094
95class FFDCCollector:
96
97 r"""
George Keishing1e7b0182021-08-06 14:05:54 -050098 Execute commands from configuration file to collect log files.
Peter D Phan72ce6b82021-06-03 06:18:26 -050099 Fetch and store generated files at the specified location.
100
101 """
102
Peter D Phan0c669772021-06-24 13:52:42 -0500103 def __init__(self,
104 hostname,
105 username,
106 password,
107 ffdc_config,
108 location,
109 remote_type,
Peter D Phane86d9a52021-07-15 10:42:25 -0500110 remote_protocol,
George Keishing4885b2f2021-07-21 15:22:45 -0500111 env_vars,
George Keishing8e94f8c2021-07-23 15:06:32 -0500112 econfig,
Peter D Phane86d9a52021-07-15 10:42:25 -0500113 log_level):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500114 r"""
115 Description of argument(s):
116
George Keishing8e94f8c2021-07-23 15:06:32 -0500117 hostname name/ip of the targeted (remote) system
118 username user on the targeted system with access to FFDC files
119 password password for user on targeted system
120 ffdc_config configuration file listing commands and files for FFDC
121 location where to store collected FFDC
122 remote_type os type of the remote host
123 remote_protocol Protocol to use to collect data
124 env_vars User define CLI env vars '{"key : "value"}'
125 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -0500126
127 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500128
129 self.hostname = hostname
130 self.username = username
131 self.password = password
132 self.ffdc_config = ffdc_config
133 self.location = location + "/" + remote_type.upper()
134 self.ssh_remoteclient = None
135 self.telnet_remoteclient = None
136 self.ffdc_dir_path = ""
137 self.ffdc_prefix = ""
138 self.target_type = remote_type.upper()
139 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -0500140 self.env_vars = env_vars
141 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -0500142 self.start_time = 0
143 self.elapsed_time = ''
144 self.logger = None
145
146 # Set prefix values for scp files and directory.
147 # Since the time stamp is at second granularity, these values are set here
148 # to be sure that all files for this run will have same timestamps
149 # and they will be saved in the same directory.
150 # self.location == local system for now
151 self.set_ffdc_defaults()
152
153 # Logger for this run. Need to be after set_ffdc_defaults()
154 self.script_logging(getattr(logging, log_level.upper()))
155
156 # Verify top level directory exists for storage
157 self.validate_local_store(self.location)
158
Peter D Phan72ce6b82021-06-03 06:18:26 -0500159 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -0500160 # Load default or user define YAML configuration file.
161 with open(self.ffdc_config, 'r') as file:
162 self.ffdc_actions = yaml.load(file, Loader=yaml.FullLoader)
163
164 if self.target_type not in self.ffdc_actions.keys():
165 self.logger.error(
166 "\n\tERROR: %s is not listed in %s.\n\n" % (self.target_type, self.ffdc_config))
167 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500168 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500169 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500170
George Keishing4885b2f2021-07-21 15:22:45 -0500171 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500172 self.logger.info("\n\tENV: User define input YAML variables")
173 self.env_dict = {}
George Keishinge1686752021-07-27 12:55:28 -0500174 self. load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500175
Peter D Phan72ce6b82021-06-03 06:18:26 -0500176 def verify_script_env(self):
177
178 # Import to log version
179 import click
180 import paramiko
181
182 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500183
George Keishing506b0582021-07-27 09:31:22 -0500184 redfishtool_version = self.run_tool_cmd('redfishtool -V').split(' ')[2].strip('\n')
185 ipmitool_version = self.run_tool_cmd('ipmitool -V').split(' ')[2]
Peter D Phan0c669772021-06-24 13:52:42 -0500186
Peter D Phane86d9a52021-07-15 10:42:25 -0500187 self.logger.info("\n\t---- Script host environment ----")
188 self.logger.info("\t{:<10} {:<10}".format('Script hostname', os.uname()[1]))
189 self.logger.info("\t{:<10} {:<10}".format('Script host os', platform.platform()))
190 self.logger.info("\t{:<10} {:>10}".format('Python', platform.python_version()))
191 self.logger.info("\t{:<10} {:>10}".format('PyYAML', yaml.__version__))
192 self.logger.info("\t{:<10} {:>10}".format('click', click.__version__))
193 self.logger.info("\t{:<10} {:>10}".format('paramiko', paramiko.__version__))
194 self.logger.info("\t{:<10} {:>9}".format('redfishtool', redfishtool_version))
195 self.logger.info("\t{:<10} {:>12}".format('ipmitool', ipmitool_version))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500196
Peter D Phan8462faf2021-06-16 12:24:15 -0500197 if eval(yaml.__version__.replace('.', ',')) < (5, 4, 1):
Peter D Phane86d9a52021-07-15 10:42:25 -0500198 self.logger.error("\n\tERROR: Python or python packages do not meet minimum version requirement.")
199 self.logger.error("\tERROR: PyYAML version 5.4.1 or higher is needed.\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500200 run_env_ok = False
201
Peter D Phane86d9a52021-07-15 10:42:25 -0500202 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500203 return run_env_ok
204
Peter D Phane86d9a52021-07-15 10:42:25 -0500205 def script_logging(self,
206 log_level_attr):
207 r"""
208 Create logger
209
210 """
211 self.logger = logging.getLogger()
212 self.logger.setLevel(log_level_attr)
213 log_file_handler = logging.FileHandler(self.ffdc_dir_path + "collector.log")
214
215 stdout_handler = logging.StreamHandler(sys.stdout)
216 self.logger.addHandler(log_file_handler)
217 self.logger.addHandler(stdout_handler)
218
219 # Turn off paramiko INFO logging
220 logging.getLogger("paramiko").setLevel(logging.WARNING)
221
Peter D Phan72ce6b82021-06-03 06:18:26 -0500222 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500223 r"""
224 Check if target system is ping-able.
225
226 """
George Keishing0662e942021-07-13 05:12:20 -0500227 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500228 if response == 0:
Peter D Phane86d9a52021-07-15 10:42:25 -0500229 self.logger.info("\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500230 return True
231 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500232 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500233 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500234 sys.exit(-1)
235
Peter D Phan72ce6b82021-06-03 06:18:26 -0500236 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500237 r"""
238 Initiate FFDC Collection depending on requested protocol.
239
240 """
241
Peter D Phane86d9a52021-07-15 10:42:25 -0500242 self.logger.info("\n\t---- Start communicating with %s ----" % self.hostname)
Peter D Phan7610bc42021-07-06 06:31:05 -0500243 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500244
George Keishingf5a57502021-07-22 16:43:47 -0500245 # Find the list of target and protocol supported.
246 check_protocol_list = []
247 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500248
George Keishingf5a57502021-07-22 16:43:47 -0500249 for target_type in config_dict.keys():
250 if self.target_type != target_type:
251 continue
George Keishingeafba182021-06-29 13:44:58 -0500252
George Keishingf5a57502021-07-22 16:43:47 -0500253 for k, v in config_dict[target_type].items():
254 if config_dict[target_type][k]['PROTOCOL'][0] not in check_protocol_list:
255 check_protocol_list.append(config_dict[target_type][k]['PROTOCOL'][0])
Peter D Phanbff617a2021-07-22 08:41:35 -0500256
George Keishingf5a57502021-07-22 16:43:47 -0500257 self.logger.info("\n\t %s protocol type: %s" % (self.target_type, check_protocol_list))
Peter D Phanbff617a2021-07-22 08:41:35 -0500258
George Keishingf5a57502021-07-22 16:43:47 -0500259 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500260
George Keishingf5a57502021-07-22 16:43:47 -0500261 if verified_working_protocol:
Peter D Phane86d9a52021-07-15 10:42:25 -0500262 self.logger.info("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500263
George Keishingf5a57502021-07-22 16:43:47 -0500264 # Verify top level directory exists for storage
265 self.validate_local_store(self.location)
266
267 if ((self.remote_protocol not in verified_working_protocol) and (self.remote_protocol != 'ALL')):
268 self.logger.info("\n\tWorking protocol list: %s" % verified_working_protocol)
269 self.logger.error(
270 '\tERROR: Requested protocol %s is not in working protocol list.\n'
271 % self.remote_protocol)
272 sys.exit(-1)
273 else:
274 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500275
276 def ssh_to_target_system(self):
277 r"""
278 Open a ssh connection to targeted system.
279
280 """
281
Peter D Phan5963d632021-07-12 09:58:55 -0500282 self.ssh_remoteclient = SSHRemoteclient(self.hostname,
283 self.username,
284 self.password)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500285
Peter D Phan5963d632021-07-12 09:58:55 -0500286 if self.ssh_remoteclient.ssh_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500287 self.logger.info("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500288
Peter D Phan5963d632021-07-12 09:58:55 -0500289 # Check scp connection.
290 # If scp connection fails,
291 # continue with FFDC generation but skip scp files to local host.
292 self.ssh_remoteclient.scp_connection()
293 return True
294 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500295 self.logger.info("\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500296 return False
297
298 def telnet_to_target_system(self):
299 r"""
300 Open a telnet connection to targeted system.
301 """
302 self.telnet_remoteclient = TelnetRemoteclient(self.hostname,
303 self.username,
304 self.password)
305 if self.telnet_remoteclient.tn_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500306 self.logger.info("\n\t[Check] %s Telnet connection established.\t [OK]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500307 return True
308 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500309 self.logger.info("\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500310 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500311
George Keishing772c9772021-06-16 23:23:42 -0500312 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500313 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500314 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500315
Peter D Phan04aca3b2021-06-21 10:37:18 -0500316 Description of argument(s):
317 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500318 """
319
Peter D Phane86d9a52021-07-15 10:42:25 -0500320 self.logger.info("\n\t---- Executing commands on " + self.hostname + " ----")
321 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500322
George Keishingf5a57502021-07-22 16:43:47 -0500323 config_dict = self.ffdc_actions
324 for target_type in config_dict.keys():
325 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500326 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500327
Peter D Phane86d9a52021-07-15 10:42:25 -0500328 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
George Keishingb97a9042021-07-29 07:41:20 -0500329 global_plugin_dict['global_log_store_path'] = self.ffdc_dir_path
George Keishingf5a57502021-07-22 16:43:47 -0500330 self.logger.info("\tSystem Type: %s" % target_type)
331 for k, v in config_dict[target_type].items():
Peter D Phan72ce6b82021-06-03 06:18:26 -0500332
George Keishingf5a57502021-07-22 16:43:47 -0500333 if self.remote_protocol not in working_protocol_list \
George Keishing6ea92b02021-07-01 11:20:50 -0500334 and self.remote_protocol != 'ALL':
335 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500336
George Keishingf5a57502021-07-22 16:43:47 -0500337 protocol = config_dict[target_type][k]['PROTOCOL'][0]
338
339 if protocol not in working_protocol_list:
340 continue
341
George Keishingb7607612021-07-27 13:31:23 -0500342 if protocol in working_protocol_list:
343 if protocol == 'SSH' or protocol == 'SCP':
George Keishing12fd0652021-07-27 13:57:11 -0500344 self.protocol_ssh(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500345 elif protocol == 'TELNET':
George Keishingf5a57502021-07-22 16:43:47 -0500346 self.protocol_telnet(target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500347 elif protocol == 'REDFISH' or protocol == 'IPMI' or protocol == 'SHELL':
George Keishing506b0582021-07-27 09:31:22 -0500348 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500349 else:
350 self.logger.error("\n\tERROR: %s is not available for %s." % (protocol, self.hostname))
George Keishingeafba182021-06-29 13:44:58 -0500351
Peter D Phan04aca3b2021-06-21 10:37:18 -0500352 # Close network connection after collecting all files
Peter D Phan7610bc42021-07-06 06:31:05 -0500353 self.elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - self.start_time))
Peter D Phanbff617a2021-07-22 08:41:35 -0500354 if self.ssh_remoteclient:
355 self.ssh_remoteclient.ssh_remoteclient_disconnect()
356 if self.telnet_remoteclient:
357 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500358
Peter D Phan0c669772021-06-24 13:52:42 -0500359 def protocol_ssh(self,
George Keishing12fd0652021-07-27 13:57:11 -0500360 protocol,
George Keishingf5a57502021-07-22 16:43:47 -0500361 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500362 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500363 r"""
364 Perform actions using SSH and SCP protocols.
365
366 Description of argument(s):
George Keishing12fd0652021-07-27 13:57:11 -0500367 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500368 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500369 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500370 """
371
George Keishing12fd0652021-07-27 13:57:11 -0500372 if protocol == 'SCP':
George Keishingf5a57502021-07-22 16:43:47 -0500373 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500374 else:
George Keishingf5a57502021-07-22 16:43:47 -0500375 self.collect_and_copy_ffdc(self.ffdc_actions[target_type][sub_type])
Peter D Phan0c669772021-06-24 13:52:42 -0500376
Peter D Phan5963d632021-07-12 09:58:55 -0500377 def protocol_telnet(self,
George Keishingf5a57502021-07-22 16:43:47 -0500378 target_type,
Peter D Phan5963d632021-07-12 09:58:55 -0500379 sub_type):
380 r"""
381 Perform actions using telnet protocol.
382 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500383 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500384 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500385 self.logger.info("\n\t[Run] Executing commands on %s using %s" % (self.hostname, 'TELNET'))
Peter D Phan5963d632021-07-12 09:58:55 -0500386 telnet_files_saved = []
387 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500388 list_of_commands = self.ffdc_actions[target_type][sub_type]['COMMANDS']
Peter D Phan5963d632021-07-12 09:58:55 -0500389 for index, each_cmd in enumerate(list_of_commands, start=0):
390 command_txt, command_timeout = self.unpack_command(each_cmd)
391 result = self.telnet_remoteclient.execute_command(command_txt, command_timeout)
392 if result:
393 try:
George Keishingf5a57502021-07-22 16:43:47 -0500394 targ_file = self.ffdc_actions[target_type][sub_type]['FILES'][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500395 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500396 targ_file = command_txt
397 self.logger.warning(
398 "\n\t[WARN] Missing filename to store data from telnet %s." % each_cmd)
399 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan5963d632021-07-12 09:58:55 -0500400 targ_file_with_path = (self.ffdc_dir_path
401 + self.ffdc_prefix
402 + targ_file)
403 # Creates a new file
Peter D Phanb76e1752021-08-03 12:50:05 -0500404 with open(targ_file_with_path, 'w') as fp:
Peter D Phan5963d632021-07-12 09:58:55 -0500405 fp.write(result)
406 fp.close
407 telnet_files_saved.append(targ_file)
408 progress_counter += 1
409 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500410 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500411 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500412 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500413
George Keishing506b0582021-07-27 09:31:22 -0500414 def protocol_execute(self,
415 protocol,
George Keishingf5a57502021-07-22 16:43:47 -0500416 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500417 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500418 r"""
George Keishing506b0582021-07-27 09:31:22 -0500419 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500420
421 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500422 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500423 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500424 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500425 """
426
George Keishing506b0582021-07-27 09:31:22 -0500427 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, protocol))
428 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500429 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500430 list_of_cmd = self.get_command_list(self.ffdc_actions[target_type][sub_type])
George Keishingeafba182021-06-29 13:44:58 -0500431 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishingcaa97e62021-08-03 14:00:09 -0500432 plugin_call = False
George Keishingb97a9042021-07-29 07:41:20 -0500433 if isinstance(each_cmd, dict):
434 if 'plugin' in each_cmd:
George Keishing1e7b0182021-08-06 14:05:54 -0500435 # If the error is set and plugin explicitly
436 # requested to skip execution on error..
437 if plugin_error_dict['exit_on_error'] and \
438 self.plugin_error_check(each_cmd['plugin']):
439 self.logger.info("\n\t[PLUGIN-ERROR] exit_on_error: %s" %
440 plugin_error_dict['exit_on_error'])
441 self.logger.info("\t[PLUGIN-SKIP] %s" %
442 each_cmd['plugin'][0])
443 continue
George Keishingcaa97e62021-08-03 14:00:09 -0500444 plugin_call = True
George Keishingb97a9042021-07-29 07:41:20 -0500445 # call the plugin
446 self.logger.info("\n\t[PLUGIN-START]")
George Keishingcaa97e62021-08-03 14:00:09 -0500447 result = self.execute_plugin_block(each_cmd['plugin'])
George Keishingb97a9042021-07-29 07:41:20 -0500448 self.logger.info("\t[PLUGIN-END]\n")
George Keishingb97a9042021-07-29 07:41:20 -0500449 else:
George Keishing2b83e042021-08-03 12:56:11 -0500450 each_cmd = self.yaml_env_and_plugin_vars_populate(each_cmd)
George Keishingb97a9042021-07-29 07:41:20 -0500451
George Keishingcaa97e62021-08-03 14:00:09 -0500452 if not plugin_call:
453 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500454 if result:
455 try:
George Keishingcaa97e62021-08-03 14:00:09 -0500456 file_name = self.get_file_list(self.ffdc_actions[target_type][sub_type])[index]
George Keishingb97a9042021-07-29 07:41:20 -0500457 # If file is specified as None.
George Keishing0581cb02021-08-05 15:08:58 -0500458 if file_name == "None":
George Keishingb97a9042021-07-29 07:41:20 -0500459 continue
George Keishing0581cb02021-08-05 15:08:58 -0500460 targ_file = self.yaml_env_and_plugin_vars_populate(file_name)
George Keishingeafba182021-06-29 13:44:58 -0500461 except IndexError:
George Keishing6ea92b02021-07-01 11:20:50 -0500462 targ_file = each_cmd.split('/')[-1]
George Keishing506b0582021-07-27 09:31:22 -0500463 self.logger.warning(
464 "\n\t[WARN] Missing filename to store data from %s." % each_cmd)
Peter D Phane86d9a52021-07-15 10:42:25 -0500465 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500466
467 targ_file_with_path = (self.ffdc_dir_path
468 + self.ffdc_prefix
469 + targ_file)
470
471 # Creates a new file
472 with open(targ_file_with_path, 'w') as fp:
473 fp.write(result)
474 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500475 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500476
477 progress_counter += 1
478 self.print_progress(progress_counter)
479
Peter D Phane86d9a52021-07-15 10:42:25 -0500480 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500481
George Keishing506b0582021-07-27 09:31:22 -0500482 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500483 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500484
Peter D Phan04aca3b2021-06-21 10:37:18 -0500485 def collect_and_copy_ffdc(self,
George Keishingf5a57502021-07-22 16:43:47 -0500486 ffdc_actions_for_target_type,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500487 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500488 r"""
489 Send commands in ffdc_config file to targeted system.
490
491 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500492 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500493 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500494 """
495
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500496 # Executing commands, if any
George Keishingf5a57502021-07-22 16:43:47 -0500497 self.ssh_execute_ffdc_commands(ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500498 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500499
Peter D Phan3beb02e2021-07-06 13:25:17 -0500500 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500501 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500502 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500503
Peter D Phan04aca3b2021-06-21 10:37:18 -0500504 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500505 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500506 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500507 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500508 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500509
Peter D Phanbabf2962021-07-07 11:24:40 -0500510 def get_command_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500511 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500512 r"""
513 Fetch list of commands from configuration file
514
515 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500516 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500517 """
518 try:
George Keishingf5a57502021-07-22 16:43:47 -0500519 list_of_commands = ffdc_actions_for_target_type['COMMANDS']
Peter D Phanbabf2962021-07-07 11:24:40 -0500520 except KeyError:
521 list_of_commands = []
522 return list_of_commands
523
524 def get_file_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500525 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500526 r"""
527 Fetch list of commands from configuration file
528
529 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500530 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500531 """
532 try:
George Keishingf5a57502021-07-22 16:43:47 -0500533 list_of_files = ffdc_actions_for_target_type['FILES']
Peter D Phanbabf2962021-07-07 11:24:40 -0500534 except KeyError:
535 list_of_files = []
536 return list_of_files
537
Peter D Phan5963d632021-07-12 09:58:55 -0500538 def unpack_command(self,
539 command):
540 r"""
541 Unpack command from config file
542
543 Description of argument(s):
544 command Command from config file.
545 """
546 if isinstance(command, dict):
547 command_txt = next(iter(command))
548 command_timeout = next(iter(command.values()))
549 elif isinstance(command, str):
550 command_txt = command
551 # Default command timeout 60 seconds
552 command_timeout = 60
553
554 return command_txt, command_timeout
555
Peter D Phan3beb02e2021-07-06 13:25:17 -0500556 def ssh_execute_ffdc_commands(self,
George Keishingf5a57502021-07-22 16:43:47 -0500557 ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500558 form_filename=False):
559 r"""
560 Send commands in ffdc_config file to targeted system.
561
562 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500563 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500564 form_filename if true, pre-pend self.target_type to filename
565 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500566 self.logger.info("\n\t[Run] Executing commands on %s using %s"
George Keishingf5a57502021-07-22 16:43:47 -0500567 % (self.hostname, ffdc_actions_for_target_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500568
George Keishingf5a57502021-07-22 16:43:47 -0500569 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500570 # If command list is empty, returns
571 if not list_of_commands:
572 return
573
574 progress_counter = 0
575 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500576 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500577
578 if form_filename:
579 command_txt = str(command_txt % self.target_type)
580
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500581 cmd_exit_code, err, response = \
582 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
583
584 if cmd_exit_code:
585 self.logger.warning(
586 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
587 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500588
Peter D Phan3beb02e2021-07-06 13:25:17 -0500589 progress_counter += 1
590 self.print_progress(progress_counter)
591
Peter D Phane86d9a52021-07-15 10:42:25 -0500592 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500593
Peter D Phan56429a62021-06-23 08:38:29 -0500594 def group_copy(self,
George Keishingf5a57502021-07-22 16:43:47 -0500595 ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500596 r"""
597 scp group of files (wild card) from remote host.
598
599 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500600 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500601 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500602
Peter D Phan5963d632021-07-12 09:58:55 -0500603 if self.ssh_remoteclient.scpclient:
George Keishing12fd0652021-07-27 13:57:11 -0500604 self.logger.info("\n\tCopying files from remote system %s via SCP.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500605
George Keishingf5a57502021-07-22 16:43:47 -0500606 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phanbabf2962021-07-07 11:24:40 -0500607 # If command list is empty, returns
608 if not list_of_commands:
609 return
Peter D Phan56429a62021-06-23 08:38:29 -0500610
Peter D Phanbabf2962021-07-07 11:24:40 -0500611 for command in list_of_commands:
612 try:
George Keishingb4540e72021-08-02 13:48:46 -0500613 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500614 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500615 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500616 continue
617
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500618 cmd_exit_code, err, response = \
619 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500620
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500621 # If file does not exist, code take no action.
622 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500623 if response:
George Keishinga56e87b2021-08-06 00:24:19 -0500624 scp_result = \
625 self.ssh_remoteclient.scp_file_from_remote(response.split('\n'),
626 self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500627 if scp_result:
George Keishinga56e87b2021-08-06 00:24:19 -0500628 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + command)
Peter D Phan56429a62021-06-23 08:38:29 -0500629 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500630 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500631
632 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500633 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500634
Peter D Phan72ce6b82021-06-03 06:18:26 -0500635 def scp_ffdc(self,
636 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500637 targ_file_prefix,
638 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500639 file_list=None,
640 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500641 r"""
642 SCP all files in file_dict to the indicated directory on the local system.
643
644 Description of argument(s):
645 targ_dir_path The path of the directory to receive the files.
646 targ_file_prefix Prefix which will be pre-pended to each
647 target file's name.
648 file_dict A dictionary of files to scp from targeted system to this system
649
650 """
651
Peter D Phan72ce6b82021-06-03 06:18:26 -0500652 progress_counter = 0
653 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500654 if form_filename:
655 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500656 source_file_path = filename
657 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
658
Peter D Phanbabf2962021-07-07 11:24:40 -0500659 # If source file name contains wild card, copy filename as is.
660 if '*' in source_file_path:
Peter D Phan5963d632021-07-12 09:58:55 -0500661 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500662 else:
Peter D Phan5963d632021-07-12 09:58:55 -0500663 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500664
665 if not quiet:
666 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500667 self.logger.info(
668 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500669 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500670 self.logger.info(
671 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500672 else:
673 progress_counter += 1
674 self.print_progress(progress_counter)
675
Peter D Phan72ce6b82021-06-03 06:18:26 -0500676 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500677 r"""
678 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
679 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
680 Individual ffdc file will have timestr_filename.
681
682 Description of class variables:
683 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
684
685 self.ffdc_prefix The prefix to be given to each ffdc file name.
686
687 """
688
689 timestr = time.strftime("%Y%m%d-%H%M%S")
690 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
691 self.ffdc_prefix = timestr + "_"
692 self.validate_local_store(self.ffdc_dir_path)
693
694 def validate_local_store(self, dir_path):
695 r"""
696 Ensure path exists to store FFDC files locally.
697
698 Description of variable:
699 dir_path The dir path where collected ffdc data files will be stored.
700
701 """
702
703 if not os.path.exists(dir_path):
704 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500705 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500706 except (IOError, OSError) as e:
707 # PermissionError
708 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500709 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500710 '\tERROR: os.makedirs %s failed with PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500711 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500712 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500713 '\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500714 sys.exit(-1)
715
716 def print_progress(self, progress):
717 r"""
718 Print activity progress +
719
720 Description of variable:
721 progress Progress counter.
722
723 """
724
725 sys.stdout.write("\r\t" + "+" * progress)
726 sys.stdout.flush()
727 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500728
729 def verify_redfish(self):
730 r"""
731 Verify remote host has redfish service active
732
733 """
George Keishing506b0582021-07-27 09:31:22 -0500734 redfish_parm = 'redfishtool -r ' \
Peter D Phan0c669772021-06-24 13:52:42 -0500735 + self.hostname + ' -S Always raw GET /redfish/v1/'
George Keishing506b0582021-07-27 09:31:22 -0500736 return(self.run_tool_cmd(redfish_parm, True))
Peter D Phan0c669772021-06-24 13:52:42 -0500737
George Keishingeafba182021-06-29 13:44:58 -0500738 def verify_ipmi(self):
739 r"""
740 Verify remote host has IPMI LAN service active
741
742 """
George Keishing484f8242021-07-27 01:42:02 -0500743 if self.target_type == 'OPENBMC':
744 ipmi_parm = 'ipmitool -I lanplus -C 17 -U ' + self.username + ' -P ' \
745 + self.password + ' -H ' + self.hostname + ' power status'
746 else:
747 ipmi_parm = 'ipmitool -I lanplus -P ' \
748 + self.password + ' -H ' + self.hostname + ' power status'
749
George Keishing506b0582021-07-27 09:31:22 -0500750 return(self.run_tool_cmd(ipmi_parm, True))
George Keishingeafba182021-06-29 13:44:58 -0500751
George Keishing506b0582021-07-27 09:31:22 -0500752 def run_tool_cmd(self,
George Keishingeafba182021-06-29 13:44:58 -0500753 parms_string,
754 quiet=False):
755 r"""
George Keishing506b0582021-07-27 09:31:22 -0500756 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500757
758 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500759 parms_string tool command options.
760 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500761 """
762
George Keishing484f8242021-07-27 01:42:02 -0500763 result = subprocess.run([parms_string],
George Keishingeafba182021-06-29 13:44:58 -0500764 stdout=subprocess.PIPE,
765 stderr=subprocess.PIPE,
766 shell=True,
767 universal_newlines=True)
768
769 if result.stderr and not quiet:
George Keishing484f8242021-07-27 01:42:02 -0500770 self.logger.error('\n\t\tERROR with %s ' % parms_string)
Peter D Phane86d9a52021-07-15 10:42:25 -0500771 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500772
773 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500774
George Keishingf5a57502021-07-22 16:43:47 -0500775 def verify_protocol(self, protocol_list):
776 r"""
777 Perform protocol working check.
778
779 Description of argument(s):
780 protocol_list List of protocol.
781 """
782
783 tmp_list = []
784 if self.target_is_pingable():
785 tmp_list.append("SHELL")
786
787 for protocol in protocol_list:
788 if self.remote_protocol != 'ALL':
789 if self.remote_protocol != protocol:
790 continue
791
792 # Only check SSH/SCP once for both protocols
793 if protocol == 'SSH' or protocol == 'SCP' and protocol not in tmp_list:
794 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -0500795 # Add only what user asked.
796 if self.remote_protocol != 'ALL':
797 tmp_list.append(self.remote_protocol)
798 else:
799 tmp_list.append('SSH')
800 tmp_list.append('SCP')
George Keishingf5a57502021-07-22 16:43:47 -0500801
802 if protocol == 'TELNET':
803 if self.telnet_to_target_system():
804 tmp_list.append(protocol)
805
806 if protocol == 'REDFISH':
807 if self.verify_redfish():
808 tmp_list.append(protocol)
809 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
810 else:
811 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
812
813 if protocol == 'IPMI':
814 if self.verify_ipmi():
815 tmp_list.append(protocol)
816 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
817 else:
818 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
819
820 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -0500821
822 def load_env(self):
823 r"""
824 Perform protocol working check.
825
826 """
827 # This is for the env vars a user can use in YAML to load it at runtime.
828 # Example YAML:
829 # -COMMANDS:
830 # - my_command ${hostname} ${username} ${password}
831 os.environ['hostname'] = self.hostname
832 os.environ['username'] = self.username
833 os.environ['password'] = self.password
834
835 # Append default Env.
836 self.env_dict['hostname'] = self.hostname
837 self.env_dict['username'] = self.username
838 self.env_dict['password'] = self.password
839
840 try:
841 tmp_env_dict = {}
842 if self.env_vars:
843 tmp_env_dict = json.loads(self.env_vars)
844 # Export ENV vars default.
845 for key, value in tmp_env_dict.items():
846 os.environ[key] = value
847 self.env_dict[key] = str(value)
848
849 if self.econfig:
850 with open(self.econfig, 'r') as file:
851 tmp_env_dict = yaml.load(file, Loader=yaml.FullLoader)
852 # Export ENV vars.
853 for key, value in tmp_env_dict['env_params'].items():
854 os.environ[key] = str(value)
855 self.env_dict[key] = str(value)
856 except json.decoder.JSONDecodeError as e:
857 self.logger.error("\n\tERROR: %s " % e)
858 sys.exit(-1)
859
860 # This to mask the password from displaying on the console.
861 mask_dict = self.env_dict.copy()
862 for k, v in mask_dict.items():
863 if k.lower().find("password") != -1:
864 hidden_text = []
865 hidden_text.append(v)
866 password_regex = '(' +\
867 '|'.join([re.escape(x) for x in hidden_text]) + ')'
868 mask_dict[k] = re.sub(password_regex, "********", v)
869
870 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -0500871
872 def execute_python_eval(self, eval_string):
873 r"""
874 Execute qualified python function using eval.
875
876 Description of argument(s):
877 eval_string Execute the python object.
878
879 Example:
880 eval(plugin.foo_func.foo_func(10))
881 """
882 try:
883 self.logger.info("\tCall func: %s" % eval_string)
884 result = eval(eval_string)
885 self.logger.info("\treturn: %s" % str(result))
886 except (ValueError, SyntaxError, NameError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -0500887 self.logger.error("\tERROR: execute_python_eval: %s" % e)
888 # Set the plugin error state.
889 plugin_error_dict['exit_on_error'] = True
George Keishingb97a9042021-07-29 07:41:20 -0500890 pass
891
892 return result
893
894 def execute_plugin_block(self, plugin_cmd_list):
895 r"""
896 Pack the plugin command to quailifed python string object.
897
898 Description of argument(s):
899 plugin_list_dict Plugin block read from YAML
900 [{'plugin_name': 'plugin.foo_func.my_func'},
901 {'plugin_args': [10]}]
902
903 Example:
904 - plugin:
905 - plugin_name: plugin.foo_func.my_func
906 - plugin_args:
907 - arg1
908 - arg2
909
910 - plugin:
911 - plugin_name: result = plugin.foo_func.my_func
912 - plugin_args:
913 - arg1
914 - arg2
915
916 - plugin:
917 - plugin_name: result1,result2 = plugin.foo_func.my_func
918 - plugin_args:
919 - arg1
920 - arg2
921 """
922 try:
923 plugin_name = plugin_cmd_list[0]['plugin_name']
924 # Equal separator means plugin function returns result.
925 if ' = ' in plugin_name:
926 # Ex. ['result', 'plugin.foo_func.my_func']
927 plugin_name_args = plugin_name.split(' = ')
928 # plugin func return data.
929 for arg in plugin_name_args:
930 if arg == plugin_name_args[-1]:
931 plugin_name = arg
932 else:
933 plugin_resp = arg.split(',')
934 # ['result1','result2']
935 for x in plugin_resp:
936 global_plugin_list.append(x)
937 global_plugin_dict[x] = ""
938
939 # Walk the plugin args ['arg1,'arg2']
940 # If the YAML plugin statement 'plugin_args' is not declared.
941 if any('plugin_args' in d for d in plugin_cmd_list):
942 plugin_args = plugin_cmd_list[1]['plugin_args']
943 if plugin_args:
944 plugin_args = self.yaml_args_populate(plugin_args)
945 else:
946 plugin_args = []
947 else:
948 plugin_args = self.yaml_args_populate([])
949
950 # Pack the args arg1, arg2, .... argn into
951 # "arg1","arg2","argn" string as params for function.
952 parm_args_str = self.yaml_args_string(plugin_args)
953 if parm_args_str:
954 plugin_func = plugin_name + '(' + parm_args_str + ')'
955 else:
956 plugin_func = plugin_name + '()'
957
958 # Execute plugin function.
959 if global_plugin_dict:
960 resp = self.execute_python_eval(plugin_func)
961 self.response_args_data(resp)
962 else:
George Keishingcaa97e62021-08-03 14:00:09 -0500963 resp = self.execute_python_eval(plugin_func)
964 return resp
George Keishingb97a9042021-07-29 07:41:20 -0500965 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -0500966 # Set the plugin error state.
967 plugin_error_dict['exit_on_error'] = True
968 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -0500969 pass
970
971 def response_args_data(self, plugin_resp):
972 r"""
973 Parse the plugin function response.
974
975 plugin_resp Response data from plugin function.
976 """
977 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -0500978 resp_data = ""
George Keishingb97a9042021-07-29 07:41:20 -0500979 # There is nothing to update the plugin response.
980 if len(global_plugin_list) == 0 or plugin_resp == 'None':
981 return
982
George Keishing5765f792021-08-02 13:08:53 -0500983 if isinstance(plugin_resp, str):
984 resp_data = plugin_resp.strip('\r\n\t')
985 resp_list.append(resp_data)
986 elif isinstance(plugin_resp, bytes):
987 resp_data = str(plugin_resp, 'UTF-8').strip('\r\n\t')
988 resp_list.append(resp_data)
989 elif isinstance(plugin_resp, tuple):
990 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -0500991 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -0500992 else:
993 resp_list = list(plugin_resp)
994 resp_list = [x.strip('\r\n\t') for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -0500995 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -0500996 if len(global_plugin_list) == 1:
997 resp_list.append([x.strip('\r\n\t') for x in plugin_resp])
998 else:
999 resp_list = [x.strip('\r\n\t') for x in plugin_resp]
1000 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1001 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001002
1003 for idx, item in enumerate(resp_list, start=0):
1004 # Exit loop
1005 if idx >= len(global_plugin_list):
1006 break
1007 # Find the index of the return func in the list and
1008 # update the global func return dictionary.
1009 try:
1010 dict_idx = global_plugin_list[idx]
1011 global_plugin_dict[dict_idx] = item
1012 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001013 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001014 pass
1015
1016 # Done updating plugin dict irrespective of pass or failed,
1017 # clear all the list element.
1018 global_plugin_list.clear()
1019
1020 def yaml_args_string(self, plugin_args):
1021 r"""
1022 Pack the args into string.
1023
1024 plugin_args arg list ['arg1','arg2,'argn']
1025 """
1026 args_str = ''
1027 for args in plugin_args:
1028 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001029 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001030 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001031 elif args in global_plugin_type_list:
1032 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001033 else:
1034 args_str += '"' + str(args.strip('\r\n\t')) + '"'
1035 # Skip last list element.
1036 if args != plugin_args[-1]:
1037 args_str += ","
1038 return args_str
1039
1040 def yaml_args_populate(self, yaml_arg_list):
1041 r"""
1042 Decode ${MY_VAR} and load env data when read from YAML.
1043
1044 Description of argument(s):
1045 yaml_arg_list arg list read from YAML
1046
1047 Example:
1048 - plugin_args:
1049 - arg1
1050 - arg2
1051
1052 yaml_arg_list: [arg2, arg2]
1053 """
1054 # Get the env loaded keys as list ['hostname', 'username', 'password'].
1055 env_vars_list = list(self.env_dict)
1056
1057 if isinstance(yaml_arg_list, list):
1058 tmp_list = []
1059 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001060 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001061 tmp_list.append(arg)
1062 continue
1063 elif isinstance(arg, str):
1064 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1065 tmp_list.append(arg_str)
1066 else:
1067 tmp_list.append(arg)
1068
1069 # return populated list.
1070 return tmp_list
1071
1072 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1073 r"""
1074 Update ${MY_VAR} and my_plugin_vars
1075
1076 Description of argument(s):
1077 yaml_arg_str arg string read from YAML
1078
1079 Example:
1080 - cat ${MY_VAR}
1081 - ls -AX my_plugin_var
1082 """
1083 # Parse the string for env vars.
1084 try:
1085 # Example, list of matching env vars ['username', 'password', 'hostname']
1086 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
1087 var_name_regex = '\\$\\{([^\\}]+)\\}'
1088 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1089 for var in env_var_names_list:
1090 env_var = os.environ[var]
1091 env_replace = '${' + var + '}'
1092 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1093 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001094 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001095 pass
1096
1097 # Parse the string for plugin vars.
1098 try:
1099 # Example, list of plugin vars ['my_username', 'my_data']
1100 plugin_var_name_list = global_plugin_dict.keys()
1101 for var in plugin_var_name_list:
George Keishing0581cb02021-08-05 15:08:58 -05001102 # skip env var list already populated above block list.
1103 if var in env_var_names_list:
1104 continue
George Keishingb97a9042021-07-29 07:41:20 -05001105 # If this plugin var exist but empty value in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001106 # This is either a YAML plugin statement incorrectly used or
George Keishingb97a9042021-07-29 07:41:20 -05001107 # user added a plugin var which is not populated.
George Keishing0581cb02021-08-05 15:08:58 -05001108 if yaml_arg_str in global_plugin_dict:
1109 if isinstance(global_plugin_dict[var], (list, dict)):
1110 # List data type or dict can't be replaced, use directly
1111 # in eval function call.
1112 global_plugin_type_list.append(var)
1113 else:
1114 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
1115 # Just a string like filename or command.
1116 else:
George Keishingb97a9042021-07-29 07:41:20 -05001117 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
1118 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001119 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001120 pass
1121
1122 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001123
1124 def plugin_error_check(self, plugin_dict):
1125 r"""
1126 Plugin error dict processing.
1127
1128 Description of argument(s):
1129 plugin_dict Dictionary of plugin error.
1130 """
1131 if any('plugin_error' in d for d in plugin_dict):
1132 for d in plugin_dict:
1133 if 'plugin_error' in d:
1134 value = d['plugin_error']
1135 # Reference if the error is set or not by plugin.
1136 return plugin_error_dict[value]