blob: 4e11529b7a09ce10fc8884af2d1d942574dcb9df [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
8import sys
9import yaml
George Keishing4885b2f2021-07-21 15:22:45 -050010import json
Peter D Phan72ce6b82021-06-03 06:18:26 -050011import time
Peter D Phane86d9a52021-07-15 10:42:25 -050012import logging
Peter D Phan72ce6b82021-06-03 06:18:26 -050013import platform
14from errno import EACCES, EPERM
Peter D Phan0c669772021-06-24 13:52:42 -050015import subprocess
Peter D Phan72ce6b82021-06-03 06:18:26 -050016from ssh_utility import SSHRemoteclient
Peter D Phan5963d632021-07-12 09:58:55 -050017from telnet_utility import TelnetRemoteclient
Peter D Phan72ce6b82021-06-03 06:18:26 -050018
19
20class FFDCCollector:
21
22 r"""
23 Sends commands from configuration file to the targeted system to collect log files.
24 Fetch and store generated files at the specified location.
25
26 """
27
Peter D Phan0c669772021-06-24 13:52:42 -050028 def __init__(self,
29 hostname,
30 username,
31 password,
32 ffdc_config,
33 location,
34 remote_type,
Peter D Phane86d9a52021-07-15 10:42:25 -050035 remote_protocol,
George Keishing4885b2f2021-07-21 15:22:45 -050036 env_vars,
Peter D Phane86d9a52021-07-15 10:42:25 -050037 log_level):
Peter D Phan72ce6b82021-06-03 06:18:26 -050038 r"""
39 Description of argument(s):
40
41 hostname name/ip of the targeted (remote) system
42 username user on the targeted system with access to FFDC files
43 password password for user on targeted system
44 ffdc_config configuration file listing commands and files for FFDC
Peter D Phan04aca3b2021-06-21 10:37:18 -050045 location where to store collected FFDC
46 remote_type os type of the remote host
Peter D Phan72ce6b82021-06-03 06:18:26 -050047
48 """
Peter D Phane86d9a52021-07-15 10:42:25 -050049
50 self.hostname = hostname
51 self.username = username
52 self.password = password
George Keishing04d29102021-07-16 02:05:57 -050053 # This is for the env vars a user can use in YAML to load it at runtime.
54 # Example YAML:
55 # -COMMANDS:
56 # - my_command ${hostname} ${username} ${password}
57 os.environ['hostname'] = hostname
58 os.environ['username'] = username
59 os.environ['password'] = password
60
Peter D Phane86d9a52021-07-15 10:42:25 -050061 self.ffdc_config = ffdc_config
62 self.location = location + "/" + remote_type.upper()
63 self.ssh_remoteclient = None
64 self.telnet_remoteclient = None
65 self.ffdc_dir_path = ""
66 self.ffdc_prefix = ""
67 self.target_type = remote_type.upper()
68 self.remote_protocol = remote_protocol.upper()
69 self.start_time = 0
70 self.elapsed_time = ''
71 self.logger = None
72
73 # Set prefix values for scp files and directory.
74 # Since the time stamp is at second granularity, these values are set here
75 # to be sure that all files for this run will have same timestamps
76 # and they will be saved in the same directory.
77 # self.location == local system for now
78 self.set_ffdc_defaults()
79
80 # Logger for this run. Need to be after set_ffdc_defaults()
81 self.script_logging(getattr(logging, log_level.upper()))
82
83 # Verify top level directory exists for storage
84 self.validate_local_store(self.location)
85
Peter D Phan72ce6b82021-06-03 06:18:26 -050086 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -050087 # Load default or user define YAML configuration file.
88 with open(self.ffdc_config, 'r') as file:
89 self.ffdc_actions = yaml.load(file, Loader=yaml.FullLoader)
90
91 if self.target_type not in self.ffdc_actions.keys():
92 self.logger.error(
93 "\n\tERROR: %s is not listed in %s.\n\n" % (self.target_type, self.ffdc_config))
94 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -050095 else:
Peter D Phan8462faf2021-06-16 12:24:15 -050096 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -050097
George Keishing4885b2f2021-07-21 15:22:45 -050098 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -050099 self.logger.info("\n\tENV: User define input YAML variables")
100 self.env_dict = {}
101
George Keishing4885b2f2021-07-21 15:22:45 -0500102 try:
103 if env_vars:
George Keishingaa1f8482021-07-22 00:54:55 -0500104 self.env_dict = json.loads(env_vars)
George Keishing4885b2f2021-07-21 15:22:45 -0500105
106 # Export ENV vars default.
George Keishingaa1f8482021-07-22 00:54:55 -0500107 for key, value in self.env_dict.items():
George Keishing4885b2f2021-07-21 15:22:45 -0500108 os.environ[key] = value
George Keishingaa1f8482021-07-22 00:54:55 -0500109
George Keishing4885b2f2021-07-21 15:22:45 -0500110 except json.decoder.JSONDecodeError as e:
111 self.logger.error("\n\tERROR: %s " % e)
112 sys.exit(-1)
113
George Keishingaa1f8482021-07-22 00:54:55 -0500114 # Append default Env.
115 self.env_dict['hostname'] = self.hostname
116 self.env_dict['username'] = self.username
117 self.env_dict['password'] = self.password
118 self.logger.info(json.dumps(self.env_dict, indent=8, sort_keys=True))
119
Peter D Phan72ce6b82021-06-03 06:18:26 -0500120 def verify_script_env(self):
121
122 # Import to log version
123 import click
124 import paramiko
125
126 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500127
George Keishingeafba182021-06-29 13:44:58 -0500128 redfishtool_version = self.run_redfishtool('-V').split(' ')[2].strip('\n')
129 ipmitool_version = self.run_ipmitool('-V').split(' ')[2]
Peter D Phan0c669772021-06-24 13:52:42 -0500130
Peter D Phane86d9a52021-07-15 10:42:25 -0500131 self.logger.info("\n\t---- Script host environment ----")
132 self.logger.info("\t{:<10} {:<10}".format('Script hostname', os.uname()[1]))
133 self.logger.info("\t{:<10} {:<10}".format('Script host os', platform.platform()))
134 self.logger.info("\t{:<10} {:>10}".format('Python', platform.python_version()))
135 self.logger.info("\t{:<10} {:>10}".format('PyYAML', yaml.__version__))
136 self.logger.info("\t{:<10} {:>10}".format('click', click.__version__))
137 self.logger.info("\t{:<10} {:>10}".format('paramiko', paramiko.__version__))
138 self.logger.info("\t{:<10} {:>9}".format('redfishtool', redfishtool_version))
139 self.logger.info("\t{:<10} {:>12}".format('ipmitool', ipmitool_version))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500140
Peter D Phan8462faf2021-06-16 12:24:15 -0500141 if eval(yaml.__version__.replace('.', ',')) < (5, 4, 1):
Peter D Phane86d9a52021-07-15 10:42:25 -0500142 self.logger.error("\n\tERROR: Python or python packages do not meet minimum version requirement.")
143 self.logger.error("\tERROR: PyYAML version 5.4.1 or higher is needed.\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500144 run_env_ok = False
145
Peter D Phane86d9a52021-07-15 10:42:25 -0500146 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500147 return run_env_ok
148
Peter D Phane86d9a52021-07-15 10:42:25 -0500149 def script_logging(self,
150 log_level_attr):
151 r"""
152 Create logger
153
154 """
155 self.logger = logging.getLogger()
156 self.logger.setLevel(log_level_attr)
157 log_file_handler = logging.FileHandler(self.ffdc_dir_path + "collector.log")
158
159 stdout_handler = logging.StreamHandler(sys.stdout)
160 self.logger.addHandler(log_file_handler)
161 self.logger.addHandler(stdout_handler)
162
163 # Turn off paramiko INFO logging
164 logging.getLogger("paramiko").setLevel(logging.WARNING)
165
Peter D Phan72ce6b82021-06-03 06:18:26 -0500166 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500167 r"""
168 Check if target system is ping-able.
169
170 """
George Keishing0662e942021-07-13 05:12:20 -0500171 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500172 if response == 0:
Peter D Phane86d9a52021-07-15 10:42:25 -0500173 self.logger.info("\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500174 return True
175 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500176 self.logger.error(
177 "\n>>>>>\tERROR: %s is not ping-able. FFDC collection aborted.\n" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500178 sys.exit(-1)
179
Peter D Phan72ce6b82021-06-03 06:18:26 -0500180 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500181 r"""
182 Initiate FFDC Collection depending on requested protocol.
183
184 """
185
Peter D Phane86d9a52021-07-15 10:42:25 -0500186 self.logger.info("\n\t---- Start communicating with %s ----" % self.hostname)
Peter D Phan7610bc42021-07-06 06:31:05 -0500187 self.start_time = time.time()
George Keishing772c9772021-06-16 23:23:42 -0500188 working_protocol_list = []
Peter D Phan72ce6b82021-06-03 06:18:26 -0500189 if self.target_is_pingable():
George Keishing04d29102021-07-16 02:05:57 -0500190 working_protocol_list.append("SHELL")
George Keishing772c9772021-06-16 23:23:42 -0500191 # Check supported protocol ping,ssh, redfish are working.
192 if self.ssh_to_target_system():
193 working_protocol_list.append("SSH")
George Keishing615fe322021-06-24 01:24:36 -0500194 working_protocol_list.append("SCP")
Peter D Phan0c669772021-06-24 13:52:42 -0500195
196 # Redfish
197 if self.verify_redfish():
198 working_protocol_list.append("REDFISH")
Peter D Phane86d9a52021-07-15 10:42:25 -0500199 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
Peter D Phan0c669772021-06-24 13:52:42 -0500200 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500201 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan0c669772021-06-24 13:52:42 -0500202
Peter D Phan5963d632021-07-12 09:58:55 -0500203 # IPMI
George Keishingeafba182021-06-29 13:44:58 -0500204 if self.verify_ipmi():
205 working_protocol_list.append("IPMI")
Peter D Phane86d9a52021-07-15 10:42:25 -0500206 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
George Keishingeafba182021-06-29 13:44:58 -0500207 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500208 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
George Keishingeafba182021-06-29 13:44:58 -0500209
Peter D Phan5963d632021-07-12 09:58:55 -0500210 # Telnet
211 if self.telnet_to_target_system():
212 working_protocol_list.append("TELNET")
213
Peter D Phan72ce6b82021-06-03 06:18:26 -0500214 # Verify top level directory exists for storage
215 self.validate_local_store(self.location)
Peter D Phane86d9a52021-07-15 10:42:25 -0500216 self.logger.info("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500217
218 if ((self.remote_protocol not in working_protocol_list) and (self.remote_protocol != 'ALL')):
Peter D Phane86d9a52021-07-15 10:42:25 -0500219 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
220 self.logger.error(
Peter D Phan0c669772021-06-24 13:52:42 -0500221 '>>>>>\tERROR: Requested protocol %s is not in working protocol list.\n'
222 % self.remote_protocol)
223 sys.exit(-1)
224 else:
225 self.generate_ffdc(working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500226
227 def ssh_to_target_system(self):
228 r"""
229 Open a ssh connection to targeted system.
230
231 """
232
Peter D Phan5963d632021-07-12 09:58:55 -0500233 self.ssh_remoteclient = SSHRemoteclient(self.hostname,
234 self.username,
235 self.password)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500236
Peter D Phan5963d632021-07-12 09:58:55 -0500237 if self.ssh_remoteclient.ssh_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500238 self.logger.info("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500239
Peter D Phan5963d632021-07-12 09:58:55 -0500240 # Check scp connection.
241 # If scp connection fails,
242 # continue with FFDC generation but skip scp files to local host.
243 self.ssh_remoteclient.scp_connection()
244 return True
245 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500246 self.logger.info("\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500247 return False
248
249 def telnet_to_target_system(self):
250 r"""
251 Open a telnet connection to targeted system.
252 """
253 self.telnet_remoteclient = TelnetRemoteclient(self.hostname,
254 self.username,
255 self.password)
256 if self.telnet_remoteclient.tn_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500257 self.logger.info("\n\t[Check] %s Telnet connection established.\t [OK]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500258 return True
259 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500260 self.logger.info("\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500261 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500262
George Keishing772c9772021-06-16 23:23:42 -0500263 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500264 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500265 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500266
Peter D Phan04aca3b2021-06-21 10:37:18 -0500267 Description of argument(s):
268 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500269 """
270
Peter D Phane86d9a52021-07-15 10:42:25 -0500271 self.logger.info("\n\t---- Executing commands on " + self.hostname + " ----")
272 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500273
George Keishing86764b52021-07-01 04:32:03 -0500274 ffdc_actions = self.ffdc_actions
Peter D Phan2b8052d2021-06-22 10:55:41 -0500275
Peter D Phan72ce6b82021-06-03 06:18:26 -0500276 for machine_type in ffdc_actions.keys():
George Keishing6ea92b02021-07-01 11:20:50 -0500277 if self.target_type != machine_type:
278 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500279
Peter D Phane86d9a52021-07-15 10:42:25 -0500280 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
281 self.logger.info("\tSystem Type: %s" % machine_type)
George Keishing6ea92b02021-07-01 11:20:50 -0500282 for k, v in ffdc_actions[machine_type].items():
Peter D Phan72ce6b82021-06-03 06:18:26 -0500283
George Keishing6ea92b02021-07-01 11:20:50 -0500284 if self.remote_protocol != ffdc_actions[machine_type][k]['PROTOCOL'][0] \
285 and self.remote_protocol != 'ALL':
286 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500287
Peter D Phanbabf2962021-07-07 11:24:40 -0500288 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SSH' \
289 or ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SCP':
290 if 'SSH' in working_protocol_list \
291 or 'SCP' in working_protocol_list:
Peter D Phan3beb02e2021-07-06 13:25:17 -0500292 self.protocol_ssh(ffdc_actions, machine_type, k)
293 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500294 self.logger.error("\n\tERROR: SSH or SCP is not available for %s." % self.hostname)
George Keishing6ea92b02021-07-01 11:20:50 -0500295
Peter D Phan5963d632021-07-12 09:58:55 -0500296 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'TELNET':
297 if 'TELNET' in working_protocol_list:
298 self.protocol_telnet(ffdc_actions, machine_type, k)
299 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500300 self.logger.error("\n\tERROR: TELNET is not available for %s." % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500301
George Keishing6ea92b02021-07-01 11:20:50 -0500302 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'REDFISH':
Peter D Phan3beb02e2021-07-06 13:25:17 -0500303 if 'REDFISH' in working_protocol_list:
304 self.protocol_redfish(ffdc_actions, machine_type, k)
305 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500306 self.logger.error("\n\tERROR: REDFISH is not available for %s." % self.hostname)
George Keishing6ea92b02021-07-01 11:20:50 -0500307
308 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'IPMI':
Peter D Phan3beb02e2021-07-06 13:25:17 -0500309 if 'IPMI' in working_protocol_list:
310 self.protocol_ipmi(ffdc_actions, machine_type, k)
311 else:
Peter D Phand1fccd32021-07-21 06:45:54 -0500312 self.logger.error("\n\tERROR: IPMI is not available for %s." % self.hostname)
George Keishing04d29102021-07-16 02:05:57 -0500313
314 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SHELL':
315 if 'SHELL' in working_protocol_list:
316 self.protocol_shell_script(ffdc_actions, machine_type, k)
317 else:
318 self.logger.error("\n\tERROR: can't execute SHELL script")
George Keishingeafba182021-06-29 13:44:58 -0500319
Peter D Phan04aca3b2021-06-21 10:37:18 -0500320 # Close network connection after collecting all files
Peter D Phan7610bc42021-07-06 06:31:05 -0500321 self.elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - self.start_time))
Peter D Phan5963d632021-07-12 09:58:55 -0500322 self.ssh_remoteclient.ssh_remoteclient_disconnect()
323 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500324
Peter D Phan0c669772021-06-24 13:52:42 -0500325 def protocol_ssh(self,
326 ffdc_actions,
George Keishing6ea92b02021-07-01 11:20:50 -0500327 machine_type,
328 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500329 r"""
330 Perform actions using SSH and SCP protocols.
331
332 Description of argument(s):
333 ffdc_actions List of actions from ffdc_config.yaml.
334 machine_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500335 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500336 """
337
George Keishing6ea92b02021-07-01 11:20:50 -0500338 if sub_type == 'DUMP_LOGS':
339 self.group_copy(ffdc_actions[machine_type][sub_type])
340 else:
341 self.collect_and_copy_ffdc(ffdc_actions[machine_type][sub_type])
Peter D Phan0c669772021-06-24 13:52:42 -0500342
Peter D Phan5963d632021-07-12 09:58:55 -0500343 def protocol_telnet(self,
344 ffdc_actions,
345 machine_type,
346 sub_type):
347 r"""
348 Perform actions using telnet protocol.
349 Description of argument(s):
350 ffdc_actions List of actions from ffdc_config.yaml.
351 machine_type OS Type of remote host.
352 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500353 self.logger.info("\n\t[Run] Executing commands on %s using %s" % (self.hostname, 'TELNET'))
Peter D Phan5963d632021-07-12 09:58:55 -0500354 telnet_files_saved = []
355 progress_counter = 0
356 list_of_commands = ffdc_actions[machine_type][sub_type]['COMMANDS']
357 for index, each_cmd in enumerate(list_of_commands, start=0):
358 command_txt, command_timeout = self.unpack_command(each_cmd)
359 result = self.telnet_remoteclient.execute_command(command_txt, command_timeout)
360 if result:
361 try:
362 targ_file = ffdc_actions[machine_type][sub_type]['FILES'][index]
363 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500364 targ_file = command_txt
365 self.logger.warning(
366 "\n\t[WARN] Missing filename to store data from telnet %s." % each_cmd)
367 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan5963d632021-07-12 09:58:55 -0500368 targ_file_with_path = (self.ffdc_dir_path
369 + self.ffdc_prefix
370 + targ_file)
371 # Creates a new file
372 with open(targ_file_with_path, 'wb') as fp:
373 fp.write(result)
374 fp.close
375 telnet_files_saved.append(targ_file)
376 progress_counter += 1
377 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500378 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500379 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500380 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500381
Peter D Phan0c669772021-06-24 13:52:42 -0500382 def protocol_redfish(self,
383 ffdc_actions,
George Keishing6ea92b02021-07-01 11:20:50 -0500384 machine_type,
385 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500386 r"""
387 Perform actions using Redfish protocol.
388
389 Description of argument(s):
390 ffdc_actions List of actions from ffdc_config.yaml.
391 machine_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500392 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500393 """
394
Peter D Phane86d9a52021-07-15 10:42:25 -0500395 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, 'REDFISH'))
Peter D Phan0c669772021-06-24 13:52:42 -0500396 redfish_files_saved = []
397 progress_counter = 0
George Keishing6ea92b02021-07-01 11:20:50 -0500398 list_of_URL = ffdc_actions[machine_type][sub_type]['URL']
Peter D Phan0c669772021-06-24 13:52:42 -0500399 for index, each_url in enumerate(list_of_URL, start=0):
400 redfish_parm = '-u ' + self.username + ' -p ' + self.password + ' -r ' \
401 + self.hostname + ' -S Always raw GET ' + each_url
402
403 result = self.run_redfishtool(redfish_parm)
404 if result:
405 try:
Peter D Phanbabf2962021-07-07 11:24:40 -0500406 targ_file = self.get_file_list(ffdc_actions[machine_type][sub_type])[index]
Peter D Phan0c669772021-06-24 13:52:42 -0500407 except IndexError:
408 targ_file = each_url.split('/')[-1]
Peter D Phane86d9a52021-07-15 10:42:25 -0500409 self.logger.warning(
410 "\n\t[WARN] Missing filename to store data from redfish URL %s." % each_url)
411 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan0c669772021-06-24 13:52:42 -0500412
413 targ_file_with_path = (self.ffdc_dir_path
414 + self.ffdc_prefix
415 + targ_file)
416
417 # Creates a new file
418 with open(targ_file_with_path, 'w') as fp:
419 fp.write(result)
420 fp.close
421 redfish_files_saved.append(targ_file)
422
423 progress_counter += 1
424 self.print_progress(progress_counter)
425
Peter D Phane86d9a52021-07-15 10:42:25 -0500426 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan0c669772021-06-24 13:52:42 -0500427
428 for file in redfish_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500429 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan0c669772021-06-24 13:52:42 -0500430
George Keishingeafba182021-06-29 13:44:58 -0500431 def protocol_ipmi(self,
432 ffdc_actions,
George Keishing6ea92b02021-07-01 11:20:50 -0500433 machine_type,
434 sub_type):
George Keishingeafba182021-06-29 13:44:58 -0500435 r"""
436 Perform actions using ipmitool over LAN protocol.
437
438 Description of argument(s):
439 ffdc_actions List of actions from ffdc_config.yaml.
440 machine_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500441 sub_type Group type of commands.
George Keishingeafba182021-06-29 13:44:58 -0500442 """
443
Peter D Phane86d9a52021-07-15 10:42:25 -0500444 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, 'IPMI'))
George Keishingeafba182021-06-29 13:44:58 -0500445 ipmi_files_saved = []
446 progress_counter = 0
Peter D Phanbabf2962021-07-07 11:24:40 -0500447 list_of_cmd = self.get_command_list(ffdc_actions[machine_type][sub_type])
George Keishingeafba182021-06-29 13:44:58 -0500448 for index, each_cmd in enumerate(list_of_cmd, start=0):
449 ipmi_parm = '-U ' + self.username + ' -P ' + self.password + ' -H ' \
Peter D Phand1fccd32021-07-21 06:45:54 -0500450 + self.hostname + ' -I lanplus ' + each_cmd
George Keishingeafba182021-06-29 13:44:58 -0500451
452 result = self.run_ipmitool(ipmi_parm)
453 if result:
454 try:
Peter D Phanbabf2962021-07-07 11:24:40 -0500455 targ_file = self.get_file_list(ffdc_actions[machine_type][sub_type])[index]
George Keishingeafba182021-06-29 13:44:58 -0500456 except IndexError:
George Keishing6ea92b02021-07-01 11:20:50 -0500457 targ_file = each_cmd.split('/')[-1]
Peter D Phane86d9a52021-07-15 10:42:25 -0500458 self.logger.warning("\n\t[WARN] Missing filename to store data from IPMI %s." % each_cmd)
459 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500460
461 targ_file_with_path = (self.ffdc_dir_path
462 + self.ffdc_prefix
463 + targ_file)
464
465 # Creates a new file
466 with open(targ_file_with_path, 'w') as fp:
467 fp.write(result)
468 fp.close
469 ipmi_files_saved.append(targ_file)
470
471 progress_counter += 1
472 self.print_progress(progress_counter)
473
Peter D Phane86d9a52021-07-15 10:42:25 -0500474 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500475
476 for file in ipmi_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500477 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500478
Peter D Phan04aca3b2021-06-21 10:37:18 -0500479 def collect_and_copy_ffdc(self,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500480 ffdc_actions_for_machine_type,
481 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500482 r"""
483 Send commands in ffdc_config file to targeted system.
484
485 Description of argument(s):
486 ffdc_actions_for_machine_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500487 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500488 """
489
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500490 # Executing commands, if any
Peter D Phan3beb02e2021-07-06 13:25:17 -0500491 self.ssh_execute_ffdc_commands(ffdc_actions_for_machine_type,
492 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500493
Peter D Phan3beb02e2021-07-06 13:25:17 -0500494 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500495 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500496 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500497
Peter D Phan04aca3b2021-06-21 10:37:18 -0500498 # Retrieving files from target system
Peter D Phanbabf2962021-07-07 11:24:40 -0500499 list_of_files = self.get_file_list(ffdc_actions_for_machine_type)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500500 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500501 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500502 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500503
Peter D Phanbabf2962021-07-07 11:24:40 -0500504 def get_command_list(self,
505 ffdc_actions_for_machine_type):
506 r"""
507 Fetch list of commands from configuration file
508
509 Description of argument(s):
510 ffdc_actions_for_machine_type commands and files for the selected remote host type.
511 """
512 try:
513 list_of_commands = ffdc_actions_for_machine_type['COMMANDS']
514 except KeyError:
515 list_of_commands = []
516 return list_of_commands
517
518 def get_file_list(self,
519 ffdc_actions_for_machine_type):
520 r"""
521 Fetch list of commands from configuration file
522
523 Description of argument(s):
524 ffdc_actions_for_machine_type commands and files for the selected remote host type.
525 """
526 try:
527 list_of_files = ffdc_actions_for_machine_type['FILES']
528 except KeyError:
529 list_of_files = []
530 return list_of_files
531
Peter D Phan5963d632021-07-12 09:58:55 -0500532 def unpack_command(self,
533 command):
534 r"""
535 Unpack command from config file
536
537 Description of argument(s):
538 command Command from config file.
539 """
540 if isinstance(command, dict):
541 command_txt = next(iter(command))
542 command_timeout = next(iter(command.values()))
543 elif isinstance(command, str):
544 command_txt = command
545 # Default command timeout 60 seconds
546 command_timeout = 60
547
548 return command_txt, command_timeout
549
Peter D Phan3beb02e2021-07-06 13:25:17 -0500550 def ssh_execute_ffdc_commands(self,
551 ffdc_actions_for_machine_type,
552 form_filename=False):
553 r"""
554 Send commands in ffdc_config file to targeted system.
555
556 Description of argument(s):
557 ffdc_actions_for_machine_type commands and files for the selected remote host type.
558 form_filename if true, pre-pend self.target_type to filename
559 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500560 self.logger.info("\n\t[Run] Executing commands on %s using %s"
561 % (self.hostname, ffdc_actions_for_machine_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500562
Peter D Phanbabf2962021-07-07 11:24:40 -0500563 list_of_commands = self.get_command_list(ffdc_actions_for_machine_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500564 # If command list is empty, returns
565 if not list_of_commands:
566 return
567
568 progress_counter = 0
569 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500570 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500571
572 if form_filename:
573 command_txt = str(command_txt % self.target_type)
574
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500575 cmd_exit_code, err, response = \
576 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
577
578 if cmd_exit_code:
579 self.logger.warning(
580 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
581 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500582
Peter D Phan3beb02e2021-07-06 13:25:17 -0500583 progress_counter += 1
584 self.print_progress(progress_counter)
585
Peter D Phane86d9a52021-07-15 10:42:25 -0500586 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500587
Peter D Phan56429a62021-06-23 08:38:29 -0500588 def group_copy(self,
589 ffdc_actions_for_machine_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500590 r"""
591 scp group of files (wild card) from remote host.
592
593 Description of argument(s):
594 ffdc_actions_for_machine_type commands and files for the selected remote host type.
595 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500596
Peter D Phan5963d632021-07-12 09:58:55 -0500597 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500598 self.logger.info("\n\tCopying DUMP files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500599
Peter D Phanbabf2962021-07-07 11:24:40 -0500600 list_of_commands = self.get_command_list(ffdc_actions_for_machine_type)
601 # If command list is empty, returns
602 if not list_of_commands:
603 return
Peter D Phan56429a62021-06-23 08:38:29 -0500604
Peter D Phanbabf2962021-07-07 11:24:40 -0500605 for command in list_of_commands:
606 try:
607 filename = command.split(' ')[2]
608 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500609 self.logger.info("\t\tInvalid command %s for DUMP_LOGS block." % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500610 continue
611
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500612 cmd_exit_code, err, response = \
613 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500614
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500615 # If file does not exist, code take no action.
616 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500617 if response:
Peter D Phan5963d632021-07-12 09:58:55 -0500618 scp_result = self.ssh_remoteclient.scp_file_from_remote(filename, self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500619 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500620 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500621 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500622 self.logger.info("\t\tThere is no " + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500623
624 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500625 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500626
Peter D Phan72ce6b82021-06-03 06:18:26 -0500627 def scp_ffdc(self,
628 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500629 targ_file_prefix,
630 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500631 file_list=None,
632 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500633 r"""
634 SCP all files in file_dict to the indicated directory on the local system.
635
636 Description of argument(s):
637 targ_dir_path The path of the directory to receive the files.
638 targ_file_prefix Prefix which will be pre-pended to each
639 target file's name.
640 file_dict A dictionary of files to scp from targeted system to this system
641
642 """
643
Peter D Phan72ce6b82021-06-03 06:18:26 -0500644 progress_counter = 0
645 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500646 if form_filename:
647 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500648 source_file_path = filename
649 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
650
Peter D Phanbabf2962021-07-07 11:24:40 -0500651 # If source file name contains wild card, copy filename as is.
652 if '*' in source_file_path:
Peter D Phan5963d632021-07-12 09:58:55 -0500653 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500654 else:
Peter D Phan5963d632021-07-12 09:58:55 -0500655 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500656
657 if not quiet:
658 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500659 self.logger.info(
660 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500661 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500662 self.logger.info(
663 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500664 else:
665 progress_counter += 1
666 self.print_progress(progress_counter)
667
Peter D Phan72ce6b82021-06-03 06:18:26 -0500668 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500669 r"""
670 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
671 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
672 Individual ffdc file will have timestr_filename.
673
674 Description of class variables:
675 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
676
677 self.ffdc_prefix The prefix to be given to each ffdc file name.
678
679 """
680
681 timestr = time.strftime("%Y%m%d-%H%M%S")
682 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
683 self.ffdc_prefix = timestr + "_"
684 self.validate_local_store(self.ffdc_dir_path)
685
686 def validate_local_store(self, dir_path):
687 r"""
688 Ensure path exists to store FFDC files locally.
689
690 Description of variable:
691 dir_path The dir path where collected ffdc data files will be stored.
692
693 """
694
695 if not os.path.exists(dir_path):
696 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500697 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500698 except (IOError, OSError) as e:
699 # PermissionError
700 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500701 self.logger.error(
702 '>>>>>\tERROR: os.makedirs %s failed with PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500703 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500704 self.logger.error(
705 '>>>>>\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500706 sys.exit(-1)
707
708 def print_progress(self, progress):
709 r"""
710 Print activity progress +
711
712 Description of variable:
713 progress Progress counter.
714
715 """
716
717 sys.stdout.write("\r\t" + "+" * progress)
718 sys.stdout.flush()
719 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500720
721 def verify_redfish(self):
722 r"""
723 Verify remote host has redfish service active
724
725 """
726 redfish_parm = '-u ' + self.username + ' -p ' + self.password + ' -r ' \
727 + self.hostname + ' -S Always raw GET /redfish/v1/'
728 return(self.run_redfishtool(redfish_parm, True))
729
George Keishingeafba182021-06-29 13:44:58 -0500730 def verify_ipmi(self):
731 r"""
732 Verify remote host has IPMI LAN service active
733
734 """
735 ipmi_parm = '-U ' + self.username + ' -P ' + self.password + ' -H ' \
Peter D Phand1fccd32021-07-21 06:45:54 -0500736 + self.hostname + ' power status -I lanplus'
George Keishingeafba182021-06-29 13:44:58 -0500737 return(self.run_ipmitool(ipmi_parm, True))
738
Peter D Phan0c669772021-06-24 13:52:42 -0500739 def run_redfishtool(self,
740 parms_string,
741 quiet=False):
742 r"""
743 Run CLI redfishtool
744
745 Description of variable:
746 parms_string redfishtool subcommand and options.
747 quiet do not print redfishtool error message if True
748 """
749
750 result = subprocess.run(['redfishtool ' + parms_string],
751 stdout=subprocess.PIPE,
752 stderr=subprocess.PIPE,
753 shell=True,
754 universal_newlines=True)
755
756 if result.stderr and not quiet:
Peter D Phane86d9a52021-07-15 10:42:25 -0500757 self.logger.error('\n\t\tERROR with redfishtool ' + parms_string)
758 self.logger.error('\t\t' + result.stderr)
Peter D Phan0c669772021-06-24 13:52:42 -0500759
760 return result.stdout
George Keishingeafba182021-06-29 13:44:58 -0500761
762 def run_ipmitool(self,
763 parms_string,
764 quiet=False):
765 r"""
766 Run CLI IPMI tool.
767
768 Description of variable:
769 parms_string ipmitool subcommand and options.
770 quiet do not print redfishtool error message if True
771 """
772
773 result = subprocess.run(['ipmitool -I lanplus -C 17 ' + parms_string],
774 stdout=subprocess.PIPE,
775 stderr=subprocess.PIPE,
776 shell=True,
777 universal_newlines=True)
778
779 if result.stderr and not quiet:
Peter D Phane86d9a52021-07-15 10:42:25 -0500780 self.logger.error('\n\t\tERROR with ipmitool -I lanplus -C 17 ' + parms_string)
781 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500782
783 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500784
785 def run_shell_script(self,
786 parms_string,
787 quiet=False):
788 r"""
789 Run CLI shell script tool.
790
791 Description of variable:
792 parms_string script command options.
793 quiet do not print redfishtool error message if True
794 """
795
796 result = subprocess.run([parms_string],
797 stdout=subprocess.PIPE,
798 stderr=subprocess.PIPE,
799 shell=True,
800 universal_newlines=True)
801
802 if result.stderr and not quiet:
803 self.logger.error('\n\t\tERROR executing %s' % parms_string)
804 self.logger.error('\t\t' + result.stderr)
805
806 return result.stdout
807
808 def protocol_shell_script(self,
809 ffdc_actions,
810 machine_type,
811 sub_type):
812 r"""
813 Perform SHELL script execution locally.
814
815 Description of argument(s):
816 ffdc_actions List of actions from ffdc_config.yaml.
817 machine_type OS Type of remote host.
818 sub_type Group type of commands.
819 """
820
821 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, 'SHELL'))
822 shell_files_saved = []
823 progress_counter = 0
824 list_of_cmd = self.get_command_list(ffdc_actions[machine_type][sub_type])
825 for index, each_cmd in enumerate(list_of_cmd, start=0):
826
827 result = self.run_shell_script(each_cmd)
828 if result:
829 try:
830 targ_file = self.get_file_list(ffdc_actions[machine_type][sub_type])[index]
831 except IndexError:
832 targ_file = each_cmd.split('/')[-1]
833 self.logger.warning("\n\t[WARN] Missing filename to store data %s." % each_cmd)
834 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
835
836 targ_file_with_path = (self.ffdc_dir_path
837 + self.ffdc_prefix
838 + targ_file)
839
840 # Creates a new file
841 with open(targ_file_with_path, 'w') as fp:
842 fp.write(result)
843 fp.close
844 shell_files_saved.append(targ_file)
845
846 progress_counter += 1
847 self.print_progress(progress_counter)
848
849 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
850
851 for file in shell_files_saved:
852 self.logger.info("\n\t\tSuccessfully save file " + file + ".")