2020-11-05 12:01:12 -06:00
|
|
|
#!/usr/bin/env python3
|
2019-09-13 12:50:31 -05:00
|
|
|
|
|
|
|
import os
|
|
|
|
from collections import defaultdict
|
|
|
|
from datetime import datetime
|
|
|
|
|
2020-11-05 12:01:12 -06:00
|
|
|
from sonic_py_common.logger import Logger
|
|
|
|
|
2019-09-13 12:50:31 -05:00
|
|
|
SYSLOG_IDENTIFIER = 'core_cleanup.py'
|
2020-11-05 12:01:12 -06:00
|
|
|
CORE_FILE_DIR = '/var/core/'
|
2019-09-13 12:50:31 -05:00
|
|
|
MAX_CORE_FILES = 4
|
|
|
|
|
2020-12-03 17:57:50 -06:00
|
|
|
|
2019-09-13 12:50:31 -05:00
|
|
|
def main():
|
2020-11-05 12:01:12 -06:00
|
|
|
logger = Logger(SYSLOG_IDENTIFIER)
|
|
|
|
logger.set_min_log_priority_info()
|
|
|
|
|
2019-09-13 12:50:31 -05:00
|
|
|
if os.getuid() != 0:
|
2020-11-05 12:01:12 -06:00
|
|
|
logger.log_error('Root required to clean up core files')
|
2019-09-13 12:50:31 -05:00
|
|
|
return
|
|
|
|
|
2020-11-05 12:01:12 -06:00
|
|
|
logger.log_info('Cleaning up core files')
|
2019-09-13 12:50:31 -05:00
|
|
|
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)
|
|
|
|
for f in core_files:
|
|
|
|
process = f.split('.')[0]
|
|
|
|
curr_files = core_files_by_process[process]
|
|
|
|
curr_files.append(f)
|
|
|
|
|
|
|
|
if len(curr_files) > MAX_CORE_FILES:
|
2020-12-03 17:57:50 -06:00
|
|
|
curr_files.sort(reverse=True, key=lambda x: datetime.utcfromtimestamp(int(x.split('.')[1])))
|
2019-09-13 12:50:31 -05:00
|
|
|
oldest_core = curr_files[MAX_CORE_FILES]
|
2020-11-05 12:01:12 -06:00
|
|
|
logger.log_info('Deleting {}'.format(oldest_core))
|
2019-09-13 12:50:31 -05:00
|
|
|
try:
|
|
|
|
os.remove(os.path.join(CORE_FILE_DIR, oldest_core))
|
|
|
|
except:
|
2020-11-05 12:01:12 -06:00
|
|
|
logger.log_error('Unexpected error occured trying to delete {}'.format(oldest_core))
|
2019-09-13 12:50:31 -05:00
|
|
|
core_files_by_process[process] = curr_files[0:MAX_CORE_FILES]
|
|
|
|
|
2020-11-05 12:01:12 -06:00
|
|
|
logger.log_info('Finished cleaning up core files')
|
2019-09-13 12:50:31 -05:00
|
|
|
|
2020-12-03 17:57:50 -06:00
|
|
|
|
2019-09-13 12:50:31 -05:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|