<commit_before>"""
Server Density plugin
MySQL

https://www.serverdensity.com/plugins/mysql/
https://github.com/serverdensity/sd-agent-plugins/

version: 0.1
"""
import traceback
import re

try:
    import MySQLdb
except ImportError:
    pass

# com commands.
COMMANDS = [
    'Com_select',
    'Com_delete',
    'Com_update',
    'Com_commit',
    'Questions',
    'Com_rollback',
    'Handler_commit',
    'Handler_delete',
    'Handler_delete',
    'Handler_update',
    'Handler_write',
    'Handler_rollback',
    'Handler_read_first',
    'Handler_read_rnd',
]


class MySQL(object):

    def __init__(self, agent_config, checks_logger, raw_config):
        self.agent_config = agent_config
        self.checks_logger = checks_logger
        self.raw_config = raw_config
        self.connection = None
        self.datastore = {}

    def version_is_above_5(self, status):
        if (int(status['version'][0]) >= 5 and
                int(status['version'][2]) >= 2):
            return True
        else:
            return False

    def get_db_results(self, db, query):
        cursor = db.cursor()
        try:
            cursor.execute(query)
            results = float(cursor.fetchone()[1])
        except ValueError:
            cursor.execute(query)
            results = cursor.fetchone()[1]
        return results

    def run_query(self, db, query):
        """Run a query and returns a dictionary with results"""
        try:
            cursor = db.cursor()
            cursor.execute(query)
            metric = {}
            for entry in cursor:
                try:
                    metric[entry[0]] = float(entry[1])
                except ValueError as e:
                    metric[entry[0]] = entry[1]

            return metric
        except MySQLdb.OperationalError as message:
            self.checks_logger.debug(
                'mysql: MySQL query error when getting metrics = '.format(
                    message)
                )

    def calculate_per_s(self, command, result):
        if (not self.datastore.get(command) and
                self.datastore.get(command) != 0):
            self.checks_logger.debug(
                'mysql: Datastore unset for '
                '{}, storing for first time'.format(command))
            self.datastore[command] = result
            com_per_s = 0
        else:
            com_per_s = (result - self.datastore[command]) / 60
            if com_per_s < 0:
                com_per_s = 0
            self.datastore[command] = result
        return com_per_s

    def preliminaries(self):
        if ('MySQLServer' not in self.raw_config and
                'mysql_server' not in self.raw_config['MySQLServer'] or
                self.raw_config['MySQLServer']['mysql_server'] == '' or
                self.raw_config['MySQLServer']['mysql_user'] == '' or
                self.raw_config['MySQLServer']['mysql_pass'] == ''):
            self.checks_logger.debug('mysql: config not set')
            return False

        if not self.raw_config['MySQLServer'].get('mysql_port'):
            self.raw_config['MySQLServer']['mysql_port'] = "3306"

        self.checks_logger.debug('mysql: config set')

        try:
            import MySQLdb
        except ImportError:
            self.checks_logger.error('mysql: unable to import MySQLdb')
            return False

        # Note, code here doesn't really make sense. See what I copied.
        if self.raw_config['MySQLServer'].get('mysql_server'):
            # Connect
            try:
                MySQLdb.connect(
                    host=self.raw_config['MySQLServer']['mysql_server'],
                    user=self.raw_config['MySQLServer']['mysql_user'],
                    passw=self.raw_config['MySQLServer']['mysql_pass'],
                    port=int(self.raw_config['MySQLServer']['mysql_port'])
                    )
            except MySQLdb.OperationalError as message:
                self.checks_logger.error(
                    "mysql: MySQL connection error: {}".format(message))
                return False
        elif (self.raw_config['MySQLServer'].get('mysql_ssl_cert') and
                self.raw_config['MySQLServer'].get('mysql_ssl_key')):
            ssl = {
                'cert': self.raw_config['MySQLServer']['mysql_ssl_cert'],
                'key': self.raw_config['MySQLServer']['mysql_ssl_key']
            }
            MySQLdb.connect(
                host=self.raw_config['MySQLServer']['mysql_server'],
                user=self.raw_config['MySQLServer']['mysql_user'],
                passwd=self.raw_config['MySQLServer']['mysql_pass'],
                port=int(self.raw_config['MySQLServer']['mysql_port']),
                ssl=ssl
            )
        else:
            # Connect
            try:
                MySQLdb.connect(
                    host='localhost',
                    user=self.raw_config['MySQLServer']['mysql_user'],
                    passwd=self.raw_config['MySQLServer']['mysql_pass'],
                    port=int(self.raw_config['MySQLServer']['mysql_port']))
            except MySQLdb.OperationalError as message:
                self.checks_logger.error(<commit_msg>Correcting keyword argument for MySQL connect<commit_after>"""
Server Density plugin
MySQL

https://www.serverdensity.com/plugins/mysql/
https://github.com/serverdensity/sd-agent-plugins/

version: 0.1
"""
import traceback
import re

try:
    import MySQLdb
except ImportError:
    pass

# com commands.
COMMANDS = [
    'Com_select',
    'Com_delete',
    'Com_update',
    'Com_commit',
    'Questions',
    'Com_rollback',
    'Handler_commit',
    'Handler_delete',
    'Handler_delete',
    'Handler_update',
    'Handler_write',
    'Handler_rollback',
    'Handler_read_first',
    'Handler_read_rnd',
]


class MySQL(object):

    def __init__(self, agent_config, checks_logger, raw_config):
        self.agent_config = agent_config
        self.checks_logger = checks_logger
        self.raw_config = raw_config
        self.connection = None
        self.datastore = {}

    def version_is_above_5(self, status):
        if (int(status['version'][0]) >= 5 and
                int(status['version'][2]) >= 2):
            return True
        else:
            return False

    def get_db_results(self, db, query):
        cursor = db.cursor()
        try:
            cursor.execute(query)
            results = float(cursor.fetchone()[1])
        except ValueError:
            cursor.execute(query)
            results = cursor.fetchone()[1]
        return results

    def run_query(self, db, query):
        """Run a query and returns a dictionary with results"""
        try:
            cursor = db.cursor()
            cursor.execute(query)
            metric = {}
            for entry in cursor:
                try:
                    metric[entry[0]] = float(entry[1])
                except ValueError as e:
                    metric[entry[0]] = entry[1]

            return metric
        except MySQLdb.OperationalError as message:
            self.checks_logger.debug(
                'mysql: MySQL query error when getting metrics = '.format(
                    message)
                )

    def calculate_per_s(self, command, result):
        if (not self.datastore.get(command) and
                self.datastore.get(command) != 0):
            self.checks_logger.debug(
                'mysql: Datastore unset for '
                '{}, storing for first time'.format(command))
            self.datastore[command] = result
            com_per_s = 0
        else:
            com_per_s = (result - self.datastore[command]) / 60
            if com_per_s < 0:
                com_per_s = 0
            self.datastore[command] = result
        return com_per_s

    def preliminaries(self):
        if ('MySQLServer' not in self.raw_config and
                'mysql_server' not in self.raw_config['MySQLServer'] or
                self.raw_config['MySQLServer']['mysql_server'] == '' or
                self.raw_config['MySQLServer']['mysql_user'] == '' or
                self.raw_config['MySQLServer']['mysql_pass'] == ''):
            self.checks_logger.debug('mysql: config not set')
            return False

        if not self.raw_config['MySQLServer'].get('mysql_port'):
            self.raw_config['MySQLServer']['mysql_port'] = "3306"

        self.checks_logger.debug('mysql: config set')

        try:
            import MySQLdb
        except ImportError:
            self.checks_logger.error('mysql: unable to import MySQLdb')
            return False

        # Note, code here doesn't really make sense. See what I copied.
        if self.raw_config['MySQLServer'].get('mysql_server'):
            # Connect
            try:
                MySQLdb.connect(
                    host=self.raw_config['MySQLServer']['mysql_server'],
                    user=self.raw_config['MySQLServer']['mysql_user'],
                    passwd=self.raw_config['MySQLServer']['mysql_pass'],
                    port=int(self.raw_config['MySQLServer']['mysql_port'])
                    )
            except MySQLdb.OperationalError as message:
                self.checks_logger.error(
                    "mysql: MySQL connection error: {}".format(message))
                return False
        elif (self.raw_config['MySQLServer'].get('mysql_ssl_cert') and
                self.raw_config['MySQLServer'].get('mysql_ssl_key')):
            ssl = {
                'cert': self.raw_config['MySQLServer']['mysql_ssl_cert'],
                'key': self.raw_config['MySQLServer']['mysql_ssl_key']
            }
            MySQLdb.connect(
                host=self.raw_config['MySQLServer']['mysql_server'],
                user=self.raw_config['MySQLServer']['mysql_user'],
                passwd=self.raw_config['MySQLServer']['mysql_pass'],
                port=int(self.raw_config['MySQLServer']['mysql_port']),
                ssl=ssl
            )
        else:
            # Connect
            try:
                MySQLdb.connect(
                    host='localhost',
                    user=self.raw_config['MySQLServer']['mysql_user'],
                    passwd=self.raw_config['MySQLServer']['mysql_pass'],
                    port=int(self.raw_config['MySQLServer']['mysql_port']))
            except MySQLdb.OperationalError as message:
                self.checks_logger.error(
{'fraction_non_alphanumeric': 0.11464234277484397, 'fraction_numerical': 0.00441670667306769, 'mean_word_length': 1.87893864013267, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '54341', 'n_tokens_mistral': 2967, 'n_tokens_neox': 2809, 'n_words': 546}