const schedule = require('node-schedule');
const request = require("request");
const shell = require("shelljs")
const exec = require('child_process').exec;

// const express = require('express');
// const app = express();

    let appList = [
        {host:"127.0.0.1",port:"61337",httpchk:"/parse",name:"server",cmd:"pm2 restart server"},
    ]
const keepaliveTask = ()=>{
    shell.exec(`cd /opt/edu-textbook-server && pm2 start server.js -i max`,{silent:true})
    //每分钟的1-10秒都会触发，其它通配符依次类推
    schedule.scheduleJob('*/10 * * * * *', ()=>{
        appList.forEach(app=>{
            checkHttpAlive(app);
        })
    })
}
keepaliveTask()


async function checkHttpAlive(app){
    let info = shell.exec(`pm2 info ${app.name}`,{ silent: true })
    // pm2服务不存在，无需检查
    if(!info?.stdout){
        return
    }

    // pm2服务存在，判断是否正常
    jsonRequest(`http://${app.host}:${app.port}${app.httpchk}`,"GET").then(data=>{
        // console.log(data)
    }).catch(err=>{
        console.log(err)
        console.log("开始重启->"+app.host);
        let com = exec(`${app.cmd}`)
        com.stdout.on('data', function (data) {
            console.log("重启成功->"+data);
            // res();
        });

        com.stderr.on('data', function (data) {
            console.log('重启出错->' + data);
            // res();
        });
    })
}

function jsonRequest(url,method, body){
    body = body || {}
    method = method || "GET"
    return new Promise((resolve,reject)=>{
        request({
            url: url,
            method: method,
            json:true,
            headers:{
                "Content-Type": "application/json"
            },
            body:body
        },(error, response, body) => {
            if (!error && response.statusCode == 200) {
                resolve(body)
            }else{
                console.error(error)
                reject(error)
            }
        })
    })
}