import time
import whatap.pack.tagcount_pack as tagcount_pack 
import whatap.osinfo as osinfo
import whatap.agent.secure.security_master as secure

class TaskInfraKernel:
    KERNEL = "infra_kernel"
    KERNEL_RUNQUEUE = "runq"
    KERNEL_BLOCKQUEUE = "blockq"
    KERNEL_PENDINGQUEUE = "pendingq"
    KERNEL_WAITQUEUE = "waitq"
    KERNEL_FORK = "fork"
    KERNEL_EXEC = "exec"
    KERNEL_INTERRUPT = "interrupt"
    KERNEL_SYSTEMCALL = "syscall"
    KERNEL_CONTEXTSWITCH = "ctxswitch"

    def __init__(self, interval = 2):
        self.intervalValue = interval
        self.recType = 1

    def interval(self):
        return self.intervalValue

    def process(self, os_, pcode, oid, now):
        kernel = osinfo.GetCpuStat()

        if not kernel:
            return None

        secu = secure.GetSecurityMaster()
        p = tagcount_pack.TagCountPack()
        p.pcode = pcode
        p.oid = oid
        p.time = now
        p.category = TaskInfraKernel.KERNEL
        p.putTag("oname", str(secu.oname))
        p.putTag("!rectype", str(self.recType))

        p.put(TaskInfraKernel.KERNEL_RUNQUEUE, kernel.runqueue)
        p.put(TaskInfraKernel.KERNEL_BLOCKQUEUE, kernel.blockqueue)
        if kernel.waitqueue != osinfo.CPUStat.UNSUPPORTED:
            p.put(TaskInfraKernel.KERNEL_WAITQUEUE, kernel.waitqueue)
        if kernel.pendingqueue != osinfo.CPUStat.UNSUPPORTED:
            p.put(TaskInfraKernel.KERNEL_PENDINGQUEUE, kernel.pendingqueue)
        p.put(TaskInfraKernel.KERNEL_FORK, kernel.forkCount)
        p.put(TaskInfraKernel.KERNEL_EXEC, kernel.execCount)
        p.put(TaskInfraKernel.KERNEL_INTERRUPT, kernel.interrupt)
        p.put(TaskInfraKernel.KERNEL_SYSTEMCALL, kernel.syscall)
        p.put(TaskInfraKernel.KERNEL_CONTEXTSWITCH, kernel.ctx)

        return p
