#!/usr/bin/env python
'''
Plugin to monitor performance of eaccelerator module for PHP.

To use: 
1. Copy script to munin plugins folder
2. Symbolically link to eacc_memory and eacc_cached
   * eacc_memory shows memory usage
   * eacc_cached shows number of scripts cached and discarded
3. Set configuration options in munin config file as follows
[eacc_*]
env.auth_user username
env.auth_pwd password
env_cpanel url_of_stats.php
4. Copy stats.php into the eacc control panel folder and set $user/$pw to match auth_user/auth_pwd
   * Ideally, these should be the same values as set in control.php
5. Run `munin-run eacc_memory` and `munin-run eacc_cached` to make sure scripts are running correctly, you should see non-zero values
6. Restart munin-node

This script's homepage: https://github.com/hermzz/munin-eaccelerator-plugin
eAccelerator homepage: http://eaccelerator.net/
'''
import sys, os

command_vars = {
    'memory': ['memorysize', 'memoryallocated'],
    'cached': ['cachedscripts', 'removedscripts']
}

config = {
    'memory':
            'graph_title eacceleratory memory usage\n' +
            'graph_info This graph shows memory performance of PHP eaccelerator module\n' +
            'graphs_args -1 0\n' +
            'graph_category webserver\n' +
            
            'memorysize.label total\n' +
            'memorysize.draw AREA\n' +
            'memorysize.min 0\n' +
            'memorysize.info Total memory\n' +
            
            'memoryallocated.label allocated\n' +
            'memoryallocated.draw LINE1\n' +
            'memoryallocated.min 0\n' +
            'memoryallocated.info Memory allocated',
    'cached': 
            'graph_title eacceleratory cached scripts\n' +
            'graph_info This graph shows how many scripts are cached by PHP eaccelerator module\n' +
            'graphs_args -1 0\n' +
            'graph_category webserver\n' +
            
            'cachedscripts.label cached scripts\n' +
            'cachedscripts.draw LINE1\n' +
            'cachedscripts.min 0\n' +
            'cachedscripts.info Cached scripts\n' +
            
            'removedscripts.label removed scripts\n' +
            'removedscripts.draw LINE1\n' +
            'removedscripts.min 0\n' +
            'removedscripts.info Removed scripts'
}

def print_config(command):
    print config[command]

def get_stats():
    fetcher = httplib2.Http()
    if 'auth_user' in os.environ and 'auth_pwd' in os.environ:
        fetcher.add_credentials(os.environ['auth_user'], os.environ['auth_pwd'])
    resp, content = fetcher.request(os.environ["cpanel"])
    
    if resp['status'] != '200':
        content = '0 0 0 0'
        
    bits = content.split(' ')
    return {'memorysize': bits[0], 'memoryallocated': bits[1], 'cachedscripts': bits[2], 'removedscripts': bits[3]}

def print_stats(command):
	stats = get_stats()
	
	for var in command_vars[command]:
	    print "%s.value %s" % (var, stats[var])

if __name__ == "__main__":
    try:
        import httplib2
    except ImportError:
        print "httplib2 not found"
        sys.exit(1)
    
    if os.environ['cpanel'] == '':
        print "env.cpanel not defined in munin config"
        sys.exit()

    underscore = sys.argv[0].find('_')
    
    if underscore == -1:
        print "Symbolically link this file to eacc_memory or eacc_cached"
        sys.exit(1)
    else:
        command = sys.argv[0][underscore+1:]
        
        if len(sys.argv) > 1 and sys.argv[1] != '':
            if sys.argv[1] == 'config':
                print_config(command)
            else:
                print "Command %s not recognized" % sys.argv[1]
                sys.exit(1)
        else:
            print_stats(command)
