<?php
require("../../inc/lib.inc");
//This script file is executed when login in the ems
//get the alarm number of the five alarm level
if (!session_id()) session_start();
// echo "<pre>";
// print_r($_SESSION);
// echo "</pre>";
if (isset($_SESSION["userInfo"])) {
    if (!isset($userInfo)) $userInfo = $_SESSION["userInfo"];
    $selectedLanguage = $userInfo['language'];
    $language = $userInfo['language'];
    $userName = $userInfo['ID'];
    $userPwd = $userInfo['PWD'];
    $userIp = $userInfo['IP'];
    $session_id = session_id();
    $login_time = date('Y-m-d H:i:s', $userInfo['refresh_time']);
}



$dbName = 'OMC_PUB';
$defTable = 'sysAlarmConf';
$logTable = 'sysAlarmLog';
$showSql = " SELECT  t2.alarmLevel,count(*) as number
			FROM $logTable as t1,$defTable as t2
			WHERE t1.clearTime = '0000-00-00 00:00:00' 
				AND t1.sysTypeNo = t2.sysTypeNo 
				AND t1.compCode  = t2.compCode 
				AND t1.alarmCode = t2.alarmCode
			GROUP BY t2.alarmLevel
		";

if (0) echo "<br>showSql=$showSql";
$result=@mysqli_query($pubConn,$showSql);
echo mysqli_error($pubConn);
global $alarmNumArr;
while ($rows = @mysqli_fetch_array($result)) {
    $alarmNumArr[$rows['alarmLevel']]['number'] = $rows['number'];
}
//echo "alarmNumArr=$alarmNumArr<br>";
// echo "<pre>";
// echo print_r($alarmNumArr);
// echo "</pre>";

for ($i = 1; $i <= 5; $i++) {
    if (trim($alarmNumArr[$i]['number']) == "")
        $alarmNumArr[$i]['number'] = 0;
}
$retureValue = $alarmNumArr[1]['number'] . "_" . $alarmNumArr[2]['number'] . "_" . $alarmNumArr[3]['number'] . "_" . $alarmNumArr[4]['number'] . "_" . $alarmNumArr[5]['number'];
echo "$retureValue";  ///is should


	$cpuMax=95;
    $default_user_name="agtuser";
	$sql="select pubVarValue from OMC_PUB.omcPubVarConf where pubVarName='ResourceThreshold' ";
	$res=mysqli_query($pubConn,$sql);
	$row=mysqli_fetch_array($res);
	if(strlen(trim($row['pubVarValue'])) > 0)
		$cpuMax=$row['pubVarValue'];



// 查询 CPU 使用率
$cpuSql = "SELECT sysNo, subSysNo, detailStat FROM OMC_PUB.sysStat WHERE sysTypeNo = 200 and sysNo != 0";
$cpuResult = @mysqli_query($pubConn, $cpuSql);
echo mysqli_error($pubConn);


