#!/usr/bin/env python

import psutil
import pyelasticsearch
from pyelasticsearch import *
import time
from daemon import runner
import socket
import ConfigParser

# Configuration section
config = ConfigParser.ConfigParser()
config.read('psmond.cfg')

URL      = config.get('Server', 'server')
INDEX    = config.get('Settings', 'index')
DOCTYPE  = 'PS'
HOSTNAME = socket.gethostname()
ES       = ElasticSearch(URL)

class PSMonitor():
    def __init__(self):
        self.stdin_path   = '/dev/null'
        self.stdout_path  = config.get('Settings', 'stdout_path')
        self.stderr_path  = config.get('Settings', 'stderr_path')
        self.pidfile_path =  config.get('Settings', 'pidfile_path')
        self.pidfile_timeout = int(config.get('Settings', 'pidfile_timeout'))

    def update(self):
        psd = psutil.disk_io_counters()
	nsd = psutil.network_io_counters()

        doc = {
	   'hostname': HOSTNAME,
           'timestamp': time.time(),
            'io': {'read_count': psd.read_count,
	        'write_count': psd.write_count,
         	'read_bytes': psd.read_bytes,
	        'write_bytes': psd.write_bytes,
        	'read_time': psd.read_time,
            	'write_time': psd.write_time
		},
	 	
            'netio': {'bytes_sent': nsd.bytes_sent,
	        'bytes_recv': nsd.bytes_recv,
	        'packets_sent': nsd.packets_sent,
	        'packets_recv': nsd.packets_recv
		}
            }
        ES.index(INDEX, DOCTYPE, doc)

    def run(self):
        while True:
            self.update()
            time.sleep(int(config.get('Settings', 'update_interval')))

psm = PSMonitor()
daemon_runner = runner.DaemonRunner(psm)
daemon_runner.do_action()
