blob: 3f5c599e1f319931bead82fd4b6c51a9728f86bd [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(
George Keishing7bf55092021-07-22 12:33:34 -0500177 "\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")
Peter D Phan0c669772021-06-24 13:52:42 -0500191
Peter D Phanbff617a2021-07-22 08:41:35 -0500192 for machine_type in self.ffdc_actions.keys():
193 if self.target_type != machine_type:
194 continue
Peter D Phan0c669772021-06-24 13:52:42 -0500195
Peter D Phanbff617a2021-07-22 08:41:35 -0500196 for k, v in self.ffdc_actions[machine_type].items():
George Keishingeafba182021-06-29 13:44:58 -0500197
Peter D Phanbff617a2021-07-22 08:41:35 -0500198 # If config protocol is SSH or SCP
199 if (self.ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SSH'
200 or self.ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SCP') \
201 and (self.remote_protocol == 'ALL'
202 or self.remote_protocol == 'SSH' or self.remote_protocol == 'SCP'):
203
204 # Only check SSH/SCP once for both protocols
205 if 'SSH' not in working_protocol_list \
206 and 'SCP' not in working_protocol_list:
207 if self.ssh_to_target_system():
208 working_protocol_list.append("SSH")
209 working_protocol_list.append("SCP")
210
211 # If config protocol is TELNET
212 if (self.ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'TELNET') \
213 and (self.remote_protocol == 'ALL' or self.remote_protocol == 'TELNET'):
214 if self.telnet_to_target_system():
215 working_protocol_list.append("TELNET")
216
217 # If config protocol is REDFISH
218 if (self.ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'REDFISH') \
219 and (self.remote_protocol == 'ALL' or self.remote_protocol == 'REDFISH'):
220 if self.verify_redfish():
221 working_protocol_list.append("REDFISH")
222 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
223 else:
224 self.logger.info(
225 "\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
226
227 # If config protocol is IPMI
228 if (self.ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'IPMI') \
229 and (self.remote_protocol == 'ALL' or self.remote_protocol == 'IPMI'):
230 if self.verify_ipmi():
231 working_protocol_list.append("IPMI")
232 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
233 else:
234 self.logger.info(
235 "\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500236
Peter D Phan72ce6b82021-06-03 06:18:26 -0500237 # Verify top level directory exists for storage
238 self.validate_local_store(self.location)
Peter D Phane86d9a52021-07-15 10:42:25 -0500239 self.logger.info("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500240
241 if ((self.remote_protocol not in working_protocol_list) and (self.remote_protocol != 'ALL')):
Peter D Phane86d9a52021-07-15 10:42:25 -0500242 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
243 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500244 '\tERROR: Requested protocol %s is not in working protocol list.\n'
Peter D Phan0c669772021-06-24 13:52:42 -0500245 % self.remote_protocol)
246 sys.exit(-1)
247 else:
248 self.generate_ffdc(working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500249
250 def ssh_to_target_system(self):
251 r"""
252 Open a ssh connection to targeted system.
253
254 """
255
Peter D Phan5963d632021-07-12 09:58:55 -0500256 self.ssh_remoteclient = SSHRemoteclient(self.hostname,
257 self.username,
258 self.password)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500259
Peter D Phan5963d632021-07-12 09:58:55 -0500260 if self.ssh_remoteclient.ssh_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500261 self.logger.info("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500262
Peter D Phan5963d632021-07-12 09:58:55 -0500263 # Check scp connection.
264 # If scp connection fails,
265 # continue with FFDC generation but skip scp files to local host.
266 self.ssh_remoteclient.scp_connection()
267 return True
268 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500269 self.logger.info("\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500270 return False
271
272 def telnet_to_target_system(self):
273 r"""
274 Open a telnet connection to targeted system.
275 """
276 self.telnet_remoteclient = TelnetRemoteclient(self.hostname,
277 self.username,
278 self.password)
279 if self.telnet_remoteclient.tn_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500280 self.logger.info("\n\t[Check] %s Telnet connection established.\t [OK]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500281 return True
282 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500283 self.logger.info("\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500284 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500285
George Keishing772c9772021-06-16 23:23:42 -0500286 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500287 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500288 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500289
Peter D Phan04aca3b2021-06-21 10:37:18 -0500290 Description of argument(s):
291 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500292 """
293
Peter D Phane86d9a52021-07-15 10:42:25 -0500294 self.logger.info("\n\t---- Executing commands on " + self.hostname + " ----")
295 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500296
George Keishing86764b52021-07-01 04:32:03 -0500297 ffdc_actions = self.ffdc_actions
Peter D Phan2b8052d2021-06-22 10:55:41 -0500298
Peter D Phan72ce6b82021-06-03 06:18:26 -0500299 for machine_type in ffdc_actions.keys():
George Keishing6ea92b02021-07-01 11:20:50 -0500300 if self.target_type != machine_type:
301 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500302
Peter D Phane86d9a52021-07-15 10:42:25 -0500303 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
304 self.logger.info("\tSystem Type: %s" % machine_type)
George Keishing6ea92b02021-07-01 11:20:50 -0500305 for k, v in ffdc_actions[machine_type].items():
Peter D Phan72ce6b82021-06-03 06:18:26 -0500306
George Keishing6ea92b02021-07-01 11:20:50 -0500307 if self.remote_protocol != ffdc_actions[machine_type][k]['PROTOCOL'][0] \
308 and self.remote_protocol != 'ALL':
309 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500310
Peter D Phanbabf2962021-07-07 11:24:40 -0500311 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SSH' \
312 or ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SCP':
313 if 'SSH' in working_protocol_list \
314 or 'SCP' in working_protocol_list:
Peter D Phan3beb02e2021-07-06 13:25:17 -0500315 self.protocol_ssh(ffdc_actions, machine_type, k)
316 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500317 self.logger.error("\n\tERROR: SSH or SCP is not available for %s." % self.hostname)
George Keishing6ea92b02021-07-01 11:20:50 -0500318
Peter D Phan5963d632021-07-12 09:58:55 -0500319 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'TELNET':
320 if 'TELNET' in working_protocol_list:
321 self.protocol_telnet(ffdc_actions, machine_type, k)
322 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500323 self.logger.error("\n\tERROR: TELNET is not available for %s." % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500324
George Keishing6ea92b02021-07-01 11:20:50 -0500325 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'REDFISH':
Peter D Phan3beb02e2021-07-06 13:25:17 -0500326 if 'REDFISH' in working_protocol_list:
327 self.protocol_redfish(ffdc_actions, machine_type, k)
328 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500329 self.logger.error("\n\tERROR: REDFISH is not available for %s." % self.hostname)
George Keishing6ea92b02021-07-01 11:20:50 -0500330
331 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'IPMI':
Peter D Phan3beb02e2021-07-06 13:25:17 -0500332 if 'IPMI' in working_protocol_list:
333 self.protocol_ipmi(ffdc_actions, machine_type, k)
334 else:
Peter D Phand1fccd32021-07-21 06:45:54 -0500335 self.logger.error("\n\tERROR: IPMI is not available for %s." % self.hostname)
George Keishing04d29102021-07-16 02:05:57 -0500336
337 if ffdc_actions[machine_type][k]['PROTOCOL'][0] == 'SHELL':
338 if 'SHELL' in working_protocol_list:
339 self.protocol_shell_script(ffdc_actions, machine_type, k)
340 else:
341 self.logger.error("\n\tERROR: can't execute SHELL script")
George Keishingeafba182021-06-29 13:44:58 -0500342
Peter D Phan04aca3b2021-06-21 10:37:18 -0500343 # Close network connection after collecting all files
Peter D Phan7610bc42021-07-06 06:31:05 -0500344 self.elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - self.start_time))
Peter D Phanbff617a2021-07-22 08:41:35 -0500345 if self.ssh_remoteclient:
346 self.ssh_remoteclient.ssh_remoteclient_disconnect()
347 if self.telnet_remoteclient:
348 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500349
Peter D Phan0c669772021-06-24 13:52:42 -0500350 def protocol_ssh(self,
351 ffdc_actions,
George Keishing6ea92b02021-07-01 11:20:50 -0500352 machine_type,
353 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500354 r"""
355 Perform actions using SSH and SCP protocols.
356
357 Description of argument(s):
358 ffdc_actions List of actions from ffdc_config.yaml.
359 machine_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500360 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500361 """
362
George Keishing6ea92b02021-07-01 11:20:50 -0500363 if sub_type == 'DUMP_LOGS':
364 self.group_copy(ffdc_actions[machine_type][sub_type])
365 else:
366 self.collect_and_copy_ffdc(ffdc_actions[machine_type][sub_type])
Peter D Phan0c669772021-06-24 13:52:42 -0500367
Peter D Phan5963d632021-07-12 09:58:55 -0500368 def protocol_telnet(self,
369 ffdc_actions,
370 machine_type,
371 sub_type):
372 r"""
373 Perform actions using telnet protocol.
374 Description of argument(s):
375 ffdc_actions List of actions from ffdc_config.yaml.
376 machine_type OS Type of remote host.
377 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500378 self.logger.info("\n\t[Run] Executing commands on %s using %s" % (self.hostname, 'TELNET'))
Peter D Phan5963d632021-07-12 09:58:55 -0500379 telnet_files_saved = []
380 progress_counter = 0
381 list_of_commands = ffdc_actions[machine_type][sub_type]['COMMANDS']
382 for index, each_cmd in enumerate(list_of_commands, start=0):
383 command_txt, command_timeout = self.unpack_command(each_cmd)
384 result = self.telnet_remoteclient.execute_command(command_txt, command_timeout)
385 if result:
386 try:
387 targ_file = ffdc_actions[machine_type][sub_type]['FILES'][index]
388 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500389 targ_file = command_txt
390 self.logger.warning(
391 "\n\t[WARN] Missing filename to store data from telnet %s." % each_cmd)
392 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan5963d632021-07-12 09:58:55 -0500393 targ_file_with_path = (self.ffdc_dir_path
394 + self.ffdc_prefix
395 + targ_file)
396 # Creates a new file
397 with open(targ_file_with_path, 'wb') as fp:
398 fp.write(result)
399 fp.close
400 telnet_files_saved.append(targ_file)
401 progress_counter += 1
402 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500403 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500404 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500405 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500406
Peter D Phan0c669772021-06-24 13:52:42 -0500407 def protocol_redfish(self,
408 ffdc_actions,
George Keishing6ea92b02021-07-01 11:20:50 -0500409 machine_type,
410 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500411 r"""
412 Perform actions using Redfish protocol.
413
414 Description of argument(s):
415 ffdc_actions List of actions from ffdc_config.yaml.
416 machine_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500417 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500418 """
419
Peter D Phane86d9a52021-07-15 10:42:25 -0500420 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, 'REDFISH'))
Peter D Phan0c669772021-06-24 13:52:42 -0500421 redfish_files_saved = []
422 progress_counter = 0
George Keishing6ea92b02021-07-01 11:20:50 -0500423 list_of_URL = ffdc_actions[machine_type][sub_type]['URL']
Peter D Phan0c669772021-06-24 13:52:42 -0500424 for index, each_url in enumerate(list_of_URL, start=0):
425 redfish_parm = '-u ' + self.username + ' -p ' + self.password + ' -r ' \
426 + self.hostname + ' -S Always raw GET ' + each_url
427
428 result = self.run_redfishtool(redfish_parm)
429 if result:
430 try:
Peter D Phanbabf2962021-07-07 11:24:40 -0500431 targ_file = self.get_file_list(ffdc_actions[machine_type][sub_type])[index]
Peter D Phan0c669772021-06-24 13:52:42 -0500432 except IndexError:
433 targ_file = each_url.split('/')[-1]
Peter D Phane86d9a52021-07-15 10:42:25 -0500434 self.logger.warning(
435 "\n\t[WARN] Missing filename to store data from redfish URL %s." % each_url)
436 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan0c669772021-06-24 13:52:42 -0500437
438 targ_file_with_path = (self.ffdc_dir_path
439 + self.ffdc_prefix
440 + targ_file)
441
442 # Creates a new file
443 with open(targ_file_with_path, 'w') as fp:
444 fp.write(result)
445 fp.close
446 redfish_files_saved.append(targ_file)
447
448 progress_counter += 1
449 self.print_progress(progress_counter)
450
Peter D Phane86d9a52021-07-15 10:42:25 -0500451 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan0c669772021-06-24 13:52:42 -0500452
453 for file in redfish_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500454 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan0c669772021-06-24 13:52:42 -0500455
George Keishingeafba182021-06-29 13:44:58 -0500456 def protocol_ipmi(self,
457 ffdc_actions,
George Keishing6ea92b02021-07-01 11:20:50 -0500458 machine_type,
459 sub_type):
George Keishingeafba182021-06-29 13:44:58 -0500460 r"""
461 Perform actions using ipmitool over LAN protocol.
462
463 Description of argument(s):
464 ffdc_actions List of actions from ffdc_config.yaml.
465 machine_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500466 sub_type Group type of commands.
George Keishingeafba182021-06-29 13:44:58 -0500467 """
468
Peter D Phane86d9a52021-07-15 10:42:25 -0500469 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, 'IPMI'))
George Keishingeafba182021-06-29 13:44:58 -0500470 ipmi_files_saved = []
471 progress_counter = 0
Peter D Phanbabf2962021-07-07 11:24:40 -0500472 list_of_cmd = self.get_command_list(ffdc_actions[machine_type][sub_type])
George Keishingeafba182021-06-29 13:44:58 -0500473 for index, each_cmd in enumerate(list_of_cmd, start=0):
474 ipmi_parm = '-U ' + self.username + ' -P ' + self.password + ' -H ' \
Peter D Phand1fccd32021-07-21 06:45:54 -0500475 + self.hostname + ' -I lanplus ' + each_cmd
George Keishingeafba182021-06-29 13:44:58 -0500476
477 result = self.run_ipmitool(ipmi_parm)
478 if result:
479 try:
Peter D Phanbabf2962021-07-07 11:24:40 -0500480 targ_file = self.get_file_list(ffdc_actions[machine_type][sub_type])[index]
George Keishingeafba182021-06-29 13:44:58 -0500481 except IndexError:
George Keishing6ea92b02021-07-01 11:20:50 -0500482 targ_file = each_cmd.split('/')[-1]
Peter D Phane86d9a52021-07-15 10:42:25 -0500483 self.logger.warning("\n\t[WARN] Missing filename to store data from IPMI %s." % each_cmd)
484 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500485
486 targ_file_with_path = (self.ffdc_dir_path
487 + self.ffdc_prefix
488 + targ_file)
489
490 # Creates a new file
491 with open(targ_file_with_path, 'w') as fp:
492 fp.write(result)
493 fp.close
494 ipmi_files_saved.append(targ_file)
495
496 progress_counter += 1
497 self.print_progress(progress_counter)
498
Peter D Phane86d9a52021-07-15 10:42:25 -0500499 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500500
501 for file in ipmi_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500502 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500503
Peter D Phan04aca3b2021-06-21 10:37:18 -0500504 def collect_and_copy_ffdc(self,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500505 ffdc_actions_for_machine_type,
506 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500507 r"""
508 Send commands in ffdc_config file to targeted system.
509
510 Description of argument(s):
511 ffdc_actions_for_machine_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500512 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500513 """
514
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500515 # Executing commands, if any
Peter D Phan3beb02e2021-07-06 13:25:17 -0500516 self.ssh_execute_ffdc_commands(ffdc_actions_for_machine_type,
517 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500518
Peter D Phan3beb02e2021-07-06 13:25:17 -0500519 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500520 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500521 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500522
Peter D Phan04aca3b2021-06-21 10:37:18 -0500523 # Retrieving files from target system
Peter D Phanbabf2962021-07-07 11:24:40 -0500524 list_of_files = self.get_file_list(ffdc_actions_for_machine_type)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500525 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500526 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500527 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500528
Peter D Phanbabf2962021-07-07 11:24:40 -0500529 def get_command_list(self,
530 ffdc_actions_for_machine_type):
531 r"""
532 Fetch list of commands from configuration file
533
534 Description of argument(s):
535 ffdc_actions_for_machine_type commands and files for the selected remote host type.
536 """
537 try:
538 list_of_commands = ffdc_actions_for_machine_type['COMMANDS']
539 except KeyError:
540 list_of_commands = []
541 return list_of_commands
542
543 def get_file_list(self,
544 ffdc_actions_for_machine_type):
545 r"""
546 Fetch list of commands from configuration file
547
548 Description of argument(s):
549 ffdc_actions_for_machine_type commands and files for the selected remote host type.
550 """
551 try:
552 list_of_files = ffdc_actions_for_machine_type['FILES']
553 except KeyError:
554 list_of_files = []
555 return list_of_files
556
Peter D Phan5963d632021-07-12 09:58:55 -0500557 def unpack_command(self,
558 command):
559 r"""
560 Unpack command from config file
561
562 Description of argument(s):
563 command Command from config file.
564 """
565 if isinstance(command, dict):
566 command_txt = next(iter(command))
567 command_timeout = next(iter(command.values()))
568 elif isinstance(command, str):
569 command_txt = command
570 # Default command timeout 60 seconds
571 command_timeout = 60
572
573 return command_txt, command_timeout
574
Peter D Phan3beb02e2021-07-06 13:25:17 -0500575 def ssh_execute_ffdc_commands(self,
576 ffdc_actions_for_machine_type,
577 form_filename=False):
578 r"""
579 Send commands in ffdc_config file to targeted system.
580
581 Description of argument(s):
582 ffdc_actions_for_machine_type commands and files for the selected remote host type.
583 form_filename if true, pre-pend self.target_type to filename
584 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500585 self.logger.info("\n\t[Run] Executing commands on %s using %s"
586 % (self.hostname, ffdc_actions_for_machine_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500587
Peter D Phanbabf2962021-07-07 11:24:40 -0500588 list_of_commands = self.get_command_list(ffdc_actions_for_machine_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500589 # If command list is empty, returns
590 if not list_of_commands:
591 return
592
593 progress_counter = 0
594 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500595 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500596
597 if form_filename:
598 command_txt = str(command_txt % self.target_type)
599
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500600 cmd_exit_code, err, response = \
601 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
602
603 if cmd_exit_code:
604 self.logger.warning(
605 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
606 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500607
Peter D Phan3beb02e2021-07-06 13:25:17 -0500608 progress_counter += 1
609 self.print_progress(progress_counter)
610
Peter D Phane86d9a52021-07-15 10:42:25 -0500611 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500612
Peter D Phan56429a62021-06-23 08:38:29 -0500613 def group_copy(self,
614 ffdc_actions_for_machine_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500615 r"""
616 scp group of files (wild card) from remote host.
617
618 Description of argument(s):
619 ffdc_actions_for_machine_type commands and files for the selected remote host type.
620 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500621
Peter D Phan5963d632021-07-12 09:58:55 -0500622 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500623 self.logger.info("\n\tCopying DUMP files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500624
Peter D Phanbabf2962021-07-07 11:24:40 -0500625 list_of_commands = self.get_command_list(ffdc_actions_for_machine_type)
626 # If command list is empty, returns
627 if not list_of_commands:
628 return
Peter D Phan56429a62021-06-23 08:38:29 -0500629
Peter D Phanbabf2962021-07-07 11:24:40 -0500630 for command in list_of_commands:
631 try:
632 filename = command.split(' ')[2]
633 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500634 self.logger.info("\t\tInvalid command %s for DUMP_LOGS block." % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500635 continue
636
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500637 cmd_exit_code, err, response = \
638 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500639
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500640 # If file does not exist, code take no action.
641 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500642 if response:
Peter D Phan5963d632021-07-12 09:58:55 -0500643 scp_result = self.ssh_remoteclient.scp_file_from_remote(filename, self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500644 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500645 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500646 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500647 self.logger.info("\t\tThere is no " + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500648
649 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500650 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500651
Peter D Phan72ce6b82021-06-03 06:18:26 -0500652 def scp_ffdc(self,
653 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500654 targ_file_prefix,
655 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500656 file_list=None,
657 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500658 r"""
659 SCP all files in file_dict to the indicated directory on the local system.
660
661 Description of argument(s):
662 targ_dir_path The path of the directory to receive the files.
663 targ_file_prefix Prefix which will be pre-pended to each
664 target file's name.
665 file_dict A dictionary of files to scp from targeted system to this system
666
667 """
668
Peter D Phan72ce6b82021-06-03 06:18:26 -0500669 progress_counter = 0
670 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500671 if form_filename:
672 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500673 source_file_path = filename
674 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
675
Peter D Phanbabf2962021-07-07 11:24:40 -0500676 # If source file name contains wild card, copy filename as is.
677 if '*' in source_file_path:
Peter D Phan5963d632021-07-12 09:58:55 -0500678 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500679 else:
Peter D Phan5963d632021-07-12 09:58:55 -0500680 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500681
682 if not quiet:
683 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500684 self.logger.info(
685 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500686 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500687 self.logger.info(
688 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500689 else:
690 progress_counter += 1
691 self.print_progress(progress_counter)
692
Peter D Phan72ce6b82021-06-03 06:18:26 -0500693 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500694 r"""
695 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
696 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
697 Individual ffdc file will have timestr_filename.
698
699 Description of class variables:
700 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
701
702 self.ffdc_prefix The prefix to be given to each ffdc file name.
703
704 """
705
706 timestr = time.strftime("%Y%m%d-%H%M%S")
707 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
708 self.ffdc_prefix = timestr + "_"
709 self.validate_local_store(self.ffdc_dir_path)
710
711 def validate_local_store(self, dir_path):
712 r"""
713 Ensure path exists to store FFDC files locally.
714
715 Description of variable:
716 dir_path The dir path where collected ffdc data files will be stored.
717
718 """
719
720 if not os.path.exists(dir_path):
721 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500722 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500723 except (IOError, OSError) as e:
724 # PermissionError
725 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500726 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500727 '\tERROR: os.makedirs %s failed with PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500728 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500729 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500730 '\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500731 sys.exit(-1)
732
733 def print_progress(self, progress):
734 r"""
735 Print activity progress +
736
737 Description of variable:
738 progress Progress counter.
739
740 """
741
742 sys.stdout.write("\r\t" + "+" * progress)
743 sys.stdout.flush()
744 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500745
746 def verify_redfish(self):
747 r"""
748 Verify remote host has redfish service active
749
750 """
751 redfish_parm = '-u ' + self.username + ' -p ' + self.password + ' -r ' \
752 + self.hostname + ' -S Always raw GET /redfish/v1/'
753 return(self.run_redfishtool(redfish_parm, True))
754
George Keishingeafba182021-06-29 13:44:58 -0500755 def verify_ipmi(self):
756 r"""
757 Verify remote host has IPMI LAN service active
758
759 """
760 ipmi_parm = '-U ' + self.username + ' -P ' + self.password + ' -H ' \
Peter D Phand1fccd32021-07-21 06:45:54 -0500761 + self.hostname + ' power status -I lanplus'
George Keishingeafba182021-06-29 13:44:58 -0500762 return(self.run_ipmitool(ipmi_parm, True))
763
Peter D Phan0c669772021-06-24 13:52:42 -0500764 def run_redfishtool(self,
765 parms_string,
766 quiet=False):
767 r"""
768 Run CLI redfishtool
769
770 Description of variable:
771 parms_string redfishtool subcommand and options.
772 quiet do not print redfishtool error message if True
773 """
774
775 result = subprocess.run(['redfishtool ' + parms_string],
776 stdout=subprocess.PIPE,
777 stderr=subprocess.PIPE,
778 shell=True,
779 universal_newlines=True)
780
781 if result.stderr and not quiet:
George Keishing7bf55092021-07-22 12:33:34 -0500782 self.logger.error('\n\tERROR with redfishtool ' + parms_string)
783 self.logger.error('\n\t%s' % result.stderr.split('\n'))
Peter D Phan0c669772021-06-24 13:52:42 -0500784
785 return result.stdout
George Keishingeafba182021-06-29 13:44:58 -0500786
787 def run_ipmitool(self,
788 parms_string,
789 quiet=False):
790 r"""
791 Run CLI IPMI tool.
792
793 Description of variable:
794 parms_string ipmitool subcommand and options.
795 quiet do not print redfishtool error message if True
796 """
797
798 result = subprocess.run(['ipmitool -I lanplus -C 17 ' + parms_string],
799 stdout=subprocess.PIPE,
800 stderr=subprocess.PIPE,
801 shell=True,
802 universal_newlines=True)
803
804 if result.stderr and not quiet:
Peter D Phane86d9a52021-07-15 10:42:25 -0500805 self.logger.error('\n\t\tERROR with ipmitool -I lanplus -C 17 ' + parms_string)
806 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500807
808 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500809
810 def run_shell_script(self,
811 parms_string,
812 quiet=False):
813 r"""
814 Run CLI shell script tool.
815
816 Description of variable:
817 parms_string script command options.
818 quiet do not print redfishtool error message if True
819 """
820
821 result = subprocess.run([parms_string],
822 stdout=subprocess.PIPE,
823 stderr=subprocess.PIPE,
824 shell=True,
825 universal_newlines=True)
826
827 if result.stderr and not quiet:
828 self.logger.error('\n\t\tERROR executing %s' % parms_string)
829 self.logger.error('\t\t' + result.stderr)
830
831 return result.stdout
832
833 def protocol_shell_script(self,
834 ffdc_actions,
835 machine_type,
836 sub_type):
837 r"""
838 Perform SHELL script execution locally.
839
840 Description of argument(s):
841 ffdc_actions List of actions from ffdc_config.yaml.
842 machine_type OS Type of remote host.
843 sub_type Group type of commands.
844 """
845
846 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, 'SHELL'))
847 shell_files_saved = []
848 progress_counter = 0
849 list_of_cmd = self.get_command_list(ffdc_actions[machine_type][sub_type])
850 for index, each_cmd in enumerate(list_of_cmd, start=0):
851
852 result = self.run_shell_script(each_cmd)
853 if result:
854 try:
855 targ_file = self.get_file_list(ffdc_actions[machine_type][sub_type])[index]
856 except IndexError:
857 targ_file = each_cmd.split('/')[-1]
858 self.logger.warning("\n\t[WARN] Missing filename to store data %s." % each_cmd)
859 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
860
861 targ_file_with_path = (self.ffdc_dir_path
862 + self.ffdc_prefix
863 + targ_file)
864
865 # Creates a new file
866 with open(targ_file_with_path, 'w') as fp:
867 fp.write(result)
868 fp.close
869 shell_files_saved.append(targ_file)
870
871 progress_counter += 1
872 self.print_progress(progress_counter)
873
874 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
875
876 for file in shell_files_saved:
877 self.logger.info("\n\t\tSuccessfully save file " + file + ".")