# -*- coding: UTF-8 -*-
from common.baseFactory import *
from common import resourceParse

def execute(dataDict):

    ##执行升级前检查
    return preCheck(dataDict)
    
def disposeRecs(recs, dataDict):
    lang = dataDict['lang']
    resource = resourceParse.execute(lang)
    upgradeErrMsg = ''
    itemState = True
    NORMAL_MEMORY = 100 #内存阈值，低于该值不通过
    MAX_CPUUSAGE = 50   #CPU利用率阈值，大于等于该值不通过。
    
    if recs is None:
        log.info(dataDict,"[SysResourceCheck]records is none") 
        upgradeErrMsg = resource.get('SysResourceCheck.error')   
        return (False, upgradeErrMsg, None)
    
    recNum = recs.size()
    pattern = re.compile('^[0-9]+,[0-9]+$')
    for index in range(0, recNum):
        
        rec = recs.get(index)
        nodeId = rec.getParamStrValue(0)
        result = rec.getParamStrValue(1)
        log.info(dataDict,"[SysResourceCheck]get node system resource[nodeId:%s, result:%s]" %(nodeId,result))
        if (result == "TimeOut"):
            #执行超时
            itemState = False
            errorKey = "SysResourceCheck.timeout"
            upgradeErrMsg += getUpgErrMsg(resource,nodeId,errorKey)
            continue
        
        if re.match(pattern, result.strip()) is None:
            log.info(dataDict,"[SysResourceCheck]record is not normal")  
            itemState = False
            errorKey = "SysResourceCheck.error" 
            upgradeErrMsg += getUpgErrMsg(resource,nodeId,errorKey)
            continue
        
        resInfo = result.split(",")    
        cpuUsage =  int(resInfo[0])
        memoryRemain = int(resInfo[1])
        if (cpuUsage < MAX_CPUUSAGE) and (memoryRemain >= NORMAL_MEMORY):
            errorKey = "SysResourceCheck.pass" 
            upgradeErrMsg += getUpgErrMsg(resource,nodeId,errorKey)        
        else:
            itemState = False
            errorKey = "SysResourceCheck.notpass"
            upgradeErrMsg += getUpgErrMsg(
                resource, nodeId, errorKey,
                (cpuUsage, MAX_CPUUSAGE, memoryRemain, NORMAL_MEMORY))
                
    if not upgradeErrMsg:
        itemState = False
        upgradeErrMsg = resource.get("SysResourceCheck.error")
        
    return (itemState, upgradeErrMsg, None)

def preCheck(dataDict):
    
        recs = executeCheck(dataDict, "upd sysresourcecheck", 2)        
        return disposeRecs(recs,dataDict)
