1#!/usr/bin/python2
2# Copyright (c) 2014 The Chromium OS 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"""This script will run optimize table for chromeos_autotest_db
7
8This script might have notable impact on the mysql performance as it locks
9tables and rebuilds indexes. So be careful when running it on production
10systems.
11"""
12
13import argparse
14import logging
15import socket
16import subprocess
17import sys
18
19import common
20from autotest_lib.frontend import database_settings_helper
21from autotest_lib.server import utils
22
23# Format Appears as: [Date] [Time] - [Msg Level] - [Message]
24LOGGING_FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
25STATS_KEY = 'db_optimize.%s' % socket.gethostname()
26
27def main_without_exception_handling():
28    database_settings = database_settings_helper.get_default_db_config()
29    command = ['mysqlcheck',
30               '-o', database_settings['NAME'],
31               '-u', database_settings['USER'],
32               '-p%s' % database_settings['PASSWORD'],
33               # we want to do db optimation on each master/slave
34               # in rotation. Do not write otimize table to bin log
35               # so that it won't be picked up by slaves automatically
36               '--skip-write-binlog',
37               ]
38    subprocess.check_call(command)
39
40
41def should_optimize():
42    """Check if the server should run db_optimize.
43
44    Only shard should optimize db.
45
46    @returns: True if it should optimize db otherwise False.
47    """
48    return utils.is_shard()
49
50
51def parse_args():
52    """Parse command line arguments"""
53    parser = argparse.ArgumentParser()
54    parser.add_argument('-c', '--check_server', action='store_true',
55                        help='Check if the server should optimize db.')
56    return parser.parse_args()
57
58
59def main():
60    """Main."""
61    args = parse_args()
62
63    logging.basicConfig(level=logging.INFO, format=LOGGING_FORMAT)
64    logging.info('Calling: %s', sys.argv)
65
66    if args.check_server and not should_optimize():
67        print 'Only shard can run db optimization.'
68        return
69
70    try:
71        main_without_exception_handling()
72    except Exception as e:
73        message = 'Uncaught exception; terminating db_optimize.'
74        logging.exception(message)
75        raise
76    logging.info('db_optimize completed.')
77
78
79if __name__ == '__main__':
80    main()
81