From 522a071ffb3153231d7f6465cdb21e4275164723 Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Thu, 5 Nov 2020 10:01:12 -0800 Subject: [PATCH] [core_cleanup.py] Convert to Python 3; Fix bug; Improve code reuse (#5781) - Convert to Python 3 - Fix bug: `CORE_FILE_DIR` previously was set to `os.path.basename(__file__)`, which would resolve to the script name. Fix this by hardcoding to `/var/core/` instead - Remove locally-define logging functions; use Logger class from sonic-py-common instead --- files/scripts/core_cleanup.py | 32 ++++++++++++-------------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/files/scripts/core_cleanup.py b/files/scripts/core_cleanup.py index 67620b2397..d9025a812f 100755 --- a/files/scripts/core_cleanup.py +++ b/files/scripts/core_cleanup.py @@ -1,31 +1,24 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -import syslog import os - from collections import defaultdict from datetime import datetime +from sonic_py_common.logger import Logger + SYSLOG_IDENTIFIER = 'core_cleanup.py' -CORE_FILE_DIR = os.path.basename(__file__) +CORE_FILE_DIR = '/var/core/' MAX_CORE_FILES = 4 -def log_info(msg): - syslog.openlog(SYSLOG_IDENTIFIER) - syslog.syslog(syslog.LOG_INFO, msg) - syslog.closelog() - -def log_error(msg): - syslog.openlog(SYSLOG_IDENTIFIER) - syslog.syslog(syslog.LOG_ERR, msg) - syslog.closelog() - def main(): + logger = Logger(SYSLOG_IDENTIFIER) + logger.set_min_log_priority_info() + if os.getuid() != 0: - log_error('Root required to clean up core files') + logger.log_error('Root required to clean up core files') return - log_info('Cleaning up core files') + logger.log_info('Cleaning up core files') core_files = [f for f in os.listdir(CORE_FILE_DIR) if os.path.isfile(os.path.join(CORE_FILE_DIR, f))] core_files_by_process = defaultdict(list) @@ -37,15 +30,14 @@ def main(): if len(curr_files) > MAX_CORE_FILES: curr_files.sort(reverse = True, key = lambda x: datetime.utcfromtimestamp(int(x.split('.')[1]))) oldest_core = curr_files[MAX_CORE_FILES] - log_info('Deleting {}'.format(oldest_core)) + logger.log_info('Deleting {}'.format(oldest_core)) try: os.remove(os.path.join(CORE_FILE_DIR, oldest_core)) except: - log_error('Unexpected error occured trying to delete {}'.format(oldest_core)) + logger.log_error('Unexpected error occured trying to delete {}'.format(oldest_core)) core_files_by_process[process] = curr_files[0:MAX_CORE_FILES] - log_info('Finished cleaning up core files') + logger.log_info('Finished cleaning up core files') if __name__ == '__main__': main() -