# Copyright (C) 2005-2025 Splunk Inc. All Rights Reserved. import os from shutil import copyfile from migration.utils import remove_file, remove_folder from ITOA.setup_logging import getLogger class VersionMismatchFileFixer: ''' class that is used to remove files that do not belong to the current itsi version. Typically used to remove old files which still remain(side effect of untar approach) after the new spl is untarred. But this can be used for any files of your choice . ''' backup_folder_name = '.bkup' def __init__(self, list_of_paths, logger=None): ''' @type list_of_paths: list @param list_of_paths: list of paths ''' self.list_of_paths = list_of_paths if logger: self.logger = logger else: self.logger = getLogger() def remove_files(self): if self.list_of_paths and isinstance(self.list_of_paths, (list, tuple)): for path in self.list_of_paths: if not os.path.isfile(path): self.logger.info("{} is not a file".format(path)) continue try: remove_file(path, self.logger) except OSError as os_error: # if the file cannot be removed say due to permission issue, its appropriate to throw error and # return false indicating that the step failed. # but the permission denied error is rarest of rare as it is usual to expect a user who does # app install/upgrade/migrate to have read/write access to folders inside $SPLUNK_HOME self.logger.exception(os_error) return False except Exception: self.logger.error('Failed to remove older Java archive files') return False try: self.remove_backup_folder(self.list_of_paths[0]) except OSError as os_error: # if the folder cannot be removed say due to permission issue, its appropriate to throw error and # return false indicating that the step failed. # but the permission denied error is rarest of rare as it is usual to expect a user who does # app install/upgrade/migrate to have read/write access to folders inside $SPLUNK_HOME self.logger.exception(os_error) return False except Exception: self.logger.error('Failed to remove older Java archive files') return False else: self.logger.info("list_of_paths to be deleted was either None or not one of (list, tuple)") return True def get_backup_dir_path(self, file_path): backup_dir_path = os.path.join(os.path.dirname(file_path), VersionMismatchFileFixer.backup_folder_name) return backup_dir_path def remove_backup_folder(self, backup_path): backup_dir_path = self.get_backup_dir_path(backup_path) if os.path.exists(backup_dir_path): remove_folder(backup_dir_path, self.logger) def execute(self): execution_status = self.remove_files() # if there was any problem during start of services again, it will be raised as Exception return execution_status