blob: e33fb847244e614a22046fd5bb570c2bb1bb5476 [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:
George Keishing91308ea2021-08-10 14:43:15 -0500473 if isinstance(result, dict):
474 fp.write(json.dumps(result))
475 else:
476 fp.write(result)
George Keishingeafba182021-06-29 13:44:58 -0500477 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500478 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500479
480 progress_counter += 1
481 self.print_progress(progress_counter)
482
Peter D Phane86d9a52021-07-15 10:42:25 -0500483 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500484
George Keishing506b0582021-07-27 09:31:22 -0500485 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500486 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500487
Peter D Phan04aca3b2021-06-21 10:37:18 -0500488 def collect_and_copy_ffdc(self,
George Keishingf5a57502021-07-22 16:43:47 -0500489 ffdc_actions_for_target_type,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500490 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500491 r"""
492 Send commands in ffdc_config file to targeted system.
493
494 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500495 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500496 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500497 """
498
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500499 # Executing commands, if any
George Keishingf5a57502021-07-22 16:43:47 -0500500 self.ssh_execute_ffdc_commands(ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500501 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500502
Peter D Phan3beb02e2021-07-06 13:25:17 -0500503 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500504 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500505 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500506
Peter D Phan04aca3b2021-06-21 10:37:18 -0500507 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500508 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500509 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500510 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500511 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500512
Peter D Phanbabf2962021-07-07 11:24:40 -0500513 def get_command_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500514 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500515 r"""
516 Fetch list of commands from configuration file
517
518 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500519 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500520 """
521 try:
George Keishingf5a57502021-07-22 16:43:47 -0500522 list_of_commands = ffdc_actions_for_target_type['COMMANDS']
Peter D Phanbabf2962021-07-07 11:24:40 -0500523 except KeyError:
524 list_of_commands = []
525 return list_of_commands
526
527 def get_file_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500528 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500529 r"""
530 Fetch list of commands from configuration file
531
532 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500533 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500534 """
535 try:
George Keishingf5a57502021-07-22 16:43:47 -0500536 list_of_files = ffdc_actions_for_target_type['FILES']
Peter D Phanbabf2962021-07-07 11:24:40 -0500537 except KeyError:
538 list_of_files = []
539 return list_of_files
540
Peter D Phan5963d632021-07-12 09:58:55 -0500541 def unpack_command(self,
542 command):
543 r"""
544 Unpack command from config file
545
546 Description of argument(s):
547 command Command from config file.
548 """
549 if isinstance(command, dict):
550 command_txt = next(iter(command))
551 command_timeout = next(iter(command.values()))
552 elif isinstance(command, str):
553 command_txt = command
554 # Default command timeout 60 seconds
555 command_timeout = 60
556
557 return command_txt, command_timeout
558
Peter D Phan3beb02e2021-07-06 13:25:17 -0500559 def ssh_execute_ffdc_commands(self,
George Keishingf5a57502021-07-22 16:43:47 -0500560 ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500561 form_filename=False):
562 r"""
563 Send commands in ffdc_config file to targeted system.
564
565 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500566 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500567 form_filename if true, pre-pend self.target_type to filename
568 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500569 self.logger.info("\n\t[Run] Executing commands on %s using %s"
George Keishingf5a57502021-07-22 16:43:47 -0500570 % (self.hostname, ffdc_actions_for_target_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500571
George Keishingf5a57502021-07-22 16:43:47 -0500572 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500573 # If command list is empty, returns
574 if not list_of_commands:
575 return
576
577 progress_counter = 0
578 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500579 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500580
581 if form_filename:
582 command_txt = str(command_txt % self.target_type)
583
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500584 cmd_exit_code, err, response = \
585 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
586
587 if cmd_exit_code:
588 self.logger.warning(
589 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
590 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500591
Peter D Phan3beb02e2021-07-06 13:25:17 -0500592 progress_counter += 1
593 self.print_progress(progress_counter)
594
Peter D Phane86d9a52021-07-15 10:42:25 -0500595 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500596
Peter D Phan56429a62021-06-23 08:38:29 -0500597 def group_copy(self,
George Keishingf5a57502021-07-22 16:43:47 -0500598 ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500599 r"""
600 scp group of files (wild card) from remote host.
601
602 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500603 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500604 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500605
Peter D Phan5963d632021-07-12 09:58:55 -0500606 if self.ssh_remoteclient.scpclient:
George Keishing12fd0652021-07-27 13:57:11 -0500607 self.logger.info("\n\tCopying files from remote system %s via SCP.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500608
George Keishingf5a57502021-07-22 16:43:47 -0500609 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phanbabf2962021-07-07 11:24:40 -0500610 # If command list is empty, returns
611 if not list_of_commands:
612 return
Peter D Phan56429a62021-06-23 08:38:29 -0500613
Peter D Phanbabf2962021-07-07 11:24:40 -0500614 for command in list_of_commands:
615 try:
George Keishingb4540e72021-08-02 13:48:46 -0500616 command = self.yaml_env_and_plugin_vars_populate(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500617 except IndexError:
George Keishingb4540e72021-08-02 13:48:46 -0500618 self.logger.error("\t\tInvalid command %s" % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500619 continue
620
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500621 cmd_exit_code, err, response = \
622 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500623
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500624 # If file does not exist, code take no action.
625 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500626 if response:
George Keishinga56e87b2021-08-06 00:24:19 -0500627 scp_result = \
628 self.ssh_remoteclient.scp_file_from_remote(response.split('\n'),
629 self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500630 if scp_result:
George Keishinga56e87b2021-08-06 00:24:19 -0500631 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + command)
Peter D Phan56429a62021-06-23 08:38:29 -0500632 else:
George Keishinga56e87b2021-08-06 00:24:19 -0500633 self.logger.info("\t\t%s has no result" % command)
Peter D Phan56429a62021-06-23 08:38:29 -0500634
635 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500636 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500637
Peter D Phan72ce6b82021-06-03 06:18:26 -0500638 def scp_ffdc(self,
639 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500640 targ_file_prefix,
641 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500642 file_list=None,
643 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500644 r"""
645 SCP all files in file_dict to the indicated directory on the local system.
646
647 Description of argument(s):
648 targ_dir_path The path of the directory to receive the files.
649 targ_file_prefix Prefix which will be pre-pended to each
650 target file's name.
651 file_dict A dictionary of files to scp from targeted system to this system
652
653 """
654
Peter D Phan72ce6b82021-06-03 06:18:26 -0500655 progress_counter = 0
656 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500657 if form_filename:
658 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500659 source_file_path = filename
660 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
661
Peter D Phanbabf2962021-07-07 11:24:40 -0500662 # If source file name contains wild card, copy filename as is.
663 if '*' in source_file_path:
Peter D Phan5963d632021-07-12 09:58:55 -0500664 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500665 else:
Peter D Phan5963d632021-07-12 09:58:55 -0500666 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500667
668 if not quiet:
669 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500670 self.logger.info(
671 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500672 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500673 self.logger.info(
674 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500675 else:
676 progress_counter += 1
677 self.print_progress(progress_counter)
678
Peter D Phan72ce6b82021-06-03 06:18:26 -0500679 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500680 r"""
681 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
682 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
683 Individual ffdc file will have timestr_filename.
684
685 Description of class variables:
686 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
687
688 self.ffdc_prefix The prefix to be given to each ffdc file name.
689
690 """
691
692 timestr = time.strftime("%Y%m%d-%H%M%S")
693 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
694 self.ffdc_prefix = timestr + "_"
695 self.validate_local_store(self.ffdc_dir_path)
696
697 def validate_local_store(self, dir_path):
698 r"""
699 Ensure path exists to store FFDC files locally.
700
701 Description of variable:
702 dir_path The dir path where collected ffdc data files will be stored.
703
704 """
705
706 if not os.path.exists(dir_path):
707 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500708 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500709 except (IOError, OSError) as e:
710 # PermissionError
711 if e.errno == EPERM or e.errno == EACCES:
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 PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500714 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500715 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500716 '\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500717 sys.exit(-1)
718
719 def print_progress(self, progress):
720 r"""
721 Print activity progress +
722
723 Description of variable:
724 progress Progress counter.
725
726 """
727
728 sys.stdout.write("\r\t" + "+" * progress)
729 sys.stdout.flush()
730 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500731
732 def verify_redfish(self):
733 r"""
734 Verify remote host has redfish service active
735
736 """
George Keishing506b0582021-07-27 09:31:22 -0500737 redfish_parm = 'redfishtool -r ' \
Peter D Phan0c669772021-06-24 13:52:42 -0500738 + self.hostname + ' -S Always raw GET /redfish/v1/'
George Keishing506b0582021-07-27 09:31:22 -0500739 return(self.run_tool_cmd(redfish_parm, True))
Peter D Phan0c669772021-06-24 13:52:42 -0500740
George Keishingeafba182021-06-29 13:44:58 -0500741 def verify_ipmi(self):
742 r"""
743 Verify remote host has IPMI LAN service active
744
745 """
George Keishing484f8242021-07-27 01:42:02 -0500746 if self.target_type == 'OPENBMC':
747 ipmi_parm = 'ipmitool -I lanplus -C 17 -U ' + self.username + ' -P ' \
748 + self.password + ' -H ' + self.hostname + ' power status'
749 else:
750 ipmi_parm = 'ipmitool -I lanplus -P ' \
751 + self.password + ' -H ' + self.hostname + ' power status'
752
George Keishing506b0582021-07-27 09:31:22 -0500753 return(self.run_tool_cmd(ipmi_parm, True))
George Keishingeafba182021-06-29 13:44:58 -0500754
George Keishing506b0582021-07-27 09:31:22 -0500755 def run_tool_cmd(self,
George Keishingeafba182021-06-29 13:44:58 -0500756 parms_string,
757 quiet=False):
758 r"""
George Keishing506b0582021-07-27 09:31:22 -0500759 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500760
761 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500762 parms_string tool command options.
763 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500764 """
765
George Keishing484f8242021-07-27 01:42:02 -0500766 result = subprocess.run([parms_string],
George Keishingeafba182021-06-29 13:44:58 -0500767 stdout=subprocess.PIPE,
768 stderr=subprocess.PIPE,
769 shell=True,
770 universal_newlines=True)
771
772 if result.stderr and not quiet:
George Keishing484f8242021-07-27 01:42:02 -0500773 self.logger.error('\n\t\tERROR with %s ' % parms_string)
Peter D Phane86d9a52021-07-15 10:42:25 -0500774 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500775
776 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500777
George Keishingf5a57502021-07-22 16:43:47 -0500778 def verify_protocol(self, protocol_list):
779 r"""
780 Perform protocol working check.
781
782 Description of argument(s):
783 protocol_list List of protocol.
784 """
785
786 tmp_list = []
787 if self.target_is_pingable():
788 tmp_list.append("SHELL")
789
790 for protocol in protocol_list:
791 if self.remote_protocol != 'ALL':
792 if self.remote_protocol != protocol:
793 continue
794
795 # Only check SSH/SCP once for both protocols
796 if protocol == 'SSH' or protocol == 'SCP' and protocol not in tmp_list:
797 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -0500798 # Add only what user asked.
799 if self.remote_protocol != 'ALL':
800 tmp_list.append(self.remote_protocol)
801 else:
802 tmp_list.append('SSH')
803 tmp_list.append('SCP')
George Keishingf5a57502021-07-22 16:43:47 -0500804
805 if protocol == 'TELNET':
806 if self.telnet_to_target_system():
807 tmp_list.append(protocol)
808
809 if protocol == 'REDFISH':
810 if self.verify_redfish():
811 tmp_list.append(protocol)
812 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
813 else:
814 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
815
816 if protocol == 'IPMI':
817 if self.verify_ipmi():
818 tmp_list.append(protocol)
819 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
820 else:
821 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
822
823 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -0500824
825 def load_env(self):
826 r"""
827 Perform protocol working check.
828
829 """
830 # This is for the env vars a user can use in YAML to load it at runtime.
831 # Example YAML:
832 # -COMMANDS:
833 # - my_command ${hostname} ${username} ${password}
834 os.environ['hostname'] = self.hostname
835 os.environ['username'] = self.username
836 os.environ['password'] = self.password
837
838 # Append default Env.
839 self.env_dict['hostname'] = self.hostname
840 self.env_dict['username'] = self.username
841 self.env_dict['password'] = self.password
842
843 try:
844 tmp_env_dict = {}
845 if self.env_vars:
846 tmp_env_dict = json.loads(self.env_vars)
847 # Export ENV vars default.
848 for key, value in tmp_env_dict.items():
849 os.environ[key] = value
850 self.env_dict[key] = str(value)
851
852 if self.econfig:
853 with open(self.econfig, 'r') as file:
854 tmp_env_dict = yaml.load(file, Loader=yaml.FullLoader)
855 # Export ENV vars.
856 for key, value in tmp_env_dict['env_params'].items():
857 os.environ[key] = str(value)
858 self.env_dict[key] = str(value)
859 except json.decoder.JSONDecodeError as e:
860 self.logger.error("\n\tERROR: %s " % e)
861 sys.exit(-1)
862
863 # This to mask the password from displaying on the console.
864 mask_dict = self.env_dict.copy()
865 for k, v in mask_dict.items():
866 if k.lower().find("password") != -1:
867 hidden_text = []
868 hidden_text.append(v)
869 password_regex = '(' +\
870 '|'.join([re.escape(x) for x in hidden_text]) + ')'
871 mask_dict[k] = re.sub(password_regex, "********", v)
872
873 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))
George Keishingb97a9042021-07-29 07:41:20 -0500874
875 def execute_python_eval(self, eval_string):
876 r"""
877 Execute qualified python function using eval.
878
879 Description of argument(s):
880 eval_string Execute the python object.
881
882 Example:
883 eval(plugin.foo_func.foo_func(10))
884 """
885 try:
886 self.logger.info("\tCall func: %s" % eval_string)
887 result = eval(eval_string)
888 self.logger.info("\treturn: %s" % str(result))
889 except (ValueError, SyntaxError, NameError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -0500890 self.logger.error("\tERROR: execute_python_eval: %s" % e)
891 # Set the plugin error state.
892 plugin_error_dict['exit_on_error'] = True
George Keishingb97a9042021-07-29 07:41:20 -0500893 pass
894
895 return result
896
897 def execute_plugin_block(self, plugin_cmd_list):
898 r"""
899 Pack the plugin command to quailifed python string object.
900
901 Description of argument(s):
902 plugin_list_dict Plugin block read from YAML
903 [{'plugin_name': 'plugin.foo_func.my_func'},
904 {'plugin_args': [10]}]
905
906 Example:
907 - plugin:
908 - plugin_name: plugin.foo_func.my_func
909 - plugin_args:
910 - arg1
911 - arg2
912
913 - plugin:
914 - plugin_name: result = plugin.foo_func.my_func
915 - plugin_args:
916 - arg1
917 - arg2
918
919 - plugin:
920 - plugin_name: result1,result2 = plugin.foo_func.my_func
921 - plugin_args:
922 - arg1
923 - arg2
924 """
925 try:
926 plugin_name = plugin_cmd_list[0]['plugin_name']
927 # Equal separator means plugin function returns result.
928 if ' = ' in plugin_name:
929 # Ex. ['result', 'plugin.foo_func.my_func']
930 plugin_name_args = plugin_name.split(' = ')
931 # plugin func return data.
932 for arg in plugin_name_args:
933 if arg == plugin_name_args[-1]:
934 plugin_name = arg
935 else:
936 plugin_resp = arg.split(',')
937 # ['result1','result2']
938 for x in plugin_resp:
939 global_plugin_list.append(x)
940 global_plugin_dict[x] = ""
941
942 # Walk the plugin args ['arg1,'arg2']
943 # If the YAML plugin statement 'plugin_args' is not declared.
944 if any('plugin_args' in d for d in plugin_cmd_list):
945 plugin_args = plugin_cmd_list[1]['plugin_args']
946 if plugin_args:
947 plugin_args = self.yaml_args_populate(plugin_args)
948 else:
949 plugin_args = []
950 else:
951 plugin_args = self.yaml_args_populate([])
952
953 # Pack the args arg1, arg2, .... argn into
954 # "arg1","arg2","argn" string as params for function.
955 parm_args_str = self.yaml_args_string(plugin_args)
956 if parm_args_str:
957 plugin_func = plugin_name + '(' + parm_args_str + ')'
958 else:
959 plugin_func = plugin_name + '()'
960
961 # Execute plugin function.
962 if global_plugin_dict:
963 resp = self.execute_python_eval(plugin_func)
964 self.response_args_data(resp)
965 else:
George Keishingcaa97e62021-08-03 14:00:09 -0500966 resp = self.execute_python_eval(plugin_func)
967 return resp
George Keishingb97a9042021-07-29 07:41:20 -0500968 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -0500969 # Set the plugin error state.
970 plugin_error_dict['exit_on_error'] = True
971 self.logger.error("\tERROR: execute_plugin_block: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -0500972 pass
973
974 def response_args_data(self, plugin_resp):
975 r"""
976 Parse the plugin function response.
977
978 plugin_resp Response data from plugin function.
979 """
980 resp_list = []
George Keishing5765f792021-08-02 13:08:53 -0500981 resp_data = ""
George Keishingb97a9042021-07-29 07:41:20 -0500982 # There is nothing to update the plugin response.
983 if len(global_plugin_list) == 0 or plugin_resp == 'None':
984 return
985
George Keishing5765f792021-08-02 13:08:53 -0500986 if isinstance(plugin_resp, str):
987 resp_data = plugin_resp.strip('\r\n\t')
988 resp_list.append(resp_data)
989 elif isinstance(plugin_resp, bytes):
990 resp_data = str(plugin_resp, 'UTF-8').strip('\r\n\t')
991 resp_list.append(resp_data)
992 elif isinstance(plugin_resp, tuple):
993 if len(global_plugin_list) == 1:
George Keishingb97a9042021-07-29 07:41:20 -0500994 resp_list.append(plugin_resp)
George Keishing5765f792021-08-02 13:08:53 -0500995 else:
996 resp_list = list(plugin_resp)
997 resp_list = [x.strip('\r\n\t') for x in resp_list]
George Keishingb97a9042021-07-29 07:41:20 -0500998 elif isinstance(plugin_resp, list):
George Keishing5765f792021-08-02 13:08:53 -0500999 if len(global_plugin_list) == 1:
1000 resp_list.append([x.strip('\r\n\t') for x in plugin_resp])
1001 else:
1002 resp_list = [x.strip('\r\n\t') for x in plugin_resp]
1003 elif isinstance(plugin_resp, int) or isinstance(plugin_resp, float):
1004 resp_list.append(plugin_resp)
George Keishingb97a9042021-07-29 07:41:20 -05001005
1006 for idx, item in enumerate(resp_list, start=0):
1007 # Exit loop
1008 if idx >= len(global_plugin_list):
1009 break
1010 # Find the index of the return func in the list and
1011 # update the global func return dictionary.
1012 try:
1013 dict_idx = global_plugin_list[idx]
1014 global_plugin_dict[dict_idx] = item
1015 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001016 self.logger.warn("\tWARN: response_args_data: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001017 pass
1018
1019 # Done updating plugin dict irrespective of pass or failed,
1020 # clear all the list element.
1021 global_plugin_list.clear()
1022
1023 def yaml_args_string(self, plugin_args):
1024 r"""
1025 Pack the args into string.
1026
1027 plugin_args arg list ['arg1','arg2,'argn']
1028 """
1029 args_str = ''
1030 for args in plugin_args:
1031 if args:
George Keishing0581cb02021-08-05 15:08:58 -05001032 if isinstance(args, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001033 args_str += str(args)
George Keishing0581cb02021-08-05 15:08:58 -05001034 elif args in global_plugin_type_list:
1035 args_str += str(global_plugin_dict[args])
George Keishingb97a9042021-07-29 07:41:20 -05001036 else:
1037 args_str += '"' + str(args.strip('\r\n\t')) + '"'
1038 # Skip last list element.
1039 if args != plugin_args[-1]:
1040 args_str += ","
1041 return args_str
1042
1043 def yaml_args_populate(self, yaml_arg_list):
1044 r"""
1045 Decode ${MY_VAR} and load env data when read from YAML.
1046
1047 Description of argument(s):
1048 yaml_arg_list arg list read from YAML
1049
1050 Example:
1051 - plugin_args:
1052 - arg1
1053 - arg2
1054
1055 yaml_arg_list: [arg2, arg2]
1056 """
1057 # Get the env loaded keys as list ['hostname', 'username', 'password'].
1058 env_vars_list = list(self.env_dict)
1059
1060 if isinstance(yaml_arg_list, list):
1061 tmp_list = []
1062 for arg in yaml_arg_list:
George Keishing0581cb02021-08-05 15:08:58 -05001063 if isinstance(arg, (int, float)):
George Keishingb97a9042021-07-29 07:41:20 -05001064 tmp_list.append(arg)
1065 continue
1066 elif isinstance(arg, str):
1067 arg_str = self.yaml_env_and_plugin_vars_populate(str(arg))
1068 tmp_list.append(arg_str)
1069 else:
1070 tmp_list.append(arg)
1071
1072 # return populated list.
1073 return tmp_list
1074
1075 def yaml_env_and_plugin_vars_populate(self, yaml_arg_str):
1076 r"""
1077 Update ${MY_VAR} and my_plugin_vars
1078
1079 Description of argument(s):
1080 yaml_arg_str arg string read from YAML
1081
1082 Example:
1083 - cat ${MY_VAR}
1084 - ls -AX my_plugin_var
1085 """
1086 # Parse the string for env vars.
1087 try:
1088 # Example, list of matching env vars ['username', 'password', 'hostname']
1089 # Extra escape \ for special symbols. '\$\{([^\}]+)\}' works good.
1090 var_name_regex = '\\$\\{([^\\}]+)\\}'
1091 env_var_names_list = re.findall(var_name_regex, yaml_arg_str)
1092 for var in env_var_names_list:
1093 env_var = os.environ[var]
1094 env_replace = '${' + var + '}'
1095 yaml_arg_str = yaml_arg_str.replace(env_replace, env_var)
1096 except Exception as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001097 self.logger.error("\tERROR:yaml_env_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001098 pass
1099
1100 # Parse the string for plugin vars.
1101 try:
1102 # Example, list of plugin vars ['my_username', 'my_data']
1103 plugin_var_name_list = global_plugin_dict.keys()
1104 for var in plugin_var_name_list:
George Keishing0581cb02021-08-05 15:08:58 -05001105 # skip env var list already populated above block list.
1106 if var in env_var_names_list:
1107 continue
George Keishingb97a9042021-07-29 07:41:20 -05001108 # If this plugin var exist but empty value in dict, don't replace.
George Keishing0581cb02021-08-05 15:08:58 -05001109 # This is either a YAML plugin statement incorrectly used or
George Keishingb97a9042021-07-29 07:41:20 -05001110 # user added a plugin var which is not populated.
George Keishing0581cb02021-08-05 15:08:58 -05001111 if yaml_arg_str in global_plugin_dict:
1112 if isinstance(global_plugin_dict[var], (list, dict)):
1113 # List data type or dict can't be replaced, use directly
1114 # in eval function call.
1115 global_plugin_type_list.append(var)
1116 else:
1117 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
1118 # Just a string like filename or command.
1119 else:
George Keishingb97a9042021-07-29 07:41:20 -05001120 yaml_arg_str = yaml_arg_str.replace(str(var), str(global_plugin_dict[var]))
1121 except (IndexError, ValueError) as e:
George Keishing1e7b0182021-08-06 14:05:54 -05001122 self.logger.error("\tERROR: yaml_plugin_vars_populate: %s" % e)
George Keishingb97a9042021-07-29 07:41:20 -05001123 pass
1124
1125 return yaml_arg_str
George Keishing1e7b0182021-08-06 14:05:54 -05001126
1127 def plugin_error_check(self, plugin_dict):
1128 r"""
1129 Plugin error dict processing.
1130
1131 Description of argument(s):
1132 plugin_dict Dictionary of plugin error.
1133 """
1134 if any('plugin_error' in d for d in plugin_dict):
1135 for d in plugin_dict:
1136 if 'plugin_error' in d:
1137 value = d['plugin_error']
1138 # Reference if the error is set or not by plugin.
1139 return plugin_error_dict[value]