blob: 5c9d1f0370a7eb06cd6b73b3d304615de0299157 [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
George Keishing04d29102021-07-16 02:05:57 -050058 # This is for the env vars a user can use in YAML to load it at runtime.
59 # Example YAML:
60 # -COMMANDS:
61 # - my_command ${hostname} ${username} ${password}
62 os.environ['hostname'] = hostname
63 os.environ['username'] = username
64 os.environ['password'] = password
65
Peter D Phane86d9a52021-07-15 10:42:25 -050066 self.ffdc_config = ffdc_config
67 self.location = location + "/" + remote_type.upper()
68 self.ssh_remoteclient = None
69 self.telnet_remoteclient = None
70 self.ffdc_dir_path = ""
71 self.ffdc_prefix = ""
72 self.target_type = remote_type.upper()
73 self.remote_protocol = remote_protocol.upper()
74 self.start_time = 0
75 self.elapsed_time = ''
76 self.logger = None
77
78 # Set prefix values for scp files and directory.
79 # Since the time stamp is at second granularity, these values are set here
80 # to be sure that all files for this run will have same timestamps
81 # and they will be saved in the same directory.
82 # self.location == local system for now
83 self.set_ffdc_defaults()
84
85 # Logger for this run. Need to be after set_ffdc_defaults()
86 self.script_logging(getattr(logging, log_level.upper()))
87
88 # Verify top level directory exists for storage
89 self.validate_local_store(self.location)
90
Peter D Phan72ce6b82021-06-03 06:18:26 -050091 if self.verify_script_env():
Peter D Phane86d9a52021-07-15 10:42:25 -050092 # Load default or user define YAML configuration file.
93 with open(self.ffdc_config, 'r') as file:
94 self.ffdc_actions = yaml.load(file, Loader=yaml.FullLoader)
95
96 if self.target_type not in self.ffdc_actions.keys():
97 self.logger.error(
98 "\n\tERROR: %s is not listed in %s.\n\n" % (self.target_type, self.ffdc_config))
99 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500100 else:
Peter D Phan8462faf2021-06-16 12:24:15 -0500101 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500102
George Keishing4885b2f2021-07-21 15:22:45 -0500103 # Load ENV vars from user.
George Keishingaa1f8482021-07-22 00:54:55 -0500104 self.logger.info("\n\tENV: User define input YAML variables")
105 self.env_dict = {}
106
George Keishing4885b2f2021-07-21 15:22:45 -0500107 try:
108 if env_vars:
George Keishingaa1f8482021-07-22 00:54:55 -0500109 self.env_dict = json.loads(env_vars)
George Keishing4885b2f2021-07-21 15:22:45 -0500110
111 # Export ENV vars default.
George Keishingaa1f8482021-07-22 00:54:55 -0500112 for key, value in self.env_dict.items():
George Keishing4885b2f2021-07-21 15:22:45 -0500113 os.environ[key] = value
George Keishingaa1f8482021-07-22 00:54:55 -0500114
George Keishing8e94f8c2021-07-23 15:06:32 -0500115 if econfig:
116 with open(econfig, 'r') as file:
117 env_config_dict = yaml.load(file, Loader=yaml.FullLoader)
118 # Export ENV vars.
119 for key, value in env_config_dict['env_params'].items():
120 os.environ[key] = str(value)
121 self.env_dict[key] = str(value)
122
George Keishing4885b2f2021-07-21 15:22:45 -0500123 except json.decoder.JSONDecodeError as e:
124 self.logger.error("\n\tERROR: %s " % e)
125 sys.exit(-1)
126
George Keishingaa1f8482021-07-22 00:54:55 -0500127 # Append default Env.
128 self.env_dict['hostname'] = self.hostname
129 self.env_dict['username'] = self.username
130 self.env_dict['password'] = self.password
George Keishing0813e712021-07-26 08:29:20 -0500131 # This to mask the password from displaying on the console.
132 mask_dict = self.env_dict.copy()
133 for k, v in mask_dict.items():
134 if k.lower().find("password") != -1:
135 hidden_text = []
136 hidden_text.append(v)
137 password_regex = '(' +\
138 '|'.join([re.escape(x) for x in hidden_text]) + ')'
139 mask_dict[k] = re.sub(password_regex, "********", v)
140 self.logger.info(json.dumps(mask_dict, indent=8, sort_keys=True))
George Keishingaa1f8482021-07-22 00:54:55 -0500141
Peter D Phan72ce6b82021-06-03 06:18:26 -0500142 def verify_script_env(self):
143
144 # Import to log version
145 import click
146 import paramiko
147
148 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -0500149
George Keishing506b0582021-07-27 09:31:22 -0500150 redfishtool_version = self.run_tool_cmd('redfishtool -V').split(' ')[2].strip('\n')
151 ipmitool_version = self.run_tool_cmd('ipmitool -V').split(' ')[2]
Peter D Phan0c669772021-06-24 13:52:42 -0500152
Peter D Phane86d9a52021-07-15 10:42:25 -0500153 self.logger.info("\n\t---- Script host environment ----")
154 self.logger.info("\t{:<10} {:<10}".format('Script hostname', os.uname()[1]))
155 self.logger.info("\t{:<10} {:<10}".format('Script host os', platform.platform()))
156 self.logger.info("\t{:<10} {:>10}".format('Python', platform.python_version()))
157 self.logger.info("\t{:<10} {:>10}".format('PyYAML', yaml.__version__))
158 self.logger.info("\t{:<10} {:>10}".format('click', click.__version__))
159 self.logger.info("\t{:<10} {:>10}".format('paramiko', paramiko.__version__))
160 self.logger.info("\t{:<10} {:>9}".format('redfishtool', redfishtool_version))
161 self.logger.info("\t{:<10} {:>12}".format('ipmitool', ipmitool_version))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500162
Peter D Phan8462faf2021-06-16 12:24:15 -0500163 if eval(yaml.__version__.replace('.', ',')) < (5, 4, 1):
Peter D Phane86d9a52021-07-15 10:42:25 -0500164 self.logger.error("\n\tERROR: Python or python packages do not meet minimum version requirement.")
165 self.logger.error("\tERROR: PyYAML version 5.4.1 or higher is needed.\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500166 run_env_ok = False
167
Peter D Phane86d9a52021-07-15 10:42:25 -0500168 self.logger.info("\t---- End script host environment ----")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500169 return run_env_ok
170
Peter D Phane86d9a52021-07-15 10:42:25 -0500171 def script_logging(self,
172 log_level_attr):
173 r"""
174 Create logger
175
176 """
177 self.logger = logging.getLogger()
178 self.logger.setLevel(log_level_attr)
179 log_file_handler = logging.FileHandler(self.ffdc_dir_path + "collector.log")
180
181 stdout_handler = logging.StreamHandler(sys.stdout)
182 self.logger.addHandler(log_file_handler)
183 self.logger.addHandler(stdout_handler)
184
185 # Turn off paramiko INFO logging
186 logging.getLogger("paramiko").setLevel(logging.WARNING)
187
Peter D Phan72ce6b82021-06-03 06:18:26 -0500188 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500189 r"""
190 Check if target system is ping-able.
191
192 """
George Keishing0662e942021-07-13 05:12:20 -0500193 response = os.system("ping -c 1 %s 2>&1 >/dev/null" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500194 if response == 0:
Peter D Phane86d9a52021-07-15 10:42:25 -0500195 self.logger.info("\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500196 return True
197 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500198 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500199 "\n\tERROR: %s is not ping-able. FFDC collection aborted.\n" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500200 sys.exit(-1)
201
Peter D Phan72ce6b82021-06-03 06:18:26 -0500202 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500203 r"""
204 Initiate FFDC Collection depending on requested protocol.
205
206 """
207
Peter D Phane86d9a52021-07-15 10:42:25 -0500208 self.logger.info("\n\t---- Start communicating with %s ----" % self.hostname)
Peter D Phan7610bc42021-07-06 06:31:05 -0500209 self.start_time = time.time()
Peter D Phan0c669772021-06-24 13:52:42 -0500210
George Keishingf5a57502021-07-22 16:43:47 -0500211 # Find the list of target and protocol supported.
212 check_protocol_list = []
213 config_dict = self.ffdc_actions
Peter D Phan0c669772021-06-24 13:52:42 -0500214
George Keishingf5a57502021-07-22 16:43:47 -0500215 for target_type in config_dict.keys():
216 if self.target_type != target_type:
217 continue
George Keishingeafba182021-06-29 13:44:58 -0500218
George Keishingf5a57502021-07-22 16:43:47 -0500219 for k, v in config_dict[target_type].items():
220 if config_dict[target_type][k]['PROTOCOL'][0] not in check_protocol_list:
221 check_protocol_list.append(config_dict[target_type][k]['PROTOCOL'][0])
Peter D Phanbff617a2021-07-22 08:41:35 -0500222
George Keishingf5a57502021-07-22 16:43:47 -0500223 self.logger.info("\n\t %s protocol type: %s" % (self.target_type, check_protocol_list))
Peter D Phanbff617a2021-07-22 08:41:35 -0500224
George Keishingf5a57502021-07-22 16:43:47 -0500225 verified_working_protocol = self.verify_protocol(check_protocol_list)
Peter D Phanbff617a2021-07-22 08:41:35 -0500226
George Keishingf5a57502021-07-22 16:43:47 -0500227 if verified_working_protocol:
Peter D Phane86d9a52021-07-15 10:42:25 -0500228 self.logger.info("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500229
George Keishingf5a57502021-07-22 16:43:47 -0500230 # Verify top level directory exists for storage
231 self.validate_local_store(self.location)
232
233 if ((self.remote_protocol not in verified_working_protocol) and (self.remote_protocol != 'ALL')):
234 self.logger.info("\n\tWorking protocol list: %s" % verified_working_protocol)
235 self.logger.error(
236 '\tERROR: Requested protocol %s is not in working protocol list.\n'
237 % self.remote_protocol)
238 sys.exit(-1)
239 else:
240 self.generate_ffdc(verified_working_protocol)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500241
242 def ssh_to_target_system(self):
243 r"""
244 Open a ssh connection to targeted system.
245
246 """
247
Peter D Phan5963d632021-07-12 09:58:55 -0500248 self.ssh_remoteclient = SSHRemoteclient(self.hostname,
249 self.username,
250 self.password)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500251
Peter D Phan5963d632021-07-12 09:58:55 -0500252 if self.ssh_remoteclient.ssh_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500253 self.logger.info("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500254
Peter D Phan5963d632021-07-12 09:58:55 -0500255 # Check scp connection.
256 # If scp connection fails,
257 # continue with FFDC generation but skip scp files to local host.
258 self.ssh_remoteclient.scp_connection()
259 return True
260 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500261 self.logger.info("\n\t[Check] %s SSH connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500262 return False
263
264 def telnet_to_target_system(self):
265 r"""
266 Open a telnet connection to targeted system.
267 """
268 self.telnet_remoteclient = TelnetRemoteclient(self.hostname,
269 self.username,
270 self.password)
271 if self.telnet_remoteclient.tn_remoteclient_login():
Peter D Phane86d9a52021-07-15 10:42:25 -0500272 self.logger.info("\n\t[Check] %s Telnet connection established.\t [OK]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500273 return True
274 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500275 self.logger.info("\n\t[Check] %s Telnet connection.\t [NOT AVAILABLE]" % self.hostname)
Peter D Phan5963d632021-07-12 09:58:55 -0500276 return False
Peter D Phan72ce6b82021-06-03 06:18:26 -0500277
George Keishing772c9772021-06-16 23:23:42 -0500278 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500279 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500280 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500281
Peter D Phan04aca3b2021-06-21 10:37:18 -0500282 Description of argument(s):
283 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500284 """
285
Peter D Phane86d9a52021-07-15 10:42:25 -0500286 self.logger.info("\n\t---- Executing commands on " + self.hostname + " ----")
287 self.logger.info("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500288
George Keishingf5a57502021-07-22 16:43:47 -0500289 config_dict = self.ffdc_actions
290 for target_type in config_dict.keys():
291 if self.target_type != target_type:
George Keishing6ea92b02021-07-01 11:20:50 -0500292 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500293
Peter D Phane86d9a52021-07-15 10:42:25 -0500294 self.logger.info("\n\tFFDC Path: %s " % self.ffdc_dir_path)
George Keishingf5a57502021-07-22 16:43:47 -0500295 self.logger.info("\tSystem Type: %s" % target_type)
296 for k, v in config_dict[target_type].items():
Peter D Phan72ce6b82021-06-03 06:18:26 -0500297
George Keishingf5a57502021-07-22 16:43:47 -0500298 if self.remote_protocol not in working_protocol_list \
George Keishing6ea92b02021-07-01 11:20:50 -0500299 and self.remote_protocol != 'ALL':
300 continue
Peter D Phan72ce6b82021-06-03 06:18:26 -0500301
George Keishingf5a57502021-07-22 16:43:47 -0500302 protocol = config_dict[target_type][k]['PROTOCOL'][0]
303
304 if protocol not in working_protocol_list:
305 continue
306
George Keishingb7607612021-07-27 13:31:23 -0500307 if protocol in working_protocol_list:
308 if protocol == 'SSH' or protocol == 'SCP':
George Keishingf5a57502021-07-22 16:43:47 -0500309 self.protocol_ssh(target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500310 elif protocol == 'TELNET':
George Keishingf5a57502021-07-22 16:43:47 -0500311 self.protocol_telnet(target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500312 elif protocol == 'REDFISH' or protocol == 'IPMI' or protocol == 'SHELL':
George Keishing506b0582021-07-27 09:31:22 -0500313 self.protocol_execute(protocol, target_type, k)
George Keishingb7607612021-07-27 13:31:23 -0500314 else:
315 self.logger.error("\n\tERROR: %s is not available for %s." % (protocol, self.hostname))
George Keishingeafba182021-06-29 13:44:58 -0500316
Peter D Phan04aca3b2021-06-21 10:37:18 -0500317 # Close network connection after collecting all files
Peter D Phan7610bc42021-07-06 06:31:05 -0500318 self.elapsed_time = time.strftime("%H:%M:%S", time.gmtime(time.time() - self.start_time))
Peter D Phanbff617a2021-07-22 08:41:35 -0500319 if self.ssh_remoteclient:
320 self.ssh_remoteclient.ssh_remoteclient_disconnect()
321 if self.telnet_remoteclient:
322 self.telnet_remoteclient.tn_remoteclient_disconnect()
Peter D Phan04aca3b2021-06-21 10:37:18 -0500323
Peter D Phan0c669772021-06-24 13:52:42 -0500324 def protocol_ssh(self,
George Keishingf5a57502021-07-22 16:43:47 -0500325 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500326 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500327 r"""
328 Perform actions using SSH and SCP protocols.
329
330 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500331 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500332 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500333 """
334
George Keishing6ea92b02021-07-01 11:20:50 -0500335 if sub_type == 'DUMP_LOGS':
George Keishingf5a57502021-07-22 16:43:47 -0500336 self.group_copy(self.ffdc_actions[target_type][sub_type])
George Keishing6ea92b02021-07-01 11:20:50 -0500337 else:
George Keishingf5a57502021-07-22 16:43:47 -0500338 self.collect_and_copy_ffdc(self.ffdc_actions[target_type][sub_type])
Peter D Phan0c669772021-06-24 13:52:42 -0500339
Peter D Phan5963d632021-07-12 09:58:55 -0500340 def protocol_telnet(self,
George Keishingf5a57502021-07-22 16:43:47 -0500341 target_type,
Peter D Phan5963d632021-07-12 09:58:55 -0500342 sub_type):
343 r"""
344 Perform actions using telnet protocol.
345 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500346 target_type OS Type of remote host.
Peter D Phan5963d632021-07-12 09:58:55 -0500347 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500348 self.logger.info("\n\t[Run] Executing commands on %s using %s" % (self.hostname, 'TELNET'))
Peter D Phan5963d632021-07-12 09:58:55 -0500349 telnet_files_saved = []
350 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500351 list_of_commands = self.ffdc_actions[target_type][sub_type]['COMMANDS']
Peter D Phan5963d632021-07-12 09:58:55 -0500352 for index, each_cmd in enumerate(list_of_commands, start=0):
353 command_txt, command_timeout = self.unpack_command(each_cmd)
354 result = self.telnet_remoteclient.execute_command(command_txt, command_timeout)
355 if result:
356 try:
George Keishingf5a57502021-07-22 16:43:47 -0500357 targ_file = self.ffdc_actions[target_type][sub_type]['FILES'][index]
Peter D Phan5963d632021-07-12 09:58:55 -0500358 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500359 targ_file = command_txt
360 self.logger.warning(
361 "\n\t[WARN] Missing filename to store data from telnet %s." % each_cmd)
362 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
Peter D Phan5963d632021-07-12 09:58:55 -0500363 targ_file_with_path = (self.ffdc_dir_path
364 + self.ffdc_prefix
365 + targ_file)
366 # Creates a new file
367 with open(targ_file_with_path, 'wb') as fp:
368 fp.write(result)
369 fp.close
370 telnet_files_saved.append(targ_file)
371 progress_counter += 1
372 self.print_progress(progress_counter)
Peter D Phane86d9a52021-07-15 10:42:25 -0500373 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan5963d632021-07-12 09:58:55 -0500374 for file in telnet_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500375 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
Peter D Phan5963d632021-07-12 09:58:55 -0500376
George Keishing506b0582021-07-27 09:31:22 -0500377 def protocol_execute(self,
378 protocol,
George Keishingf5a57502021-07-22 16:43:47 -0500379 target_type,
George Keishing6ea92b02021-07-01 11:20:50 -0500380 sub_type):
Peter D Phan0c669772021-06-24 13:52:42 -0500381 r"""
George Keishing506b0582021-07-27 09:31:22 -0500382 Perform actions for a given protocol.
Peter D Phan0c669772021-06-24 13:52:42 -0500383
384 Description of argument(s):
George Keishing506b0582021-07-27 09:31:22 -0500385 protocol Protocol to execute.
George Keishingf5a57502021-07-22 16:43:47 -0500386 target_type OS Type of remote host.
George Keishing6ea92b02021-07-01 11:20:50 -0500387 sub_type Group type of commands.
Peter D Phan0c669772021-06-24 13:52:42 -0500388 """
389
George Keishing506b0582021-07-27 09:31:22 -0500390 self.logger.info("\n\t[Run] Executing commands to %s using %s" % (self.hostname, protocol))
391 executed_files_saved = []
George Keishingeafba182021-06-29 13:44:58 -0500392 progress_counter = 0
George Keishingf5a57502021-07-22 16:43:47 -0500393 list_of_cmd = self.get_command_list(self.ffdc_actions[target_type][sub_type])
George Keishingeafba182021-06-29 13:44:58 -0500394 for index, each_cmd in enumerate(list_of_cmd, start=0):
George Keishing506b0582021-07-27 09:31:22 -0500395 result = self.run_tool_cmd(each_cmd)
George Keishingeafba182021-06-29 13:44:58 -0500396 if result:
397 try:
George Keishingf5a57502021-07-22 16:43:47 -0500398 targ_file = self.get_file_list(self.ffdc_actions[target_type][sub_type])[index]
George Keishingeafba182021-06-29 13:44:58 -0500399 except IndexError:
George Keishing6ea92b02021-07-01 11:20:50 -0500400 targ_file = each_cmd.split('/')[-1]
George Keishing506b0582021-07-27 09:31:22 -0500401 self.logger.warning(
402 "\n\t[WARN] Missing filename to store data from %s." % each_cmd)
Peter D Phane86d9a52021-07-15 10:42:25 -0500403 self.logger.warning("\t[WARN] Data will be stored in %s." % targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500404
405 targ_file_with_path = (self.ffdc_dir_path
406 + self.ffdc_prefix
407 + targ_file)
408
409 # Creates a new file
410 with open(targ_file_with_path, 'w') as fp:
411 fp.write(result)
412 fp.close
George Keishing506b0582021-07-27 09:31:22 -0500413 executed_files_saved.append(targ_file)
George Keishingeafba182021-06-29 13:44:58 -0500414
415 progress_counter += 1
416 self.print_progress(progress_counter)
417
Peter D Phane86d9a52021-07-15 10:42:25 -0500418 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
George Keishingeafba182021-06-29 13:44:58 -0500419
George Keishing506b0582021-07-27 09:31:22 -0500420 for file in executed_files_saved:
Peter D Phane86d9a52021-07-15 10:42:25 -0500421 self.logger.info("\n\t\tSuccessfully save file " + file + ".")
George Keishingeafba182021-06-29 13:44:58 -0500422
Peter D Phan04aca3b2021-06-21 10:37:18 -0500423 def collect_and_copy_ffdc(self,
George Keishingf5a57502021-07-22 16:43:47 -0500424 ffdc_actions_for_target_type,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500425 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500426 r"""
427 Send commands in ffdc_config file to targeted system.
428
429 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500430 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500431 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500432 """
433
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500434 # Executing commands, if any
George Keishingf5a57502021-07-22 16:43:47 -0500435 self.ssh_execute_ffdc_commands(ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500436 form_filename)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500437
Peter D Phan3beb02e2021-07-06 13:25:17 -0500438 # Copying files
Peter D Phan5963d632021-07-12 09:58:55 -0500439 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500440 self.logger.info("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500441
Peter D Phan04aca3b2021-06-21 10:37:18 -0500442 # Retrieving files from target system
George Keishingf5a57502021-07-22 16:43:47 -0500443 list_of_files = self.get_file_list(ffdc_actions_for_target_type)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500444 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500445 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500446 self.logger.info("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500447
Peter D Phanbabf2962021-07-07 11:24:40 -0500448 def get_command_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500449 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500450 r"""
451 Fetch list of commands from configuration file
452
453 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500454 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500455 """
456 try:
George Keishingf5a57502021-07-22 16:43:47 -0500457 list_of_commands = ffdc_actions_for_target_type['COMMANDS']
Peter D Phanbabf2962021-07-07 11:24:40 -0500458 except KeyError:
459 list_of_commands = []
460 return list_of_commands
461
462 def get_file_list(self,
George Keishingf5a57502021-07-22 16:43:47 -0500463 ffdc_actions_for_target_type):
Peter D Phanbabf2962021-07-07 11:24:40 -0500464 r"""
465 Fetch list of commands from configuration file
466
467 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500468 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phanbabf2962021-07-07 11:24:40 -0500469 """
470 try:
George Keishingf5a57502021-07-22 16:43:47 -0500471 list_of_files = ffdc_actions_for_target_type['FILES']
Peter D Phanbabf2962021-07-07 11:24:40 -0500472 except KeyError:
473 list_of_files = []
474 return list_of_files
475
Peter D Phan5963d632021-07-12 09:58:55 -0500476 def unpack_command(self,
477 command):
478 r"""
479 Unpack command from config file
480
481 Description of argument(s):
482 command Command from config file.
483 """
484 if isinstance(command, dict):
485 command_txt = next(iter(command))
486 command_timeout = next(iter(command.values()))
487 elif isinstance(command, str):
488 command_txt = command
489 # Default command timeout 60 seconds
490 command_timeout = 60
491
492 return command_txt, command_timeout
493
Peter D Phan3beb02e2021-07-06 13:25:17 -0500494 def ssh_execute_ffdc_commands(self,
George Keishingf5a57502021-07-22 16:43:47 -0500495 ffdc_actions_for_target_type,
Peter D Phan3beb02e2021-07-06 13:25:17 -0500496 form_filename=False):
497 r"""
498 Send commands in ffdc_config file to targeted system.
499
500 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500501 ffdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan3beb02e2021-07-06 13:25:17 -0500502 form_filename if true, pre-pend self.target_type to filename
503 """
Peter D Phane86d9a52021-07-15 10:42:25 -0500504 self.logger.info("\n\t[Run] Executing commands on %s using %s"
George Keishingf5a57502021-07-22 16:43:47 -0500505 % (self.hostname, ffdc_actions_for_target_type['PROTOCOL'][0]))
Peter D Phan3beb02e2021-07-06 13:25:17 -0500506
George Keishingf5a57502021-07-22 16:43:47 -0500507 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500508 # If command list is empty, returns
509 if not list_of_commands:
510 return
511
512 progress_counter = 0
513 for command in list_of_commands:
Peter D Phan5963d632021-07-12 09:58:55 -0500514 command_txt, command_timeout = self.unpack_command(command)
Peter D Phan3beb02e2021-07-06 13:25:17 -0500515
516 if form_filename:
517 command_txt = str(command_txt % self.target_type)
518
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500519 cmd_exit_code, err, response = \
520 self.ssh_remoteclient.execute_command(command_txt, command_timeout)
521
522 if cmd_exit_code:
523 self.logger.warning(
524 "\n\t\t[WARN] %s exits with code %s." % (command_txt, str(cmd_exit_code)))
525 self.logger.warning("\t\t[WARN] %s " % err)
Peter D Phanbabf2962021-07-07 11:24:40 -0500526
Peter D Phan3beb02e2021-07-06 13:25:17 -0500527 progress_counter += 1
528 self.print_progress(progress_counter)
529
Peter D Phane86d9a52021-07-15 10:42:25 -0500530 self.logger.info("\n\t[Run] Commands execution completed.\t\t [OK]")
Peter D Phan3beb02e2021-07-06 13:25:17 -0500531
Peter D Phan56429a62021-06-23 08:38:29 -0500532 def group_copy(self,
George Keishingf5a57502021-07-22 16:43:47 -0500533 ffdc_actions_for_target_type):
Peter D Phan56429a62021-06-23 08:38:29 -0500534 r"""
535 scp group of files (wild card) from remote host.
536
537 Description of argument(s):
George Keishingf5a57502021-07-22 16:43:47 -0500538 fdc_actions_for_target_type commands and files for the selected remote host type.
Peter D Phan56429a62021-06-23 08:38:29 -0500539 """
Peter D Phan3beb02e2021-07-06 13:25:17 -0500540
Peter D Phan5963d632021-07-12 09:58:55 -0500541 if self.ssh_remoteclient.scpclient:
Peter D Phane86d9a52021-07-15 10:42:25 -0500542 self.logger.info("\n\tCopying DUMP files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500543
George Keishingf5a57502021-07-22 16:43:47 -0500544 list_of_commands = self.get_command_list(ffdc_actions_for_target_type)
Peter D Phanbabf2962021-07-07 11:24:40 -0500545 # If command list is empty, returns
546 if not list_of_commands:
547 return
Peter D Phan56429a62021-06-23 08:38:29 -0500548
Peter D Phanbabf2962021-07-07 11:24:40 -0500549 for command in list_of_commands:
550 try:
551 filename = command.split(' ')[2]
552 except IndexError:
Peter D Phane86d9a52021-07-15 10:42:25 -0500553 self.logger.info("\t\tInvalid command %s for DUMP_LOGS block." % command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500554 continue
555
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500556 cmd_exit_code, err, response = \
557 self.ssh_remoteclient.execute_command(command)
Peter D Phanbabf2962021-07-07 11:24:40 -0500558
Peter D Phan2b6cb3a2021-07-19 06:55:42 -0500559 # If file does not exist, code take no action.
560 # cmd_exit_code is ignored for this scenario.
Peter D Phan56429a62021-06-23 08:38:29 -0500561 if response:
Peter D Phan5963d632021-07-12 09:58:55 -0500562 scp_result = self.ssh_remoteclient.scp_file_from_remote(filename, self.ffdc_dir_path)
Peter D Phan56429a62021-06-23 08:38:29 -0500563 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500564 self.logger.info("\t\tSuccessfully copied from " + self.hostname + ':' + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500565 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500566 self.logger.info("\t\tThere is no " + filename)
Peter D Phan56429a62021-06-23 08:38:29 -0500567
568 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500569 self.logger.info("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500570
Peter D Phan72ce6b82021-06-03 06:18:26 -0500571 def scp_ffdc(self,
572 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500573 targ_file_prefix,
574 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500575 file_list=None,
576 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500577 r"""
578 SCP all files in file_dict to the indicated directory on the local system.
579
580 Description of argument(s):
581 targ_dir_path The path of the directory to receive the files.
582 targ_file_prefix Prefix which will be pre-pended to each
583 target file's name.
584 file_dict A dictionary of files to scp from targeted system to this system
585
586 """
587
Peter D Phan72ce6b82021-06-03 06:18:26 -0500588 progress_counter = 0
589 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500590 if form_filename:
591 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500592 source_file_path = filename
593 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
594
Peter D Phanbabf2962021-07-07 11:24:40 -0500595 # If source file name contains wild card, copy filename as is.
596 if '*' in source_file_path:
Peter D Phan5963d632021-07-12 09:58:55 -0500597 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, self.ffdc_dir_path)
Peter D Phanbabf2962021-07-07 11:24:40 -0500598 else:
Peter D Phan5963d632021-07-12 09:58:55 -0500599 scp_result = self.ssh_remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500600
601 if not quiet:
602 if scp_result:
Peter D Phane86d9a52021-07-15 10:42:25 -0500603 self.logger.info(
604 "\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500605 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500606 self.logger.info(
607 "\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500608 else:
609 progress_counter += 1
610 self.print_progress(progress_counter)
611
Peter D Phan72ce6b82021-06-03 06:18:26 -0500612 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500613 r"""
614 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
615 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
616 Individual ffdc file will have timestr_filename.
617
618 Description of class variables:
619 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
620
621 self.ffdc_prefix The prefix to be given to each ffdc file name.
622
623 """
624
625 timestr = time.strftime("%Y%m%d-%H%M%S")
626 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
627 self.ffdc_prefix = timestr + "_"
628 self.validate_local_store(self.ffdc_dir_path)
629
630 def validate_local_store(self, dir_path):
631 r"""
632 Ensure path exists to store FFDC files locally.
633
634 Description of variable:
635 dir_path The dir path where collected ffdc data files will be stored.
636
637 """
638
639 if not os.path.exists(dir_path):
640 try:
George Keishing7b3a5132021-07-13 09:24:02 -0500641 os.makedirs(dir_path, 0o755)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500642 except (IOError, OSError) as e:
643 # PermissionError
644 if e.errno == EPERM or e.errno == EACCES:
Peter D Phane86d9a52021-07-15 10:42:25 -0500645 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500646 '\tERROR: os.makedirs %s failed with PermissionError.\n' % dir_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500647 else:
Peter D Phane86d9a52021-07-15 10:42:25 -0500648 self.logger.error(
George Keishing7bf55092021-07-22 12:33:34 -0500649 '\tERROR: os.makedirs %s failed with %s.\n' % (dir_path, e.strerror))
Peter D Phan72ce6b82021-06-03 06:18:26 -0500650 sys.exit(-1)
651
652 def print_progress(self, progress):
653 r"""
654 Print activity progress +
655
656 Description of variable:
657 progress Progress counter.
658
659 """
660
661 sys.stdout.write("\r\t" + "+" * progress)
662 sys.stdout.flush()
663 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500664
665 def verify_redfish(self):
666 r"""
667 Verify remote host has redfish service active
668
669 """
George Keishing506b0582021-07-27 09:31:22 -0500670 redfish_parm = 'redfishtool -r ' \
Peter D Phan0c669772021-06-24 13:52:42 -0500671 + self.hostname + ' -S Always raw GET /redfish/v1/'
George Keishing506b0582021-07-27 09:31:22 -0500672 return(self.run_tool_cmd(redfish_parm, True))
Peter D Phan0c669772021-06-24 13:52:42 -0500673
George Keishingeafba182021-06-29 13:44:58 -0500674 def verify_ipmi(self):
675 r"""
676 Verify remote host has IPMI LAN service active
677
678 """
George Keishing484f8242021-07-27 01:42:02 -0500679 if self.target_type == 'OPENBMC':
680 ipmi_parm = 'ipmitool -I lanplus -C 17 -U ' + self.username + ' -P ' \
681 + self.password + ' -H ' + self.hostname + ' power status'
682 else:
683 ipmi_parm = 'ipmitool -I lanplus -P ' \
684 + self.password + ' -H ' + self.hostname + ' power status'
685
George Keishing506b0582021-07-27 09:31:22 -0500686 return(self.run_tool_cmd(ipmi_parm, True))
George Keishingeafba182021-06-29 13:44:58 -0500687
George Keishing506b0582021-07-27 09:31:22 -0500688 def run_tool_cmd(self,
George Keishingeafba182021-06-29 13:44:58 -0500689 parms_string,
690 quiet=False):
691 r"""
George Keishing506b0582021-07-27 09:31:22 -0500692 Run CLI standard tool or scripts.
George Keishingeafba182021-06-29 13:44:58 -0500693
694 Description of variable:
George Keishing506b0582021-07-27 09:31:22 -0500695 parms_string tool command options.
696 quiet do not print tool error message if True
George Keishingeafba182021-06-29 13:44:58 -0500697 """
698
George Keishing484f8242021-07-27 01:42:02 -0500699 result = subprocess.run([parms_string],
George Keishingeafba182021-06-29 13:44:58 -0500700 stdout=subprocess.PIPE,
701 stderr=subprocess.PIPE,
702 shell=True,
703 universal_newlines=True)
704
705 if result.stderr and not quiet:
George Keishing484f8242021-07-27 01:42:02 -0500706 self.logger.error('\n\t\tERROR with %s ' % parms_string)
Peter D Phane86d9a52021-07-15 10:42:25 -0500707 self.logger.error('\t\t' + result.stderr)
George Keishingeafba182021-06-29 13:44:58 -0500708
709 return result.stdout
George Keishing04d29102021-07-16 02:05:57 -0500710
George Keishingf5a57502021-07-22 16:43:47 -0500711 def verify_protocol(self, protocol_list):
712 r"""
713 Perform protocol working check.
714
715 Description of argument(s):
716 protocol_list List of protocol.
717 """
718
719 tmp_list = []
720 if self.target_is_pingable():
721 tmp_list.append("SHELL")
722
723 for protocol in protocol_list:
724 if self.remote_protocol != 'ALL':
725 if self.remote_protocol != protocol:
726 continue
727
728 # Only check SSH/SCP once for both protocols
729 if protocol == 'SSH' or protocol == 'SCP' and protocol not in tmp_list:
730 if self.ssh_to_target_system():
George Keishingaa638702021-07-26 11:48:28 -0500731 # Add only what user asked.
732 if self.remote_protocol != 'ALL':
733 tmp_list.append(self.remote_protocol)
734 else:
735 tmp_list.append('SSH')
736 tmp_list.append('SCP')
George Keishingf5a57502021-07-22 16:43:47 -0500737
738 if protocol == 'TELNET':
739 if self.telnet_to_target_system():
740 tmp_list.append(protocol)
741
742 if protocol == 'REDFISH':
743 if self.verify_redfish():
744 tmp_list.append(protocol)
745 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
746 else:
747 self.logger.info("\n\t[Check] %s Redfish Service.\t\t [NOT AVAILABLE]" % self.hostname)
748
749 if protocol == 'IPMI':
750 if self.verify_ipmi():
751 tmp_list.append(protocol)
752 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [OK]" % self.hostname)
753 else:
754 self.logger.info("\n\t[Check] %s IPMI LAN Service.\t\t [NOT AVAILABLE]" % self.hostname)
755
756 return tmp_list