#include "dogcore.h"
#include "writeshm.h"

DogCore::DogCore(QObject *parent) : QObject(parent)
{
    logThread = new LogThread(this);
    logThread->start();
    isWorking = false;

    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(time_out()));
    for(int i=0;i<5;i++)
        chkTime[i] = QDateTime::currentDateTime().toTime_t();
}

unsigned int DogCore::chkrootprocmem(QString proname)
{
    FILE *f1=NULL,*f2=NULL;
    int pid, vmrss;
    char buff[512],name[64];
    QString cmd = QString("pgrep %1 -u root").arg(proname);
    f1 = popen(cmd.toUtf8().data(),"r");
    if(f1==NULL)
        return 0;
    if(NULL == fgets(buff,512,f1)){
        pclose(f1);
        return 0;
    }
    pid = atoi(buff);
    pclose(f1);
    QString filename = QString("/proc/%1/status").arg(pid);
    f2 = fopen(filename.toUtf8().data(),"r");
    if(NULL == f2)
        return 0;
    for(int i=0;i<16;i++)
        fgets(buff,512,f2);
    fgets(buff,512,f2);
    sscanf(buff,"%s %d",name,&vmrss);
    fclose(f2);
    return (vmrss>>10);
}

void DogCore::time_out()
{
    if(!isWorking){
        isWorking = true;
        uint chkTime1 = QDateTime::currentDateTime().toTime_t();

        if((chkTime1-chkTime[1])>300){
            chkTime[1]=chkTime1;
            if(chkrootprocmem("ytDataWriteProcess")>300){
                logThread->appendData(QString("[%1 dataWriteDog %2] %3 chkrootprocmem(ytDataWriteProcess): %4")
                                      .arg(QDateTime::fromTime_t(chkTime1).toString("yyyy-MM-dd HH:mm:ss"))
                                      .arg(chkTime1)
                                      .arg(chkTime[1])
                                      .arg(chkrootprocmem("ytDataWriteProcess")));
                system("killall ytDataWriteProcess");
                sleep(1);
                system("/root/bin/ytDataWriteProcess &");
            }
        }
        if((dataWriteShm->processStatus[1].t_time>0)
                &&(static_cast<int>(chkTime1-dataWriteShm->processStatus[1].t_time)>60)){
            if(system("killall ytDataWriteProcess")!=-1){
                if(system("/root/bin/ytDataWriteProcess &")!=-1){
                    logThread->appendData(QString("[%1 dataWriteDog %2] ytDataWriteProcess time out: %3")
                                          .arg(QDateTime::fromTime_t(chkTime1).toString("yyyy-MM-dd HH:mm:ss"))
                                          .arg(chkTime1)
                                          .arg(static_cast<int>(chkTime1-dataWriteShm->processStatus[1].t_time)));
                }
            }
        }


        isWorking = false;
    }

}


void DogCore::start(){
    time_out();
    timer->start(5000);
}











