import subprocess, shlex
import whatap.pack as pack
import whatap.pack.smbase_pack as smbase_pack
import time, os
from StringIO import StringIO

def executeCmd(command='getconf CLK_TCK'):
    process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
    buf = StringIO()
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
            break
        buf.write(output)

    return buf.getvalue()

oldVmstat = None
tckTime = float(executeCmd())

import multiprocessing
cpucore = float(multiprocessing.cpu_count())

def DEPRECATED_GetCpuMemory():
    vmstat = getVmStat()

    global oldVmstat
    if not oldVmstat:
        oldVmstat = vmstat
        return None, None, None

    millsdiff  = vmstat['created'] - oldVmstat['created']

    c = smbase_pack.CpuLinux()

    def calcTickPerSec(key):
        return 100.0 * float(vmstat['%s cpu ticks'%key] - oldVmstat['%s cpu ticks'%key]) / tckTime / float(millsdiff) / cpucore

    c.user = calcTickPerSec('non-nice user')
    c.system = calcTickPerSec('system')
    #print vmstat['idle cpu ticks'], oldVmstat['idle cpu ticks'], vmstat['idle cpu ticks'] - oldVmstat['idle cpu ticks'] 
    #print 'time diff ',vmstat['created'], oldVmstat['created']
    c.idle = calcTickPerSec('idle')
    c.nice = calcTickPerSec('nice user')
    c.irq = calcTickPerSec('IRQ')
    c.softirq = calcTickPerSec('softirq')
    c.steal = calcTickPerSec('stolen')
    c.iowait = calcTickPerSec('IO-wait')
    c.load1 = 0
    c.load5 = 0
    c.load15 = 0

    memoryInfo = vmstat
    p = smbase_pack.MemoryLinux()
    p.total = memoryInfo['total memory']
    p.free = memoryInfo['free memory']
    p.cached = memoryInfo['inactive memory']
    p.used = memoryInfo['active memory']
    p.pused = float(p.used) / float(p.total) * 100.0
    p.available = 0
    p.pavailable = 0

    p.buffers = memoryInfo['buffer memory']
    p.shared = 0

    p.swapUsed = memoryInfo['used swap']
    if float(memoryInfo['total swap']) > 0 :
        p.swapPused = 100.0* float(memoryInfo['used swap']) / float(memoryInfo['total swap'])
    else:
        p.swapPused = 0
    p.swapTotal = memoryInfo['total swap']
    p.pageFault = 0

    uptime= int(time.time()) - int(vmstat['boot time']/1024.0)
    #print 'cpu_memory', int(time.time()) , int(vmstat['boot time']/1024.0), uptime
    return c, p, uptime

import psutil
def GetCpuMemory():
    jiff = float(100)

    cpu_times = psutil.cpu_times(percpu=False)
    global oldVmstat
    if not oldVmstat:
        oldVmstat = cpu_times
        return None, None, None

    c = smbase_pack.CpuLinux()
    all_cpu = cpu_times.user + cpu_times.nice + cpu_times.idle + cpu_times.irq
    last_all_cpu = oldVmstat.user + oldVmstat.nice + oldVmstat.idle + oldVmstat.irq
    cpu_diff = float(all_cpu - last_all_cpu)
    c.user = jiff * float(cpu_times.user - oldVmstat.user) / cpu_diff
    c.system = jiff * float(cpu_times.system - oldVmstat.system) / cpu_diff
    c.iowait = jiff * float(cpu_times.iowait - oldVmstat.iowait) / cpu_diff
    c.idle = jiff * float(cpu_times.idle - oldVmstat.idle) / cpu_diff
    c.nice = jiff * float(cpu_times.nice - oldVmstat.nice) / cpu_diff
    c.irq = jiff * float(cpu_times.irq - oldVmstat.irq) / cpu_diff
    c.softirq = jiff * float(cpu_times.softirq - oldVmstat.softirq) / cpu_diff
    c.steal = jiff * float(cpu_times.steal - oldVmstat.steal) / cpu_diff
    c.load1, c.load5, c.load15= os.getloadavg()

    oldVmstat = cpu_times
    vmem = psutil.virtual_memory()

    p = smbase_pack.MemoryLinux()
    p.total = vmem.total
    p.free = vmem.free
    p.cached = vmem.cached
    p.buffers = vmem.buffers
    p.used = vmem.total - vmem.buffers - vmem.free - vmem.cached
    p.pused = float(p.used) / float(p.total) * 100.0
    p.available = vmem.available
    p.pavailable = p.available / p.total * 100.0

    p.shared = vmem.shared

    swapmem = psutil.swap_memory()
    p.swapUsed = swapmem.used
    p.swapTotal = swapmem.total
    if p.swapTotal > 0:
        p.swapPused = 100.0* float(p.swapUsed) / float(p.swapTotal)
    else:
        p.swapPused = 0

    p.pageFault = 0

    uptime= int(time.time()) - int(psutil.boot_time())
    #print 'cpu_memory', int(time.time()) , int(vmstat['boot time']/1024.0), uptime
    return c, p, uptime


def getVmStat(command="vmstat -s"):
    started=time.time()*1000
    process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
    memoryInfo = {'created': started}
    while True:
        output = process.stdout.readline().strip()
        #print 'getVmStat', output
        if not output and process.poll() is not None:
            break
        if output:
            #print 'getVmStat', output
            tokens = output.split()
            v = tokens[0]
            key = ' '.join(tokens[1:])
            memoryInfo[key]= int(v)*1024

    return memoryInfo

def test():
    GetCpuMemory()
    time.sleep(5)
    GetCpuMemory()

if __name__ == '__main__':
    test()