while ($row = @mysqli_fetch_array($cpuResult)) {

    switch($row['sysNo']){
        case 0:
            $PlatName = 'EMS';
            break;
        case 3:
            $PlatName = 'HLR';
            break;
        case 5:
            $PlatName = 'PPS';
            break;
        case 6:
            $PlatName = 'SMSC';
            break; 
        case 8:
            $PlatName = 'VMS';
            break;   
        case 9:
            $PlatName = 'MSS';
            break;                                         
        default:
            $PlatName = 'MSS';
    }


    // 解析 detailStat 获取 CPU 使用率
    $baseStat = $row['detailStat'];
    $compStat = substr($baseStat, 38);
    $compStatLen = strlen($compStat) - 1;

    $index = 0;
    $i = 0;
    while ($i < $compStatLen) {
        $tmp = substr($compStat, $i, 4);
        $component[$index]['ID'] = $tmp + 0;
        $i += 4;

        $tmp = substr($compStat, $i, 4);
        $component[$index]['Length'] = hexdec($tmp);
        $i += 4;

        $component[$index]['Content'] = substr($compStat, $i, $component[$index]['Length'] * 2);
        $i += $component[$index]['Length'] * 2;

        $index++;
    }

    // 获取组件 8 的内容并计算 CPU 使用率
    if ($component[8]['Length'] > 0) {
        $snmp_hb = $component[8]['Content'];
        //Start Time
        $pos=0;
		$tmpValue=hexdec(substr($snmp_hb,$pos,8));
		
		$startTime=date("Y-m-d H:i:s",$tmpValue);
		$pos+=8;
		
		//GET CPU Use Rate
        $cpuValue = 100 - hexdec(substr($snmp_hb, $pos, 2)); // 计算 CPU 使用率

        // 初始化计数器（针对每个 sysNo 和 subSysNo）
        if (!isset($_SESSION['cpu_high_count'])) {
            $_SESSION['cpu_high_count'] = []; // 初始化为数组
        }

        if (!isset($_SESSION['cpu_high_count'][$row['sysNo']])) {
            $_SESSION['cpu_high_count'][$row['sysNo']] = []; // 初始化 sysNo 的子数组
        }

        if (!isset($_SESSION['cpu_high_count'][$row['sysNo']][$row['subSysNo']])) {
            $_SESSION['cpu_high_count'][$row['sysNo']][$row['subSysNo']] = 0; // 初始化计数器
        }

        // 判断 CPU 使用率是否超过 95%
        if ($cpuValue > $cpuMax) {
            $_SESSION['cpu_high_count'][$row['sysNo']][$row['subSysNo']]++; // 增加计数
        } else {
            $_SESSION['cpu_high_count'][$row['sysNo']][$row['subSysNo']] = 0; // 重置计数
            // 检查是否存在未清除的告警
            $clearSql = "UPDATE sysAlarmInfo 
            SET clearTime = CURRENT_TIMESTAMP, clearMode = 0,clearBy = 'System'  
            WHERE sysTypeNo = '200' 
            AND sysNo = '{$row['sysNo']}' 
            AND subSysNo = '{$row['subSysNo']}' 
            AND alarmCode = '999' 
            AND clearTime = '0000-00-00 00:00:00'";
        mysqli_query($pubConn, $clearSql);
        echo mysqli_error($pubConn);
        }

        // 如果连续 6 次超过 95%，触发告警
        if ($_SESSION['cpu_high_count'][$row['sysNo']][$row['subSysNo']] >= 6) {
            $alarmInfo = "$PlatName-CPU usage exceeded 95% for 1 minute"; // 告警描述
            $alarmSql = "INSERT INTO sysAlarmInfo (sysTypeNo, sysNo, subSysNo, compCode, alarmCode, alarmTime, clearTime, clearMode, alarmInfo) 
                         VALUES ('200', '{$row['sysNo']}', '{$row['subSysNo']}', '0', '999', CURRENT_TIMESTAMP, '0000-00-00 00:00:00', 1, '$alarmInfo')";
            mysqli_query($pubConn, $alarmSql);
            echo mysqli_error($pubConn);

            // 重置计数器
            $_SESSION['cpu_high_count'][$row['sysNo']][$row['subSysNo']] = 0;
        }



        //CPU Use Rate Process Num
		$pos+=2;
		
		//Physical Memory Used/Total
		$tmpValue=hexdec(substr($snmp_hb,$pos,8));
		$pos+=8;
		$tmpValue1=hexdec(substr($snmp_hb,$pos,8));
		$pos+=8;
		$tmpValue2=floor(($tmpValue/$tmpValue1)*100);

		//$plat[PMTotalRate][Value]="{$tmpValue2}%";
		
		//$plat[PMTotalRateV][Value]=(floor($tmpValue/1024))."M/".(floor($tmpValue1/1024))."M";
		
		//$plat[PMTotalRatePN][Value]=floor($tmpValue2/10);
		
		//Physical Memory Used/Swap
		$tmpValue=hexdec(substr($snmp_hb,$pos,8));
		$pos+=8;
		$tmpValue1=hexdec(substr($snmp_hb,$pos,8));
		$pos+=8;
		$tmpValue2=floor(($tmpValue/$tmpValue1)*100);
		
		//$plat[PMSwapRate][Value]="{$tmpValue2}%";
		
		//$plat[PMSwapRateV][Value]=(floor($tmpValue/1024))."M/".(floor($tmpValue1/1024))."M";
		
		//$plat[PMSwapRatePN][Value]=floor($tmpValue2/10);
		
		//Physical Memory Buffers
		$tmpValue=hexdec(substr($snmp_hb,$pos,8));
		$pos+=8;
		//$plat[PMBuffers][Value]=(floor($tmpValue/1024))."M";
		
		//Physical Memory Cached
		$tmpValue=hexdec(substr($snmp_hb,$pos,8));
		$pos+=8;
		//$plat[PMCached][Value]=(floor($tmpValue/1024))."M";
		
		//Harddisk
		$tmpValue=hexdec(substr($snmp_hb,$pos,2));
		$pos+=2;
		//$plat[HDNum]=$tmpValue;
		for($i=0;$i<$plat[HDNum];$i++)
		{
			$tmpValue=hexdec(substr($snmp_hb,$pos,2));
			$pos+=2;
			$path_len=$tmpValue;
			$path="";
			for($j=0;$j<$path_len;$j++)
			{
				$path.=chr(hexdec(substr($snmp_hb,$pos,2)));
				$pos+=2;
			}
			//$plat[HD][$i][Path][Value]="($path)";
			//$plat[HD][$i][Path][Color]="#000000";
			//$plat[HD][$i][Path][Display]="block";
			
			$tmpValue=hexdec(substr($snmp_hb,$pos,8));
			$pos+=8;
			$tmpValue1=hexdec(substr($snmp_hb,$pos,8));
			$pos+=8;
			
			$tmpValue2=floor(($tmpValue/$tmpValue1)*100);
			//$plat[HD][$i][PN][Value]=floor($tmpValue2/10);
			//$plat[HD][$i][PN][Color]="#0000ff";
			//$plat[HD][$i][PN][Display]="Rect";
			
			//$plat[HD][$i][V][Value]=(floor($tmpValue/1024))."M/".(floor($tmpValue1/1024))."M";
			//$plat[HD][$i][V][Color]="#000000";
			//$plat[HD][$i][V][Display]="block";
			
			//$plat[HD][$i][Rate][Value]="{$tmpValue2}%";
			//$plat[HD][$i][Rate][Color]="#000000";
			//$plat[HD][$i][Rate][Display]="block";
		}
    }



}




?>

