#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8
#
# Munin plugin for Percona XtraDB Cluster. Monitors values of these cluster replication variables:
# percona_queues: wsrep_local_recv_queue, wsrep_local_send_queue
# percona_flow: wsrep_flow_control_sent, wsrep_flow_control_recv
# percona_transactions: wsrep_replicated, wsrep_received
# percona_transactions_bytes: wsrep_replicated_bytes, wsrep_received_bytes
# percona_replication: wsrep_local_cert_failures, wsrep_local_bf_aborts
#
# created by Sven Schliesing
# borrowed code from mysql_aggregate_ by Igor Borodikhin
#
# License : GPLv3
#
# parsed environment variables:
# host: hostname or ip-address of Mysql server (default - localhost)
# port: port number of Mysql server (default - 3306)
# user: username to access Mysql server (default - empty)
# password: password of Mysql user (default - empty)
#
# ## Requirements
# This plugin requires pythons MySQLdb module which can be installed via easy_install.
#
# ## Installation
# Copy file to directory /usr/share/munin/plugins/ and create symbolic links for each type you wish
# to monitor:
# 	percona_flow
# 	percona_queues
# 	percona_replication
# 	percona_transactions
# 	percona_transactions_bytes
#
# Minimal config for monitoring local Percona XtraDB Cluster-Server:
#
#     [percona]
#     env.user root
#     env.password vErYsEcReT
#
#  #%# capabilities=autoconf
#  #%# family=contrib

import os
import sys
from warnings import filterwarnings

import MySQLdb
import MySQLdb.cursors

filterwarnings('ignore', category=MySQLdb.Warning)

program_name = os.path.basename(__file__)

variables = {
  'percona_queues': {
    'label': 'Queue sizes',
    'vlabel': 'size',
    'fields': ['wsrep_local_recv_queue', 'wsrep_local_send_queue']
  },
  'percona_flow': {
    'label': 'Flow control',
    'vlabel': '',
    'fields': ['wsrep_flow_control_sent', 'wsrep_flow_control_recv']
  },
  'percona_transactions': {
    'label': 'Transactions in and out',
    'vlabel': 'transactions',
    'fields': ['wsrep_replicated', 'wsrep_received']
  },
  'percona_transactions_bytes': {
    'label': 'Transactions in and out in bytes',
    'vlabel': 'bytes',
    'fields': ['wsrep_replicated_bytes', 'wsrep_received_bytes']
  },
  'percona_replication': {
    'label': 'Replication conflicts',
    'vlabel': 'conflicts',
    'fields': ['wsrep_local_cert_failures', 'wsrep_local_bf_aborts'],
  }
}

# Parse environment variables
# Mysql host
if "host" in os.environ and os.environ["host"] is not None:
    server = os.environ["host"]
else:
    server = "localhost"

# Mysql port
if "port" in os.environ and os.environ["port"] is not None:
    try:
        port = int(os.environ["port"])
    except ValueError:
        port = 3306
else:
    port = 3306

# Mysql username
if "user" in os.environ and os.environ["user"] is not None:
    login = os.environ["user"]
else:
    login = ""

# Mysql password
if "password" in os.environ and os.environ["password"] is not None:
    passw = os.environ["password"]
else:
    passw = ""

# Mysql connection handler
conn = None

label = variables[program_name]['label']
vlabel = variables[program_name]['vlabel']
fields = ["'{0}'".format(x) for x in variables[program_name]['fields']]

query = "show status where Variable_name in (%s)" % ', '.join(fields)

# Connect to mysql
try:
    conn = MySQLdb.connect(host=server, user=login, passwd=passw)
    cursor = conn.cursor()
except MySQLdb.Error as e:
    print("Error %d: %s" % (e.args[0], e.args[1]))
    sys.exit(1)


values = {}

if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
    print("yes")
elif len(sys.argv) == 2 and sys.argv[1] == "config":

    print("graph_title %s" % label)
    print("graph_vlabel %s" % vlabel)
    print("graph_category db")
    print()

    try:
        cursor.execute(query)
        results = cursor.fetchall()

        for result in results:
            print("%s_size.label %s" % (result[0], result[0]))

    except MySQLdb.Error as e:
        print("Error %d: %s" % (e.args[0], e.args[1]))

else:
    try:
        cursor.execute(query)
        results = cursor.fetchall()

        for result in results:
            print("%s_size.value %s" % (result[0], result[1]))

    except MySQLdb.Error as e:
        print("Error %d: %s" % (e.args[0], e.args[1]))

if conn:
    conn.close()
