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

CMD_DEFAULT_TIMEOUT = 60



#磁盘利用率的最大值和平均值的阈值定义
G_MaxDiskUsage = 80
G_AvgDiskUsage = 60
Pattern = re.compile('^[0-9]+[,]*[0-9]*')

def execute(dataDict):

    ##执行升级前检查
    return preCheck(dataDict)

"""
    查询升级检查项，并更新界面
"""
def disposeRecs(recs, dataDict):
    lang = dataDict['lang']
    resource = resourceParse.execute(lang)
    upgradeErrMsg = ''
    itemState = True
    
    if recs is None or recs.size() == 0:
        return (False, resource.get("DiskUsageCheck.error"), None)
    
    recNum = recs.size()
    for index in range(0, recNum):
        rec = recs.get(index)
        nodeId = rec.getParamStrValue(0)
        result = rec.getParamStrValue(1)
        log.info(dataDict,"[DiskUsageCheck]diskUsage info of node:[nodeId:%s, result:%s]" % (nodeId,unicode(result)))
        (nodeStatus, errorKey, params) = checkState(result)
        itemState = itemState and nodeStatus
        upgradeErrMsg += getUpgErrMsg(resource, nodeId, errorKey, params)
    if not itemState:
        upgradeErrMsg += resource.get("DiskUsageCheck.suggestion")
    return (itemState, upgradeErrMsg, None)

"""
    执行升级前检查，并更新界面
"""
def preCheck(dataDict):
    recs = executeCheck(dataDict, "upd diskusagecheck", 2)
    return disposeRecs(recs, dataDict)

        
"""      
将获取的结果作处理，返回升级状态和错误码key。
"""        
def checkState(diskUsage):
    #结果超时处理流程
    if diskUsage.upper() == "TIMEOUT":
        return (False, "DiskUsageCheck.timeout", "")
    
    if re.match(Pattern, diskUsage.strip()) is None:
        return (False, "DiskUsageCheck.error", "")

    diskUsageStrList = diskUsage.split(",")
    diskUsageList = [int(usage) for usage in diskUsageStrList]
    
    #结果正常处理流程
    usage = diskUsageList[0]
    avgUsage = 0
    
    #兼容只有最大磁盘利用率场景
    if len(diskUsageList) > 1:
        avgUsage = diskUsageList[1]

    if usage <= G_MaxDiskUsage and avgUsage <= G_AvgDiskUsage:
        return (True, "DiskUsageCheck.pass", "")
    
    return (False, "DiskUsageCheck.notpass",
            (usage, G_MaxDiskUsage, avgUsage, G_AvgDiskUsage))
