keepalive.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const schedule = require('node-schedule');
  2. const request = require("request");
  3. const shell = require("shelljs")
  4. const exec = require('child_process').exec;
  5. // const express = require('express');
  6. // const app = express();
  7. let appList = [
  8. {host:"127.0.0.1",port:"61337",httpchk:"/parse",name:"server",cmd:"pm2 restart server"},
  9. ]
  10. const keepaliveTask = ()=>{
  11. shell.exec(`cd /opt/edu-textbook-server && pm2 start server.js -i max`,{silent:true})
  12. //每分钟的1-10秒都会触发,其它通配符依次类推
  13. schedule.scheduleJob('*/10 * * * * *', ()=>{
  14. appList.forEach(app=>{
  15. checkHttpAlive(app);
  16. })
  17. })
  18. }
  19. keepaliveTask()
  20. async function checkHttpAlive(app){
  21. let info = shell.exec(`pm2 info ${app.name}`,{ silent: true })
  22. // pm2服务不存在,无需检查
  23. if(!info?.stdout){
  24. return
  25. }
  26. // pm2服务存在,判断是否正常
  27. jsonRequest(`http://${app.host}:${app.port}${app.httpchk}`,"GET").then(data=>{
  28. // console.log(data)
  29. }).catch(err=>{
  30. console.log(err)
  31. console.log("开始重启->"+app.host);
  32. let com = exec(`${app.cmd}`)
  33. com.stdout.on('data', function (data) {
  34. console.log("重启成功->"+data);
  35. // res();
  36. });
  37. com.stderr.on('data', function (data) {
  38. console.log('重启出错->' + data);
  39. // res();
  40. });
  41. })
  42. }
  43. function jsonRequest(url,method, body){
  44. body = body || {}
  45. method = method || "GET"
  46. return new Promise((resolve,reject)=>{
  47. request({
  48. url: url,
  49. method: method,
  50. json:true,
  51. headers:{
  52. "Content-Type": "application/json"
  53. },
  54. body:body
  55. },(error, response, body) => {
  56. if (!error && response.statusCode == 200) {
  57. resolve(body)
  58. }else{
  59. console.error(error)
  60. reject(error)
  61. }
  62. })
  63. })
  64. }