简体   繁体   English

node.js应用程序在AWS上停止的问题

[英]Issue with node.js app stopping on AWS

I have a node.js app that pings a url and then sends a message to Slack if it gets an error code. 我有一个ping.js应用程序ping一个网址,然后如果它得到一个错误代码,发送一条消息给Slack。 It works fine for two days but then it just stops working. 它工作正常两天,但它只是停止工作。 I'm using Screen to keep it running but it still seems to stop. 我正在使用Screen来保持运行但它似乎仍然停止。 Any help would be greatly appreciated. 任何帮助将不胜感激。

The code is below: 代码如下:

var request = require("request")
var Hapi = require('hapi');
var Slack = require('slack-node');
var h = 0;
var s = 0;
var e = 0;

function onlineBooking(){
request({
    url: "http://example.com",
    json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {

        // 'if/else' checks that it receives an up respsose four times in a row 
        // the variable e is increased by .25 for every 200(ok response) until e reaches 1
        // it will then send a message that the server is up
        if(e < 1  && response.statusCode === 200){
            setTimeout(function () {
           console.log(response.statusCode) // Print the response code
            e =e+0.25;
            }, 6000); // 6 seconds delay between each response 
        }

    else {
          while(h == 0){
        console.log(response.statusCode) // Print the response code
        console.log("********************")
        slackReviewBot("Website :robot_face: ", response.statusCode + " - OK", "http://example.com", "");
            h++;
            s = 0; 
          } 
        }// end of else
    }// end of if
    else {
        console.log(response.statusCode) // Print the response code
        e = 0;
        setTimeout(function () {  
        while(s == 0){

        console.log(response.statusCode) // Print the response code
        console.log("********************")
        slackReviewBot("Website :robot_face: ", response.statusCode, "http://example.com", "");
            s++;
            h=0;
        }}, 3000);
    } // end of else

})

}

// sets the loop for checking every 7 seconds

setInterval(function(){

    onlineBooking();

}, 7000); 


//  this function sends server name, a message and url to slack
function slackReviewBot(servername, body, urls, bod) {

var time = require('time');
// Create a new Date instance
var now = new time.Date();
now.setTimezone("Europe/London");

    var bo = body; 
    var bod = bod;
    var urls = urls;
    var sname = servername; 
    // you'll need to replace the slack webhook below
    // you'll find info on webhooks here https://api.slack.com/incoming-webhooks
    var webhook_url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxx';
    slack = new Slack();
    slack.setWebhook(webhook_url);

        slack.webhook({
        channel: "#server-uptime",
        username: "Server:",
        icon_emoji: "http://4.bp.blogspot.com/-mYCTaPOu-60/VK98X5CJEyI/AAAAAAAAApM/0oplbclvnUY/s1600/unnamed.png",
        text: " " + "\n" + 
            "*" + sname + " * " + "\n" +
            "Status: " + bo + "\n" +
            now + "\n" +
            "Check the status here: " + urls + "\n" 

        }, function(err, response) {      
        console.log(response);
        }); 
}



// below is so you can send a test json object to the server
// http POST localhost:1337/jsonpost test=Test 
// you'll get a slack message letting you know the server is running
var server = new Hapi.Server();
server.connection({
    port: 1337
});

exports.add = function(i, j) {
    return i + j;
};

//  Slack function for sending the test reply
function slackReviewBot2(testserver) {
    testserver = testserver;
      // you'll need to replace the slack webhook below
    // you'll find info on webhooks here https://api.slack.com/incoming-webhooks
    var webhook_url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxx';
    slack2 = new Slack();
    slack2.setWebhook(webhook_url);


        slack.webhook({
        channel: "#server-uptime",
        username: "Server-Test-Reply:",
        icon_emoji: "http://www.wonderfulwebsites.ie/logo.png",
        text: ":star: :star: :star: :star: :star:" + "\n" + 
            "\n" + 
            "Sever is up and running!!!"

        }, function(err, response) {

        console.log(response);
        });
}


// take the json object for testing
server.route({
  method: 'POST'
, path: '/jsonpost',
handler: function(req, reply) {

     var review = {
      userName: req.payload.userName
      }
            //passes the review to the slackbot function 
            slackReviewBot2(review.userName);
            reply("Received");
    } 
});

// prints a server running message 
server.start(function(){
    console.log('server running at: ', server.info.url);
});

You can find a post explaining how it works below http://codingyoda.com/slack-pinging-tool.php 您可以在http://codingyoda.com/slack-pinging-tool.php下找到解释其工作原理的帖子

我不知道为什么会发生这种情况,但你可以永远修复它,如果变为非活动状态或崩溃(这将取代屏幕),它将重新启动进程。

A log would definitely help us get to the root cause here - please do check your logs and post here. 日志肯定会帮助我们找到根本原因 - 请检查您的日志并在此处发布。 As other answers suggest - any production environment I would recommend the use of forever or PM2 to restart your app if it dies. 正如其他答案所暗示的那样 - 任何生产环境我建议永远使用或PM2重新启动你的应用程序,如果它死了。 As @sebastian suggests that might fix the problem if not the cause - by auto-restarting your app. 正如@sebastian建议的那样,如果不是原因可能会解决问题 - 通过自动重启你的应用程序。 Another benefit is that these apps will log your console messages to file - which will give you (and us) a better idea of what's going on. 另一个好处是,这些应用程序会将您的控制台消息记录到文件中 - 这将使您(和我们)更好地了解正在发生的事情。

One more thought: you may be dealing with an uncaught exception. 还有一个想法:你可能正在处理未被捕获的异常。 If you think this is happening you could add a bit of code to catch, report and even shutdown gracefully. 如果您认为这种情况正在发生,您可以添加一些代码来捕获,报告甚至优雅地关闭。 George Ornbo wrote a great article on this here that I'd recommend you read when considering what to do with these exceptions. George Ornbo在这里写了一篇很棒的文章,我建议你在考虑如何处理这些异常时阅读。

Here's an overly-simplified code sample to catch uncaught exceptions that should capture the error and more importantly the stack-trace that you'll need to track down where the problem originates (assuming you capture those logs): 这是一个过于简化的代码示例,用于捕获应捕获错误的未捕获异常,更重要的是,您需要跟踪问题源自的堆栈跟踪(假设您捕获这些日志):

//catches uncaught exceptions
process.on('uncaughtException', function (err) {
    console.trace("Uncaught Exception", err);
    gracefulShutdown(err);
});

// implementation beyond the scope of this question. 
function gracefulShutdown(error) {
    process.exit(error);
} 

I hope that helps! 我希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM