master
Raw Download raw file
 1"use strict";
 2
 3var http = require('http');
 4var underscore = require('underscore');
 5
 6var checkServers = exports.checkServers = function (array, success, error) {
 7  var upCount = 0,
 8      errored = false,
 9      target,
10      i;
11  for (i = 0; i < array.length; i++) {
12    check(
13      array[i],
14      function () {
15        upCount += 1;
16        if (upCount === array.length) {
17          success();
18        }
19      },
20      function () {
21        if (errored === false) {
22          errored = true;
23          error();
24        }
25      }
26    );
27  }
28}
29
30var check = exports.check = function (connectionOptions, success, error) {
31  var baseOptions = {
32    path: "/",
33    method: 'HEAD'
34  };
35  var options = underscore.extend(baseOptions, connectionOptions);
36  var request = http.request(options, function (response) {
37    response.on('data', function () {
38      return;
39    });
40    response.on('end', function () {
41      if (response.statusCode === 200) {
42        console.log("Upstream server is up.");
43        success();
44      } else if (response.statusCode === 400) {
45        console.log("400 response code. We may be using the wrong secret.");
46        error();
47      } else if (response.statusCode === 500) {
48        console.log("500 response code. Shield may be failing to come up.");
49        error();
50      } else {
51        console.log("Unexpected response code %s.", response.statusCode);
52        error();
53      }
54    });
55  });
56
57  request.setTimeout(1000, function (socket) {
58      console.log("Timeout checking backend. The backend is probably down.");
59      request.abort();
60  });
61
62  request.on("error", function (err) {
63    console.log("Error checking backend. The immediate upstream is probably down.");
64    error();
65  });
66
67  request.end();
68};
69
70var checkWithBackoff = exports.checkWithBackoff = function (connectionOptions, success, failure, attempts, backoff) {
71  var attempts,
72      backoff = backoff || 500; // ms
73  if (attempts === undefined) {
74    attempts = 4;
75  }
76  console.log("Checking if backends are up.");
77  var failedTry = function () {
78    if (attempts >= 1) {
79      // Try again, doubling the backoff time
80      setTimeout(
81        checkWithBackoff,
82        backoff,
83        connectionOptions,
84        success,
85        failure,
86        attempts - 1,
87        backoff * 2
88      );
89    } else {
90      failure();
91    }
92  };
93  check(connectionOptions, success, failedTry);
94};