blob: b23776cc2a2d01e7722ad43b78767e35f574de09 [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
20
21class FFDCCollector:
22
23 r"""
24 Sends commands from configuration file to the targeted system to collect log files.
25 Fetch and store generated files at the specified location.
26
27 """
28
Peter D Phan0c669772021-06-24 13:52:42 -050029 def __init__(self,
30 hostname,
31 username,
32 password,
33 ffdc_config,
34 location,
35 remote_type,
Peter D Phane86d9a52021-07-15 10:42:25 -050036 remote_protocol,
George Keishing4885b2f2021-07-21 15:22:45 -050037 env_vars,
George Keishing8e94f8c2021-07-23 15:06:32 -050038 econfig,
Peter D Phane86d9a52021-07-15 10:42:25 -050039 log_level):
Peter D Phan72ce6b82021-06-03 06:18:26 -050040 r"""
41 Description of argument(s):
42
George Keishing8e94f8c2021-07-23 15:06:32 -050043 hostname name/ip of the targeted (remote) system
44 username user on the targeted system with access to FFDC files
45 password password for user on targeted system
46 ffdc_config configuration file listing commands and files for FFDC
47 location where to store collected FFDC
48 remote_type os type of the remote host
49 remote_protocol Protocol to use to collect data
50 env_vars User define CLI env vars '{"key : "value"}'
51 econfig User define env vars YAML file
Peter D Phan72ce6b82021-06-03 06:18:26 -050052
53 """
Peter D Phane86d9a52021-07-15 10:42:25 -050054
55 self.hostname = hostname
56 self.username = username
57 self.password = password
58 self.ffdc_config = ffdc_config
59 self.location = location + "/" + remote_type.upper()
60 self.ssh_remoteclient = None
61 self.telnet_remoteclient = None
62 self.ffdc_dir_path = ""
63 self.ffdc_prefix = ""
64 self.target_type = remote_type.upper()
65 self.remote_protocol = remote_protocol.upper()
George Keishinge1686752021-07-27 12:55:28 -050066 self.env_vars = env_vars
67 self.econfig = econfig
Peter D Phane86d9a52021-07-15 10:42:25 -050068 self.start_time = 0
69 self.elapsed_time = ''
70 self.logger = None
71
72 # Set prefix values for scp files and directory.
73 # Since the time stamp is at second granularity, these values are set here
74 # to be sure that all files for this run will have same timestamps
75 # and they will be saved in the same directory.
76 # self.location == local system for now
77 self.set_ffdc_defaults()
78
79 # Logger for this run. Need to be after set_ffdc_defaults()
80 self.script_logging(getattr(logging, log_level.upper()))
81
82 # Verify top level directory exists for storage
83 self.validate_local_store(self.location)
84
Peter D Phan72ce6b82021-06-03 06:18:26 -050085 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -050086 # Load default or user define YAML configuration file.
87 with open(self.ffdc_config, 'r') as file:
88 self.ffdc_actions = yaml.load(file, Loader=yaml.FullLoader)
89
90 if self.target_type not in self.ffdc_actions.keys():
91 self.logger.error(
92 "\n\tERROR: %s is not listed in %s.\n\n" % (self.target_type, self.ffdc_config))
93 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -050094 else:
Peter D Phan8462faf2021-06-16 12:24:15 -050095 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -050096
George Keishing4885b2f2021-07-21 15:22:45 -050097 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -050098 self.logger.info("\n\tENV: User define input YAML variables")
99 self.env_dict = {}
George Keishinge1686752021-07-27 12:55:28 -0500100 self. load_env()
George Keishingaa1f8482021-07-22 00:54:55 -0500101
Peter D Phan72ce6b82021-06-03 06:18:26 -0500102 def verify_script_env(self):
103
104 # Import to log version
105 import click
106 import paramiko
107
108 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500109
George Keishing506b0582021-07-27 09:31:22 -0500110 redfishtool_version = self.run_tool_cmd('redfishtool -V').split(' ')[2].strip('\n')
111 ipmitool_version = self.run_tool_cmd('ipmitool -V').split(' ')[2]
Peter D Phan0c669772021-06-24 13:52:42 -0500112
Peter D Phane86d9a52021-07-15 10:42:25 -0500113 self.logger.info("\n\t---- Script host environment ----")
114 self.logger.info("\t{:<10} {:<10}".format('Script hostname', os.uname()[1]))
115 self.logger.info("\t{:<10} {:<10}".format('Script host os', platform.platform()))
116 self.logger.info("\t{:<10} {:>10}".format('Python', platform.python_version()))
117 self.logger.info("\t{:<10} {:>10}".format('PyYAML', yaml.__version__))
118 self.logger.info("\t{:<10} {:>10}".format('click', click.__version__))
119 self.logger.info("\t{:<10} {:>10}".format('paramiko', paramiko.__version__))
120 self.logger.info("\t{:<10} {:>9}".format('redfishtool', redfishtool_version))
121 self.logger.info("\t{:<10} {:>12}".format('ipmitool', ipmitool_version))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500122
Peter D Phan8462faf2021-06-16 12:24:15 -0500123 if eval(yaml.__version__.replace('.', ',')) < (5, 4, 1):
Peter D Phane86d9a52021-07-15 10:42:25 -0500124 self.logger.error("\n\tERROR: Python or python packages do not meet minimum version requirement.")
125 self.logger.error("\tERROR: PyYAML version 5.4.1 or higher is needed.\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500126 run_env_ok = False
127
Peter D Phane86d9a52021-07-15 10:42:25 -0500128 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500129 return run_env_ok
130
Peter D Phane86d9a52021-07-15 10:42:25 -0500131 def script_logging(self,
132 log_level_attr):
133 r"""
134 Create logger
135
136 """
137 self.logger = logging.getLogger()
138 self.logger.setLevel(log_level_attr)
139 log_file_handler = logging.FileHandler(self.ffdc_dir_path + "collector.log")
140
141 stdout_handler = logging.StreamHandler(sys.stdout)
142 self.logger.addHandler(log_file_handler)
143 self.logger.addHandler(stdout_handler)
144
145 # Turn off paramiko INFO logging
146 logging.getLogger("paramiko").setLevel(logging.WARNING)
147
Peter D Phan72ce6b82021-06-03 06:18:26 -0500148 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500149 r"""
150 Check if target system is ping-able.
151
152 """
George Keishing0662e942021-07-13 05:12:20 -0500153 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500154 if response == 0:
Peter D Phane86d9a52021-07-15 10:42:25 -0500155 self.logger.info("\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500156 return True
157 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500158 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500159 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500160 sys.exit(-1)
161
Peter D Phan72ce6b82021-06-03 06:18:26 -0500162 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500163 r"""
164 Initiate FFDC Collection depending on requested protocol.
165
166 """
167
Peter D Phane86d9a52021-07-15 10:42:25 -0500168 self.logger.info("\n\t---- Start communicating with %s ----" % self.hostname)
Peter D Phan7610bc42021-07-06 06:31:05 -0500169 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500170
George Keishingf5a57502021-07-22 16:43:47 -0500171 # Find the list of target and protocol supported.
172 check_protocol_list = []
173 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500174
George Keishingf5a57502021-07-22 16:43:47 -0500175 for target_type in config_dict.keys():
176 if self.target_type != target_type:
177 continue
George Keishingeafba182021-06-29 13:44:58 -0500178
George Keishingf5a57502021-07-22 16:43:47 -0500179 for k, v in config_dict[target_type].items():
180 if config_dict[target_type][k]['PROTOCOL'][0] not in check_protocol_list:
181 check_protocol_list.append(config_dict[target_type][k]['PROTOCOL'][0])
Peter D Phanbff617a2021-07-22 08:41:35 -0500182
George Keishingf5a57502021-07-22 16:43:47 -0500183 self.logger.info("\n\t %s protocol type: %s" % (self.target_type, check_protocol_list))
Peter D Phanbff617a2021-07-22 08:41:35 -0500184
George Keishingf5a57502021-07-22 16:43:47 -0500185 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500186
George Keishingf5a57502021-07-22 16:43:47 -0500187 if verified_working_protocol:
Peter D Phane86d9a52021-07-15 10:42:25 -0500188 self.logger.info("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500189
George Keishingf5a57502021-07-22 16:43:47 -0500190 # Verify top level directory exists for storage
191 self.validate_local_store(self.location)
192
193 if ((self.remote_protocol not in verified_working_protocol) and (self.remote_protocol != 'ALL')):
194 self.logger.info("\n\tWorking protocol list: %s" % verified_working_protocol)
195 self.logger.error(
196 '\tERROR: Requested protocol %s is not in working protocol list.\n'
197 % self.remote_protocol)
198 sys.exit(-1)
199 else:
200 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500201
202 def ssh_to_target_system(self):
203 r"""
204 Open a ssh connection to targeted system.
205
206 """
207
Peter D Phan5963d632021-07-12 09:58:55 -0500208 self.ssh_remoteclient = SSHRemoteclient(self.hostname,
209 self.username,
210 self.password)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500211
Peter D Phan5963d632021-07-12 09:58:55 -0500212 if self.ssh_remoteclient.ssh_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500213 self.logger.info("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500214
Peter D Phan5963d632021-07-12 09:58:55 -0500215 # Check scp connection.
216 # If scp connection fails,
217 # continue with FFDC generation but skip scp files to local host.
218 self.ssh_remoteclient.scp_connection()
219 return True
220 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500221 self.logger.info("\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500222 return False
223
224 def telnet_to_target_system(self):
225 r"""
226 Open a telnet connection to targeted system.
227 """
228 self.telnet_remoteclient = TelnetRemoteclient(self.hostname,
229 self.username,
230 self.password)
231 if self.telnet_remoteclient.tn_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500232 self.logger.info("\n\t[Check] %s Telnet connection established.\t [OK]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500233 return True
234 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500235 self.logger.info("\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500236 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500237
George Keishing772c9772021-06-16 23:23:42 -0500238 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500239 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500240 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500241
Peter D Phan04aca3b2021-06-21 10:37:18 -0500242 Description of argument(s):
243 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500244 """
245
Peter D Phane86d9a52021-07-15 10:42:25 -0500246 self.logger.info("\n\t---- Executing commands on " + self.hostname + " ----")
247 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500248
George Keishingf5a57502021-07-22 16:43:47 -0500249 config_dict = self.ffdc_actions
250 for target_type in config_dict.keys():
251 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500252 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500253
Peter D Phane86d9a52021-07-15 10:42:25 -0500254 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
George Keishingf5a57502021-07-22 16:43:47 -0500255 self.logger.info("\tSystem Type: %s" % target_type)
256 for k, v in config_dict[target_type].items():
Peter D Phan72ce6b82021-06-03 06:18:26 -0500257
George Keishingf5a57502021-07-22 16:43:47 -0500258 if self.remote_protocol not in working_protocol_list \
George Keishing6ea92b02021-07-01 11:20:50 -0500259 and self.remote_protocol != 'ALL':
260 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500261
George Keishingf5a57502021-07-22 16:43:47 -0500262 protocol = config_dict[target_type][k]['PROTOCOL'][0]
263
264 if protocol not in working_protocol_list:
265 continue
266
George Keishingb7607612021-07-27 13:31:23 -0500267 if protocol in working_protocol_list:
268 if protocol == 'SSH' or protocol == 'SCP':
George Keishingf5a57502021-07-22 16:43:47 -0500269 self.protocol_ssh(target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500270 elif protocol == 'TELNET':
George Keishingf5a57502021-07-22 16:43:47 -0500271 self.protocol_telnet(target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500272 elif protocol == 'REDFISH' or protocol == 'IPMI' or protocol == 'SHELL':
George Keishing506b0582021-07-27 09:31:22 -0500273 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500274 else:
275 self.logger.error("\n\tERROR: %s is not available for %s." % (protocol, self.hostname))
George Keishingeafba182021-06-29 13:44:58 -0500276
Peter D Phan04aca3b2021-06-21 10:37:18 -0500277 # Close network connection after collecting all files
Peter D Phan7610bc42021-07-06 06:31:05 -0500278 self.elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - self.start_time))
Peter D Phanbff617a2021-07-22 08:41:35 -0500279 if self.ssh_remoteclient:
280 self.ssh_remoteclient.ssh_remoteclient_disconnect()
281 if self.telnet_remoteclient:
282 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500283
Peter D Phan0c669772021-06-24 13:52:42 -0500284 def protocol_ssh(self,
George Keishingf5a57502021-07-22 16:43:47 -0500285 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500286 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500287 r"""
288 Perform actions using SSH and SCP protocols.
289
290 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500291 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500292 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500293 """
294
George Keishing6ea92b02021-07-01 11:20:50 -0500295 if sub_type == 'DUMP_LOGS':
George Keishingf5a57502021-07-22 16:43:47 -0500296 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500297 else:
George Keishingf5a57502021-07-22 16:43:47 -0500298 self.collect_and_copy_ffdc(self.ffdc_actions[target_type][sub_type])
Peter D Phan0c669772021-06-24 13:52:42 -0500299
Peter D Phan5963d632021-07-12 09:58:55 -0500300 def protocol_telnet(self,
George Keishingf5a57502021-07-22 16:43:47 -0500301 target_type,
Peter D Phan5963d632021-07-12 09:58:55 -0500302 sub_type):
303 r"""
304 Perform actions using telnet protocol.
305 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500306 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500307 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500308 self.logger.info("\n\t[Run] Executing commands on %s using %s" % (self.hostname, 'TELNET'))
Peter D Phan5963d632021-07-12 09:58:55 -0500309 telnet_files_saved = []
310 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500311 list_of_commands = self.ffdc_actions[target_type][sub_type]['COMMANDS']
Peter D Phan5963d632021-07-12 09:58:55 -0500312 for index, each_cmd in enumerate(list_of_commands, start=0):
313 command_txt, command_timeout = self.unpack_command(each_cmd)
314 result = self.telnet_remoteclient.execute_command(command_txt, command_timeout)
315 if result:
316 try:
George Keishingf5a57502021-07-22 16:43:47 -0500317 targ_file = self.ffdc_actions[target_type][sub_type]['FILES'][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500318 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500319 targ_file = command_txt
320 self.logger.warning(
321 "\n\t[WARN] Missing filename to store data from telnet %s." % each_cmd)
322 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan5963d632021-07-12 09:58:55 -0500323 targ_file_with_path = (self.ffdc_dir_path
324 + self.ffdc_prefix
325 + targ_file)
326 # Creates a new file
327 with open(targ_file_with_path, 'wb') as fp:
328 fp.write(result)
329 fp.close
330 telnet_files_saved.append(targ_file)
331 progress_counter += 1
332 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500333 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500334 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500335 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500336
George Keishing506b0582021-07-27 09:31:22 -0500337 def protocol_execute(self,
338 protocol,
George Keishingf5a57502021-07-22 16:43:47 -0500339 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500340 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500341 r"""
George Keishing506b0582021-07-27 09:31:22 -0500342 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500343
344 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500345 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500346 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500347 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500348 """
349
George Keishing506b0582021-07-27 09:31:22 -0500350 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, protocol))
351 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500352 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500353 list_of_cmd = self.get_command_list(self.ffdc_actions[target_type][sub_type])
George Keishingeafba182021-06-29 13:44:58 -0500354 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishing506b0582021-07-27 09:31:22 -0500355 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500356 if result:
357 try:
George Keishingf5a57502021-07-22 16:43:47 -0500358 targ_file = self.get_file_list(self.ffdc_actions[target_type][sub_type])[index]
George Keishingeafba182021-06-29 13:44:58 -0500359 except IndexError:
George Keishing6ea92b02021-07-01 11:20:50 -0500360 targ_file = each_cmd.split('/')[-1]
George Keishing506b0582021-07-27 09:31:22 -0500361 self.logger.warning(
362 "\n\t[WARN] Missing filename to store data from %s." % each_cmd)
Peter D Phane86d9a52021-07-15 10:42:25 -0500363 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500364
365 targ_file_with_path = (self.ffdc_dir_path
366 + self.ffdc_prefix
367 + targ_file)
368
369 # Creates a new file
370 with open(targ_file_with_path, 'w') as fp:
371 fp.write(result)
372 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500373 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500374
375 progress_counter += 1
376 self.print_progress(progress_counter)
377
Peter D Phane86d9a52021-07-15 10:42:25 -0500378 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500379
George Keishing506b0582021-07-27 09:31:22 -0500380 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500381 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500382
Peter D Phan04aca3b2021-06-21 10:37:18 -0500383 def collect_and_copy_ffdc(self,
George Keishingf5a57502021-07-22 16:43:47 -0500384 ffdc_actions_for_target_type,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500385 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500386 r"""
387 Send commands in ffdc_config file to targeted system.
388
389 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500390 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500391 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500392 """
393
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500394 # Executing commands, if any
George Keishingf5a57502021-07-22 16:43:47 -0500395 self.ssh_execute_ffdc_commands(ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500396 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500397
Peter D Phan3beb02e2021-07-06 13:25:17 -0500398 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500399 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500400 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500401
Peter D Phan04aca3b2021-06-21 10:37:18 -0500402 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500403 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500404 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500405 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500406 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500407
Peter D Phanbabf2962021-07-07 11:24:40 -0500408 def get_command_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500409 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500410 r"""
411 Fetch list of commands from configuration file
412
413 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500414 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500415 """
416 try:
George Keishingf5a57502021-07-22 16:43:47 -0500417 list_of_commands = ffdc_actions_for_target_type['COMMANDS']
Peter D Phanbabf2962021-07-07 11:24:40 -0500418 except KeyError:
419 list_of_commands = []
420 return list_of_commands
421
422 def get_file_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500423 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500424 r"""
425 Fetch list of commands from configuration file
426
427 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500428 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500429 """
430 try:
George Keishingf5a57502021-07-22 16:43:47 -0500431 list_of_files = ffdc_actions_for_target_type['FILES']
Peter D Phanbabf2962021-07-07 11:24:40 -0500432 except KeyError:
433 list_of_files = []
434 return list_of_files
435
Peter D Phan5963d632021-07-12 09:58:55 -0500436 def unpack_command(self,
437 command):
438 r"""
439 Unpack command from config file
440
441 Description of argument(s):
442 command Command from config file.
443 """
444 if isinstance(command, dict):
445 command_txt = next(iter(command))
446 command_timeout = next(iter(command.values()))
447 elif isinstance(command, str):
448 command_txt = command
449 # Default command timeout 60 seconds
450 command_timeout = 60
451
452 return command_txt, command_timeout
453
Peter D Phan3beb02e2021-07-06 13:25:17 -0500454 def ssh_execute_ffdc_commands(self,
George Keishingf5a57502021-07-22 16:43:47 -0500455 ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500456 form_filename=False):
457 r"""
458 Send commands in ffdc_config file to targeted system.
459
460 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500461 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500462 form_filename if true, pre-pend self.target_type to filename
463 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500464 self.logger.info("\n\t[Run] Executing commands on %s using %s"
George Keishingf5a57502021-07-22 16:43:47 -0500465 % (self.hostname, ffdc_actions_for_target_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500466
George Keishingf5a57502021-07-22 16:43:47 -0500467 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500468 # If command list is empty, returns
469 if not list_of_commands:
470 return
471
472 progress_counter = 0
473 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500474 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500475
476 if form_filename:
477 command_txt = str(command_txt % self.target_type)
478
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500479 cmd_exit_code, err, response = \
480 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
481
482 if cmd_exit_code:
483 self.logger.warning(
484 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
485 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500486
Peter D Phan3beb02e2021-07-06 13:25:17 -0500487 progress_counter += 1
488 self.print_progress(progress_counter)
489
Peter D Phane86d9a52021-07-15 10:42:25 -0500490 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500491
Peter D Phan56429a62021-06-23 08:38:29 -0500492 def group_copy(self,
George Keishingf5a57502021-07-22 16:43:47 -0500493 ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500494 r"""
495 scp group of files (wild card) from remote host.
496
497 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500498 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500499 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500500
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\tCopying DUMP files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500503
George Keishingf5a57502021-07-22 16:43:47 -0500504 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phanbabf2962021-07-07 11:24:40 -0500505 # If command list is empty, returns
506 if not list_of_commands:
507 return
Peter D Phan56429a62021-06-23 08:38:29 -0500508
Peter D Phanbabf2962021-07-07 11:24:40 -0500509 for command in list_of_commands:
510 try:
511 filename = command.split(' ')[2]
512 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500513 self.logger.info("\t\tInvalid command %s for DUMP_LOGS block." % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500514 continue
515
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500516 cmd_exit_code, err, response = \
517 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500518
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500519 # If file does not exist, code take no action.
520 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500521 if response:
Peter D Phan5963d632021-07-12 09:58:55 -0500522 scp_result = self.ssh_remoteclient.scp_file_from_remote(filename, self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500523 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500524 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500525 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500526 self.logger.info("\t\tThere is no " + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500527
528 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500529 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500530
Peter D Phan72ce6b82021-06-03 06:18:26 -0500531 def scp_ffdc(self,
532 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500533 targ_file_prefix,
534 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500535 file_list=None,
536 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500537 r"""
538 SCP all files in file_dict to the indicated directory on the local system.
539
540 Description of argument(s):
541 targ_dir_path The path of the directory to receive the files.
542 targ_file_prefix Prefix which will be pre-pended to each
543 target file's name.
544 file_dict A dictionary of files to scp from targeted system to this system
545
546 """
547
Peter D Phan72ce6b82021-06-03 06:18:26 -0500548 progress_counter = 0
549 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500550 if form_filename:
551 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500552 source_file_path = filename
553 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
554
Peter D Phanbabf2962021-07-07 11:24:40 -0500555 # If source file name contains wild card, copy filename as is.
556 if '*' in source_file_path:
Peter D Phan5963d632021-07-12 09:58:55 -0500557 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500558 else:
Peter D Phan5963d632021-07-12 09:58:55 -0500559 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500560
561 if not quiet:
562 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500563 self.logger.info(
564 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500565 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500566 self.logger.info(
567 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500568 else:
569 progress_counter += 1
570 self.print_progress(progress_counter)
571
Peter D Phan72ce6b82021-06-03 06:18:26 -0500572 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500573 r"""
574 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
575 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
576 Individual ffdc file will have timestr_filename.
577
578 Description of class variables:
579 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
580
581 self.ffdc_prefix The prefix to be given to each ffdc file name.
582
583 """
584
585 timestr = time.strftime("%Y%m%d-%H%M%S")
586 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
587 self.ffdc_prefix = timestr + "_"
588 self.validate_local_store(self.ffdc_dir_path)
589
590 def validate_local_store(self, dir_path):
591 r"""
592 Ensure path exists to store FFDC files locally.
593
594 Description of variable:
595 dir_path The dir path where collected ffdc data files will be stored.
596
597 """
598
599 if not os.path.exists(dir_path):
600 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500601 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500602 except (IOError, OSError) as e:
603 # PermissionError
604 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500605 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500606 '\tERROR: os.makedirs %s failed with PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500607 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500608 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500609 '\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500610 sys.exit(-1)
611
612 def print_progress(self, progress):
613 r"""
614 Print activity progress +
615
616 Description of variable:
617 progress Progress counter.
618
619 """
620
621 sys.stdout.write("\r\t" + "+" * progress)
622 sys.stdout.flush()
623 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500624
625 def verify_redfish(self):
626 r"""
627 Verify remote host has redfish service active
628
629 """
George Keishing506b0582021-07-27 09:31:22 -0500630 redfish_parm = 'redfishtool -r ' \
Peter D Phan0c669772021-06-24 13:52:42 -0500631 + self.hostname + ' -S Always raw GET /redfish/v1/'
George Keishing506b0582021-07-27 09:31:22 -0500632 return(self.run_tool_cmd(redfish_parm, True))
Peter D Phan0c669772021-06-24 13:52:42 -0500633
George Keishingeafba182021-06-29 13:44:58 -0500634 def verify_ipmi(self):
635 r"""
636 Verify remote host has IPMI LAN service active
637
638 """
George Keishing484f8242021-07-27 01:42:02 -0500639 if self.target_type == 'OPENBMC':
640 ipmi_parm = 'ipmitool -I lanplus -C 17 -U ' + self.username + ' -P ' \
641 + self.password + ' -H ' + self.hostname + ' power status'
642 else:
643 ipmi_parm = 'ipmitool -I lanplus -P ' \
644 + self.password + ' -H ' + self.hostname + ' power status'
645
George Keishing506b0582021-07-27 09:31:22 -0500646 return(self.run_tool_cmd(ipmi_parm, True))
George Keishingeafba182021-06-29 13:44:58 -0500647
George Keishing506b0582021-07-27 09:31:22 -0500648 def run_tool_cmd(self,
George Keishingeafba182021-06-29 13:44:58 -0500649 parms_string,
650 quiet=False):
651 r"""
George Keishing506b0582021-07-27 09:31:22 -0500652 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500653
654 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500655 parms_string tool command options.
656 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500657 """
658
George Keishing484f8242021-07-27 01:42:02 -0500659 result = subprocess.run([parms_string],
George Keishingeafba182021-06-29 13:44:58 -0500660 stdout=subprocess.PIPE,
661 stderr=subprocess.PIPE,
662 shell=True,
663 universal_newlines=True)
664
665 if result.stderr and not quiet:
George Keishing484f8242021-07-27 01:42:02 -0500666 self.logger.error('\n\t\tERROR with %s ' % parms_string)
Peter D Phane86d9a52021-07-15 10:42:25 -0500667 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500668
669 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500670
George Keishingf5a57502021-07-22 16:43:47 -0500671 def verify_protocol(self, protocol_list):
672 r"""
673 Perform protocol working check.
674
675 Description of argument(s):
676 protocol_list List of protocol.
677 """
678
679 tmp_list = []
680 if self.target_is_pingable():
681 tmp_list.append("SHELL")
682
683 for protocol in protocol_list:
684 if self.remote_protocol != 'ALL':
685 if self.remote_protocol != protocol:
686 continue
687
688 # Only check SSH/SCP once for both protocols
689 if protocol == 'SSH' or protocol == 'SCP' and protocol not in tmp_list:
690 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -0500691 # Add only what user asked.
692 if self.remote_protocol != 'ALL':
693 tmp_list.append(self.remote_protocol)
694 else:
695 tmp_list.append('SSH')
696 tmp_list.append('SCP')
George Keishingf5a57502021-07-22 16:43:47 -0500697
698 if protocol == 'TELNET':
699 if self.telnet_to_target_system():
700 tmp_list.append(protocol)
701
702 if protocol == 'REDFISH':
703 if self.verify_redfish():
704 tmp_list.append(protocol)
705 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
706 else:
707 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
708
709 if protocol == 'IPMI':
710 if self.verify_ipmi():
711 tmp_list.append(protocol)
712 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
713 else:
714 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
715
716 return tmp_list
George Keishinge1686752021-07-27 12:55:28 -0500717
718 def load_env(self):
719 r"""
720 Perform protocol working check.
721
722 """
723 # This is for the env vars a user can use in YAML to load it at runtime.
724 # Example YAML:
725 # -COMMANDS:
726 # - my_command ${hostname} ${username} ${password}
727 os.environ['hostname'] = self.hostname
728 os.environ['username'] = self.username
729 os.environ['password'] = self.password
730
731 # Append default Env.
732 self.env_dict['hostname'] = self.hostname
733 self.env_dict['username'] = self.username
734 self.env_dict['password'] = self.password
735
736 try:
737 tmp_env_dict = {}
738 if self.env_vars:
739 tmp_env_dict = json.loads(self.env_vars)
740 # Export ENV vars default.
741 for key, value in tmp_env_dict.items():
742 os.environ[key] = value
743 self.env_dict[key] = str(value)
744
745 if self.econfig:
746 with open(self.econfig, 'r') as file:
747 tmp_env_dict = yaml.load(file, Loader=yaml.FullLoader)
748 # Export ENV vars.
749 for key, value in tmp_env_dict['env_params'].items():
750 os.environ[key] = str(value)
751 self.env_dict[key] = str(value)
752 except json.decoder.JSONDecodeError as e:
753 self.logger.error("\n\tERROR: %s " % e)
754 sys.exit(-1)
755
756 # This to mask the password from displaying on the console.
757 mask_dict = self.env_dict.copy()
758 for k, v in mask_dict.items():
759 if k.lower().find("password") != -1:
760 hidden_text = []
761 hidden_text.append(v)
762 password_regex = '(' +\
763 '|'.join([re.escape(x) for x in hidden_text]) + ')'
764 mask_dict[k] = re.sub(password_regex, "********", v)
765
766 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=False))