"""
The MIT License

Copyright (c) 2008 Gilad Raphaelli <gilad@raphaelli.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

###  Changelog:
###    v1.0.0 - 2012-05-18
###       * Brighthouse columnar database "Infobright" module, derived from mysqld module
###

###  Requires:
###       * yum install Infobright-python

###  Copyright Bob Webber, 2012
###  License to use, modify, and distribute under the GPL
###  http://www.gnu.org/licenses/gpl.txt

import time
import MySQLdb
import logging

descriptors = []

logging.basicConfig(level=logging.ERROR, format="%(asctime)s - %(name)s - %(levelname)s\t Thread-%(thread)d - %(message)s", filename='/tmp/infobrightstats.log', filemode='w')
logging.debug('starting up')

last_update = 0
infobright_conn_opts = {}
infobright_stats = {}
infobright_stats_last = {}
delta_per_second = False

REPORT_BRIGHTHOUSE = True
REPORT_BRIGHTHOUSE_ENGINE = False
REPORT_MASTER = True
REPORT_SLAVE  = True

MAX_UPDATE_TIME = 15

def update_stats(get_brighthouse=True, get_brighthouse_engine=True, get_master=True, get_slave=True):
	"""

	"""
	logging.debug('updating stats')
	global last_update
	global infobright_stats, infobright_stats_last

	cur_time = time.time()
	time_delta = cur_time - last_update
	if time_delta <= 0:
		#we went backward in time.
		logging.debug(" system clock set backwards, probably ntp")

	if cur_time - last_update < MAX_UPDATE_TIME:
		logging.debug(' wait ' + str(int(MAX_UPDATE_TIME - (cur_time - last_update))) + ' seconds')
		return True
	else:
		last_update = cur_time

	logging.debug('refreshing stats')
	infobright_stats = {}

	# Get info from DB
	try:
		conn = MySQLdb.connect(**infobright_conn_opts)

		cursor = conn.cursor(MySQLdb.cursors.DictCursor)
		cursor.execute("SELECT GET_LOCK('gmetric-infobright', 0) as ok")
		lock_stat = cursor.fetchone()
		cursor.close()

		if lock_stat['ok'] == 0:
			return False

		# infobright variables have 'brighthouse_ib_' or 'brighthouse_ini_' prefix
		cursor = conn.cursor(MySQLdb.cursors.Cursor)
		cursor.execute("SHOW VARIABLES")
		#variables = dict(((k.lower(), v) for (k,v) in cursor))
		variables = {}
		for (k,v) in cursor:
			variables[k.lower()] = v
		cursor.close()

		# infobright status values have 'bh_gdc_' or 'bh_mm_' prefix
		cursor = conn.cursor(MySQLdb.cursors.Cursor)
		# cursor.execute("SHOW /*!50002 GLOBAL */ STATUS")
		cursor.execute("SHOW GLOBAL STATUS")
		#global_status = dict(((k.lower(), v) for (k,v) in cursor))
		global_status = {}
		for (k,v) in cursor:
			# print k, v
			global_status[k.lower()] = v
		cursor.close()

		# try not to fail ?
		# BRIGHTHOUSE ENGINE status variables are pretty obscure
		get_brighthouse_engine = get_brighthouse_engine and variables.has_key('brighthouse_ini_controlmessages')
		get_master = get_master and variables['log_bin'].lower() == 'on'

		if get_brighthouse_engine:
			logging.warn('get_brighthouse_engine status not implemented')
			
		master_logs = tuple
		if get_master:
			cursor = conn.cursor(MySQLdb.cursors.Cursor)
			cursor.execute("SHOW MASTER LOGS")
			master_logs = cursor.fetchall()
			cursor.close()

		slave_status = {}
		if get_slave:
			cursor = conn.cursor(MySQLdb.cursors.DictCursor)
			cursor.execute("SHOW SLAVE STATUS")
			res = cursor.fetchone()
			if res:
				for (k,v) in res.items():
					slave_status[k.lower()] = v
			else:
				get_slave = False
			cursor.close()

		cursor = conn.cursor(MySQLdb.cursors.DictCursor)
		cursor.execute("SELECT RELEASE_LOCK('gmetric-infobright') as ok")
		cursor.close()

		conn.close()
	except MySQLdb.OperationalError, (errno, errmsg):
		logging.error('error updating stats')
		logging.error(errmsg)
		return False

	# process variables
	# http://dev.infobright.com/doc/refman/5.0/en/server-system-variables.html
	infobright_stats['version'] = variables['version']
	infobright_stats['max_connections'] = variables['max_connections']
	infobright_stats['query_cache_size'] = variables['query_cache_size']

	# process mysql status
	# http://www.infobright.com/
	interesting_mysql_status_vars = (
		'aborted_clients',
		'aborted_connects',
		'binlog_cache_disk_use',
		'binlog_cache_use',
		'bytes_received',
		'bytes_sent',
		'com_delete',
		'com_delete_multi',
		'com_insert',
		'com_insert_select',
		'com_load',
		'com_replace',
		'com_replace_select',
		'com_select',
		'com_update',
		'com_update_multi',
		'connections',
		'created_tmp_disk_tables',
		'created_tmp_files',
		'created_tmp_tables',
		'key_reads',
		'key_read_requests',
		'key_writes',
		'key_write_requests',
		'max_used_connections',
		'open_files',
		'open_tables',
		'opened_tables',
		'qcache_free_blocks',
		'qcache_free_memory',
		'qcache_hits',
		'qcache_inserts',
		'qcache_lowmem_prunes',
		'qcache_not_cached',
		'qcache_queries_in_cache',
		'qcache_total_blocks',
		'questions',
		'select_full_join',
		'select_full_range_join',
		'select_range',
		'select_range_check',
		'select_scan',
		'slave_open_temp_tables',
		'slave_retried_transactions',
		'slow_launch_threads',
		'slow_queries',
		'sort_range',
		'sort_rows',
		'sort_scan',
		'table_locks_immediate',
		'table_locks_waited',
		'threads_cached',
		'threads_connected',
		'threads_created',
		'threads_running',
		'uptime',
	)

	non_delta_mysql_status_vars = (
		'max_used_connections',
		'open_files',
		'open_tables',
		'qcache_free_blocks',
		'qcache_free_memory',
		'qcache_total_blocks',
		'slave_open_temp_tables',
		'threads_cached',
		'threads_connected',
		'threads_running',
		'uptime'