blob: 9e18b694866b5fb0467600ab8f2a7ed1f9a6517a [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
10import time
11import platform
12from errno import EACCES, EPERM
Peter D Phan0c669772021-06-24 13:52:42 -050013import subprocess
Peter D Phan72ce6b82021-06-03 06:18:26 -050014from ssh_utility import SSHRemoteclient
15
16
17class FFDCCollector:
18
19 r"""
20 Sends commands from configuration file to the targeted system to collect log files.
21 Fetch and store generated files at the specified location.
22
23 """
24
Peter D Phan04aca3b2021-06-21 10:37:18 -050025 # List of supported OSes.
26 supported_oses = ['OPENBMC', 'RHEL', 'AIX', 'UBUNTU']
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,
35 remote_protocol):
Peter D Phan72ce6b82021-06-03 06:18:26 -050036 r"""
37 Description of argument(s):
38
39 hostname name/ip of the targeted (remote) system
40 username user on the targeted system with access to FFDC files
41 password password for user on targeted system
42 ffdc_config configuration file listing commands and files for FFDC
Peter D Phan04aca3b2021-06-21 10:37:18 -050043 location where to store collected FFDC
44 remote_type os type of the remote host
Peter D Phan72ce6b82021-06-03 06:18:26 -050045
46 """
47 if self.verify_script_env():
48 self.hostname = hostname
49 self.username = username
50 self.password = password
51 self.ffdc_config = ffdc_config
52 self.location = location
53 self.remote_client = None
54 self.ffdc_dir_path = ""
55 self.ffdc_prefix = ""
Peter D Phan04aca3b2021-06-21 10:37:18 -050056 self.target_type = remote_type.upper()
Peter D Phan0c669772021-06-24 13:52:42 -050057 self.remote_protocol = remote_protocol.upper()
Peter D Phan72ce6b82021-06-03 06:18:26 -050058 else:
Peter D Phan8462faf2021-06-16 12:24:15 -050059 sys.exit(-1)
Peter D Phan72ce6b82021-06-03 06:18:26 -050060
61 def verify_script_env(self):
62
63 # Import to log version
64 import click
65 import paramiko
66
67 run_env_ok = True
Peter D Phan0c669772021-06-24 13:52:42 -050068
69 redfishtool_version = self.run_redfishtool('-V').split(' ')[2]
70
Peter D Phan72ce6b82021-06-03 06:18:26 -050071 print("\n\t---- Script host environment ----")
72 print("\t{:<10} {:<10}".format('Script hostname', os.uname()[1]))
73 print("\t{:<10} {:<10}".format('Script host os', platform.platform()))
74 print("\t{:<10} {:>10}".format('Python', platform.python_version()))
75 print("\t{:<10} {:>10}".format('PyYAML', yaml.__version__))
76 print("\t{:<10} {:>10}".format('click', click.__version__))
77 print("\t{:<10} {:>10}".format('paramiko', paramiko.__version__))
Peter D Phan0c669772021-06-24 13:52:42 -050078 print("\t{:<10} {:>10}".format('redfishtool', redfishtool_version))
Peter D Phan72ce6b82021-06-03 06:18:26 -050079
Peter D Phan8462faf2021-06-16 12:24:15 -050080 if eval(yaml.__version__.replace('.', ',')) < (5, 4, 1):
81 print("\n\tERROR: Python or python packages do not meet minimum version requirement.")
82 print("\tERROR: PyYAML version 5.4.1 or higher is needed.\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -050083 run_env_ok = False
84
85 print("\t---- End script host environment ----")
86 return run_env_ok
87
88 def target_is_pingable(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -050089 r"""
90 Check if target system is ping-able.
91
92 """
93 response = os.system("ping -c 1 -w 2 %s 2>&1 >/dev/null" % self.hostname)
94 if response == 0:
George Keishing615fe322021-06-24 01:24:36 -050095 print("\n\t[Check] %s is ping-able.\t\t [OK]" % self.hostname)
Peter D Phan72ce6b82021-06-03 06:18:26 -050096 return True
97 else:
98 print("\n>>>>>\tERROR: %s is not ping-able. FFDC collection aborted.\n" % self.hostname)
99 sys.exit(-1)
100
Peter D Phan04aca3b2021-06-21 10:37:18 -0500101 def inspect_target_machine_type(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500102 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500103 Inspect remote host os-release or uname.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500104
105 """
Peter D Phan04aca3b2021-06-21 10:37:18 -0500106 command = "cat /etc/os-release"
107 response = self.remoteclient.execute_command(command)
108 if response:
109 print("\n\t[INFO] %s /etc/os-release\n" % self.hostname)
Peter D Phan0c42a942021-06-29 09:17:27 -0500110 for each_info in response:
111 print("\t\t %s" % each_info)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500112 identity = self.find_os_type(response, 'ID').split('=')[1].upper()
113 else:
114 response = self.remoteclient.execute_command('uname -a')
115 print("\n\t[INFO] %s uname -a\n" % self.hostname)
116 print("\t\t %s" % ' '.join(response))
117 identity = self.find_os_type(response, 'AIX').split(' ')[0].upper()
Peter D Phan2b8052d2021-06-22 10:55:41 -0500118
119 # If OS does not have /etc/os-release and is not AIX,
120 # script does not yet know what to do.
Peter D Phan04aca3b2021-06-21 10:37:18 -0500121 if not identity:
122 print(">>>>>\tERROR: Script does not yet know about %s" % ' '.join(response))
123 sys.exit(-1)
124
Peter D Phan0c669772021-06-24 13:52:42 -0500125 if (self.target_type not in identity):
126
Peter D Phan04aca3b2021-06-21 10:37:18 -0500127 user_target_type = self.target_type
Peter D Phan2b8052d2021-06-22 10:55:41 -0500128 self.target_type = ""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500129 for each_os in FFDCCollector.supported_oses:
130 if each_os in identity:
131 self.target_type = each_os
132 break
Peter D Phan2b8052d2021-06-22 10:55:41 -0500133
134 # If OS in not one of ['OPENBMC', 'RHEL', 'AIX', 'UBUNTU']
135 # script does not yet know what to do.
136 if not self.target_type:
137 print(">>>>>\tERROR: Script does not yet know about %s" % identity)
138 sys.exit(-1)
139
Peter D Phan04aca3b2021-06-21 10:37:18 -0500140 print("\n\t[WARN] user request %s does not match remote host type %s.\n"
141 % (user_target_type, self.target_type))
142 print("\t[WARN] FFDC collection continues for %s.\n" % self.target_type)
143
144 def find_os_type(self,
145 listing_from_os,
146 key):
147
148 r"""
149 Return OS information with the requested key
150
151 Description of argument(s):
152
153 listing_from_os list of information returns from OS command
154 key key of the desired data
155
156 """
157
158 for each_item in listing_from_os:
159 if key in each_item:
160 return each_item
161 return ''
Peter D Phan72ce6b82021-06-03 06:18:26 -0500162
163 def collect_ffdc(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500164 r"""
165 Initiate FFDC Collection depending on requested protocol.
166
167 """
168
George Keishing772c9772021-06-16 23:23:42 -0500169 print("\n\t---- Start communicating with %s ----" % self.hostname)
170 working_protocol_list = []
Peter D Phan72ce6b82021-06-03 06:18:26 -0500171 if self.target_is_pingable():
George Keishing772c9772021-06-16 23:23:42 -0500172 # Check supported protocol ping,ssh, redfish are working.
173 if self.ssh_to_target_system():
174 working_protocol_list.append("SSH")
George Keishing615fe322021-06-24 01:24:36 -0500175 working_protocol_list.append("SCP")
Peter D Phan0c669772021-06-24 13:52:42 -0500176
177 # Redfish
178 if self.verify_redfish():
179 working_protocol_list.append("REDFISH")
180 print("\n\t[Check] %s Redfish Service.\t\t [OK]" % self.hostname)
181 else:
182 print("\n\t[Check] %s Redfish Service.\t\t [FAILED]" % self.hostname)
183
Peter D Phan72ce6b82021-06-03 06:18:26 -0500184 # Verify top level directory exists for storage
185 self.validate_local_store(self.location)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500186 self.inspect_target_machine_type()
George Keishing772c9772021-06-16 23:23:42 -0500187 print("\n\t---- Completed protocol pre-requisite check ----\n")
Peter D Phan0c669772021-06-24 13:52:42 -0500188
189 if ((self.remote_protocol not in working_protocol_list) and (self.remote_protocol != 'ALL')):
190 print("\n\tWorking protocol list: %s" % working_protocol_list)
191 print(
192 '>>>>>\tERROR: Requested protocol %s is not in working protocol list.\n'
193 % self.remote_protocol)
194 sys.exit(-1)
195 else:
196 self.generate_ffdc(working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500197
198 def ssh_to_target_system(self):
199 r"""
200 Open a ssh connection to targeted system.
201
202 """
203
204 self.remoteclient = SSHRemoteclient(self.hostname,
205 self.username,
206 self.password)
207
208 self.remoteclient.ssh_remoteclient_login()
George Keishing772c9772021-06-16 23:23:42 -0500209 print("\n\t[Check] %s SSH connection established.\t [OK]" % self.hostname)
Peter D Phan733df632021-06-17 13:13:36 -0500210
211 # Check scp connection.
212 # If scp connection fails,
213 # continue with FFDC generation but skip scp files to local host.
214 self.remoteclient.scp_connection()
George Keishing772c9772021-06-16 23:23:42 -0500215 return True
Peter D Phan72ce6b82021-06-03 06:18:26 -0500216
George Keishing772c9772021-06-16 23:23:42 -0500217 def generate_ffdc(self, working_protocol_list):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500218 r"""
Peter D Phan04aca3b2021-06-21 10:37:18 -0500219 Determine actions based on remote host type
Peter D Phan72ce6b82021-06-03 06:18:26 -0500220
Peter D Phan04aca3b2021-06-21 10:37:18 -0500221 Description of argument(s):
222 working_protocol_list list of confirmed working protocols to connect to remote host.
Peter D Phan72ce6b82021-06-03 06:18:26 -0500223 """
224
George Keishing772c9772021-06-16 23:23:42 -0500225 print("\n\t---- Executing commands on " + self.hostname + " ----")
226 print("\n\tWorking protocol list: %s" % working_protocol_list)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500227 with open(self.ffdc_config, 'r') as file:
228 ffdc_actions = yaml.load(file, Loader=yaml.FullLoader)
229
Peter D Phan2b8052d2021-06-22 10:55:41 -0500230 # Set prefix values for scp files and directory.
231 # Since the time stamp is at second granularity, these values are set here
232 # to be sure that all files for this run will have same timestamps
233 # and they will be saved in the same directory.
234 # self.location == local system for now
235 self.set_ffdc_defaults()
236
Peter D Phan72ce6b82021-06-03 06:18:26 -0500237 for machine_type in ffdc_actions.keys():
Peter D Phan72ce6b82021-06-03 06:18:26 -0500238
Peter D Phan04aca3b2021-06-21 10:37:18 -0500239 if machine_type == self.target_type:
Peter D Phan0c669772021-06-24 13:52:42 -0500240 if self.remote_protocol == 'SSH' or self.remote_protocol == 'ALL':
241 self.protocol_ssh(ffdc_actions, machine_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500242
Peter D Phan0c669772021-06-24 13:52:42 -0500243 if self.target_type == 'OPENBMC':
244 if self.remote_protocol == 'REDFISH' or self.remote_protocol == 'ALL':
245 self.protocol_redfish(ffdc_actions, 'OPENBMC_REDFISH')
Peter D Phan72ce6b82021-06-03 06:18:26 -0500246
Peter D Phan04aca3b2021-06-21 10:37:18 -0500247 # Close network connection after collecting all files
248 self.remoteclient.ssh_remoteclient_disconnect()
249
Peter D Phan0c669772021-06-24 13:52:42 -0500250 def protocol_ssh(self,
251 ffdc_actions,
252 machine_type):
253 r"""
254 Perform actions using SSH and SCP protocols.
255
256 Description of argument(s):
257 ffdc_actions List of actions from ffdc_config.yaml.
258 machine_type OS Type of remote host.
259 """
260
261 # For OPENBMC collect general system info.
262 if self.target_type == 'OPENBMC':
263
264 self.collect_and_copy_ffdc(ffdc_actions['GENERAL'],
265 form_filename=True)
266 self.group_copy(ffdc_actions['OPENBMC_DUMPS'])
267
268 # For RHEL and UBUNTU, collect common Linux OS FFDC.
269 if self.target_type == 'RHEL' \
270 or self.target_type == 'UBUNTU':
271
272 self.collect_and_copy_ffdc(ffdc_actions['LINUX'])
273
274 # Collect remote host specific FFDC.
275 self.collect_and_copy_ffdc(ffdc_actions[machine_type])
276
277 def protocol_redfish(self,
278 ffdc_actions,
279 machine_type):
280 r"""
281 Perform actions using Redfish protocol.
282
283 Description of argument(s):
284 ffdc_actions List of actions from ffdc_config.yaml.
285 machine_type OS Type of remote host.
286 """
287
288 print("\n\t[Run] Executing commands to %s using %s" % (self.hostname, 'REDFISH'))
289 redfish_files_saved = []
290 progress_counter = 0
291 list_of_URL = ffdc_actions[machine_type]['URL']
292 for index, each_url in enumerate(list_of_URL, start=0):
293 redfish_parm = '-u ' + self.username + ' -p ' + self.password + ' -r ' \
294 + self.hostname + ' -S Always raw GET ' + each_url
295
296 result = self.run_redfishtool(redfish_parm)
297 if result:
298 try:
299 targ_file = ffdc_actions[machine_type]['FILES'][index]
300 except IndexError:
301 targ_file = each_url.split('/')[-1]
302 print("\n\t[WARN] Missing filename to store data from redfish URL %s." % each_url)
303 print("\t[WARN] Data will be stored in %s." % targ_file)
304
305 targ_file_with_path = (self.ffdc_dir_path
306 + self.ffdc_prefix
307 + targ_file)
308
309 # Creates a new file
310 with open(targ_file_with_path, 'w') as fp:
311 fp.write(result)
312 fp.close
313 redfish_files_saved.append(targ_file)
314
315 progress_counter += 1
316 self.print_progress(progress_counter)
317
318 print("\n\t[Run] Commands execution completed.\t\t [OK]")
319
320 for file in redfish_files_saved:
321 print("\n\t\tSuccessfully save file " + file + ".")
322
Peter D Phan04aca3b2021-06-21 10:37:18 -0500323 def collect_and_copy_ffdc(self,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500324 ffdc_actions_for_machine_type,
325 form_filename=False):
Peter D Phan04aca3b2021-06-21 10:37:18 -0500326 r"""
327 Send commands in ffdc_config file to targeted system.
328
329 Description of argument(s):
330 ffdc_actions_for_machine_type commands and files for the selected remote host type.
Peter D Phan2b8052d2021-06-22 10:55:41 -0500331 form_filename if true, pre-pend self.target_type to filename
Peter D Phan04aca3b2021-06-21 10:37:18 -0500332 """
333
334 print("\n\t[Run] Executing commands on %s using %s"
335 % (self.hostname, ffdc_actions_for_machine_type['PROTOCOL'][0]))
336 list_of_commands = ffdc_actions_for_machine_type['COMMANDS']
337 progress_counter = 0
338 for command in list_of_commands:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500339 if form_filename:
340 command = str(command % self.target_type)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500341 self.remoteclient.execute_command(command)
342 progress_counter += 1
343 self.print_progress(progress_counter)
344
345 print("\n\t[Run] Commands execution completed.\t\t [OK]")
346
347 if self.remoteclient.scpclient:
348 print("\n\n\tCopying FFDC files from remote system %s.\n" % self.hostname)
Peter D Phan2b8052d2021-06-22 10:55:41 -0500349
Peter D Phan04aca3b2021-06-21 10:37:18 -0500350 # Retrieving files from target system
351 list_of_files = ffdc_actions_for_machine_type['FILES']
Peter D Phan2b8052d2021-06-22 10:55:41 -0500352 self.scp_ffdc(self.ffdc_dir_path, self.ffdc_prefix, form_filename, list_of_files)
Peter D Phan04aca3b2021-06-21 10:37:18 -0500353 else:
354 print("\n\n\tSkip copying FFDC files from remote system %s.\n" % self.hostname)
355
Peter D Phan56429a62021-06-23 08:38:29 -0500356 def group_copy(self,
357 ffdc_actions_for_machine_type):
358
359 r"""
360 scp group of files (wild card) from remote host.
361
362 Description of argument(s):
363 ffdc_actions_for_machine_type commands and files for the selected remote host type.
364 """
365 if self.remoteclient.scpclient:
George Keishing615fe322021-06-24 01:24:36 -0500366 print("\n\tCopying DUMP files from remote system %s.\n" % self.hostname)
Peter D Phan56429a62021-06-23 08:38:29 -0500367
368 # Retrieving files from target system, if any
369 list_of_files = ffdc_actions_for_machine_type['FILES']
370
371 for filename in list_of_files:
372 command = 'ls -AX ' + filename
373 response = self.remoteclient.execute_command(command)
374 # self.remoteclient.scp_file_from_remote() completed without exception,
375 # if any
376 if response:
377 scp_result = self.remoteclient.scp_file_from_remote(filename, self.ffdc_dir_path)
378 if scp_result:
379 print("\t\tSuccessfully copied from " + self.hostname + ':' + filename)
380 else:
381 print("\t\tThere is no " + filename)
382
383 else:
384 print("\n\n\tSkip copying files from remote system %s.\n" % self.hostname)
385
Peter D Phan72ce6b82021-06-03 06:18:26 -0500386 def scp_ffdc(self,
387 targ_dir_path,
Peter D Phan2b8052d2021-06-22 10:55:41 -0500388 targ_file_prefix,
389 form_filename,
Peter D Phan72ce6b82021-06-03 06:18:26 -0500390 file_list=None,
391 quiet=None):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500392 r"""
393 SCP all files in file_dict to the indicated directory on the local system.
394
395 Description of argument(s):
396 targ_dir_path The path of the directory to receive the files.
397 targ_file_prefix Prefix which will be pre-pended to each
398 target file's name.
399 file_dict A dictionary of files to scp from targeted system to this system
400
401 """
402
Peter D Phan72ce6b82021-06-03 06:18:26 -0500403 progress_counter = 0
404 for filename in file_list:
Peter D Phan2b8052d2021-06-22 10:55:41 -0500405 if form_filename:
406 filename = str(filename % self.target_type)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500407 source_file_path = filename
408 targ_file_path = targ_dir_path + targ_file_prefix + filename.split('/')[-1]
409
410 # self.remoteclient.scp_file_from_remote() completed without exception,
411 # add file to the receiving file list.
412 scp_result = self.remoteclient.scp_file_from_remote(source_file_path, targ_file_path)
Peter D Phan72ce6b82021-06-03 06:18:26 -0500413
414 if not quiet:
415 if scp_result:
Peter D Phan8462faf2021-06-16 12:24:15 -0500416 print("\t\tSuccessfully copied from " + self.hostname + ':' + source_file_path + ".\n")
Peter D Phan72ce6b82021-06-03 06:18:26 -0500417 else:
418 print("\t\tFail to copy from " + self.hostname + ':' + source_file_path + ".\n")
419 else:
420 progress_counter += 1
421 self.print_progress(progress_counter)
422
Peter D Phan72ce6b82021-06-03 06:18:26 -0500423 def set_ffdc_defaults(self):
Peter D Phan72ce6b82021-06-03 06:18:26 -0500424 r"""
425 Set a default value for self.ffdc_dir_path and self.ffdc_prefix.
426 Collected ffdc file will be stored in dir /self.location/hostname_timestr/.
427 Individual ffdc file will have timestr_filename.
428
429 Description of class variables:
430 self.ffdc_dir_path The dir path where collected ffdc data files should be put.
431
432 self.ffdc_prefix The prefix to be given to each ffdc file name.
433
434 """
435
436 timestr = time.strftime("%Y%m%d-%H%M%S")
437 self.ffdc_dir_path = self.location + "/" + self.hostname + "_" + timestr + "/"
438 self.ffdc_prefix = timestr + "_"
439 self.validate_local_store(self.ffdc_dir_path)
440
441 def validate_local_store(self, dir_path):
442 r"""
443 Ensure path exists to store FFDC files locally.
444
445 Description of variable:
446 dir_path The dir path where collected ffdc data files will be stored.
447
448 """
449
450 if not os.path.exists(dir_path):
451 try:
452 os.mkdir(dir_path, 0o755)
453 except (IOError, OSError) as e:
454 # PermissionError
455 if e.errno == EPERM or e.errno == EACCES:
456 print('>>>>>\tERROR: os.mkdir %s failed with PermissionError.\n' % dir_path)
457 else:
458 print('>>>>>\tERROR: os.mkdir %s failed with %s.\n' % (dir_path, e.strerror))
459 sys.exit(-1)
460
461 def print_progress(self, progress):
462 r"""
463 Print activity progress +
464
465 Description of variable:
466 progress Progress counter.
467
468 """
469
470 sys.stdout.write("\r\t" + "+" * progress)
471 sys.stdout.flush()
472 time.sleep(.1)
Peter D Phan0c669772021-06-24 13:52:42 -0500473
474 def verify_redfish(self):
475 r"""
476 Verify remote host has redfish service active
477
478 """
479 redfish_parm = '-u ' + self.username + ' -p ' + self.password + ' -r ' \
480 + self.hostname + ' -S Always raw GET /redfish/v1/'
481 return(self.run_redfishtool(redfish_parm, True))
482
483 def run_redfishtool(self,
484 parms_string,
485 quiet=False):
486 r"""
487 Run CLI redfishtool
488
489 Description of variable:
490 parms_string redfishtool subcommand and options.
491 quiet do not print redfishtool error message if True
492 """
493
494 result = subprocess.run(['redfishtool ' + parms_string],
495 stdout=subprocess.PIPE,
496 stderr=subprocess.PIPE,
497 shell=True,
498 universal_newlines=True)
499
500 if result.stderr and not quiet:
501 print('\n\t\tERROR with redfishtool ' + parms_string)
502 print('\t\t' + result.stderr)
503
504 return result.stdout