
from whatap.value.map_value import MapValue
import whatap.util.process_util as process_util
from whatap.util.date_util import DateUtil
import whatap.agent.conf.configure as config

embededScripts = {
    "ip addr show": "ifconfig -a",
	"netstat -an":  "netstat -an",
	"uname -a":     "uname -a",
	"ps -ef":       "ps -ef",
	"ps -aux":      "ps -aux",
	"pid limit":    "plimit %s",
	"ulimit -a":    "/usr/bin/sh -c \"ulimit -a\"",
}

class ExecutionCache(object):
    def __init__(self, content, timestamp):
        self.content = content
        self.timestamp = timestamp

executionCache = {}

def getCommandList():
    m = MapValue()
    for k, v in embededScripts.items():
        m.put(k, v)

    return m

def execute(scriptSlot , args):
    m = MapValue()
    if scriptSlot in embededScripts:
        fullcmd = embededScripts[scriptSlot]
        if args:
            options= []
            for i in range(args.size()):
                options.append(args.getString(i))
            fullcmd= fullcmd%tuple(options)
        now = DateUtil.now()
        conf = config.GetConfig()
        if fullcmd in executionCache and now - executionCache[fullcmd].timestamp < conf.ExecutionScriptCacheTimeout:
            return executionCache[fullcmd].content
        return_code, output = process_util.executeCmdEx(fullcmd)
        if return_code == 0:
            m.putString("stdout", output)
            executionCache[fullcmd] = ExecutionCache(m, now)
        else:
            m.putString("err", output)

    else:
        m.putString("err", "script %s doesn't exists"%( scriptSlot))

    return m