1#!/usr/bin/python 2# Copyright 2017 The Chromium Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""Utility to cleanup TKO database by removing old records. 7""" 8 9import argparse 10import logging 11import os 12import time 13 14import common 15from autotest_lib.client.bin import utils 16from autotest_lib.client.common_lib import global_config 17from autotest_lib.client.common_lib import logging_config 18 19from chromite.lib import metrics 20 21 22CONFIG = global_config.global_config 23 24# SQL command to remove old test results in TKO database. 25CLEANUP_TKO_CMD = 'call remove_old_tests_sp()' 26CLEANUP_METRICS = 'chromeos/autotest/tko_cleanup_duration' 27 28 29def parse_options(): 30 """Parse command line inputs. 31 32 @return: Options to run the script. 33 """ 34 parser = argparse.ArgumentParser() 35 parser.add_argument('-l', '--logfile', type=str, 36 default=None, 37 help='Path to the log file to save logs.') 38 return parser.parse_args() 39 40 41def main(): 42 """Main script.""" 43 options = parse_options() 44 log_config = logging_config.LoggingConfig() 45 if options.logfile: 46 log_config.add_file_handler( 47 file_path=os.path.abspath(options.logfile), level=logging.DEBUG) 48 49 server = CONFIG.get_config_value( 50 'AUTOTEST_WEB', 'global_db_host', 51 default=CONFIG.get_config_value('AUTOTEST_WEB', 'host')) 52 user = CONFIG.get_config_value( 53 'AUTOTEST_WEB', 'global_db_user', 54 default=CONFIG.get_config_value('AUTOTEST_WEB', 'user')) 55 password = CONFIG.get_config_value( 56 'AUTOTEST_WEB', 'global_db_password', 57 default=CONFIG.get_config_value('AUTOTEST_WEB', 'password')) 58 database = CONFIG.get_config_value( 59 'AUTOTEST_WEB', 'global_db_database', 60 default=CONFIG.get_config_value('AUTOTEST_WEB', 'database')) 61 62 logging.info('Start cleaning up old records in TKO database %s on server ' 63 '%s.', database, server) 64 65 start_time = time.time() 66 try: 67 utils.run_sql_cmd(server, user, password, CLEANUP_TKO_CMD, database) 68 except: 69 logging.exception('Cleanup failed with exception.') 70 finally: 71 duration = time.time() - start_time 72 metrics.SecondsDistribution(CLEANUP_METRICS).add( 73 duration, fields={'server': server}) 74 logging.info('Cleanup finished in %s seconds.', duration) 75 76 77if __name__ == '__main__': 78 main() 79