#!/usr/bin/env python
import sys
import memcache
import textwrap
import os.path
import time
from nagiosplugin import *

"""
Nagios plugin for checking memcached instances. Returns detailed memcached
statistics for use by perfdata visualisation tools.

Requirements
=============

This script requires the following python modules:

  * argparse (included with python 2.7, otherwise install with 'easy_install argparse')
  * memcache (install with 'easy_install python-memcached' if easy_install is present)

Notes
=====

It's useful to monitor the following statistics:

  * uptime
  * curr_items
  * total_items
  * bytes
  * cmd_get - delta'd by time
  * get_hits - percentage of time delta
  * total_connections - delta'd by time
  * cmd_set - delta'd by time
  * get_misses - delta'd by time
  * evictions - delta'd by time
  * bytes_written - delta'd by time
"""


class MemcachedStats(NagiosPlugin):
    """
    A Nagios plugin to check memcached statistics. Statistics are returned in perfdata formate.
    The following can be monitored: bytes used, bytes written, cache hits,
    cache hits (%), cache misses, number of current items, evictions, gets, sets, total connections,
    total items, uptime.
    """
    VERSION = '0.1'
    SERVICE = 'Memcached'
    AUTHOR = 'Ally B'
    ## a constant for a special metric we calculate ourselves
    CACHE_HITS_PERCENTAGE = 'cache_hits_percentage'

    class Defaults(object):
        timeout = 3
        hostname = 'localhost'
        port = 11211
        delta_file_path = '/var/nagios/check_memcached_plugin_delta'
        delta_precision = 2

    def parse_args(self, opts):
        """
        Parse given options and arguments
        """
        parser = self._default_parser(description=self.__doc__, version=self.VERSION, author=self.AUTHOR,
            hostname=self.Defaults.hostname, port=self.Defaults.port, delta_file_path=self.Defaults.delta_file_path,
            delta_precision=self.Defaults.delta_precision)

        parser.add_argument('-s', '--statistic', nargs='?', required=True,
            help="""The statistic to check. Use one of the following keywords:
                accepting_conns
                auth_cmds
                auth_errors
                bytes
                bytes_read
                bytes_written
                cas_badval
                cas_hits
                cas_misses
                cmd_flush
                cmd_get
                cmd_set
                conn_yields
                connection_structures
                curr_connections
                curr_items
                decr_hits
                decr_misses
                delete_hits
                delete_misses
                evictions
                get_hits
                get_misses