/
vip-resp.js
116 lines (102 loc) · 2.79 KB
/
vip-resp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Generated by CoffeeScript 1.4.0
var VipStatus, fs, http, net, os, path;
path = require('path');
os = require('options-stream');
http = require('http');
net = require('net');
fs = require('fs');
VipStatus = (function() {
var response;
function VipStatus(options) {
if (options == null) {
options = {};
}
this.options = os({
check_health: function(cb) {
return process.nextTick(cb);
},
sock_path: "" + (path.dirname(process.mainModule.filename)) + "/run/" + (path.basename(process.mainModule.filename)) + "-vr.sock",
status_url: '/status.taobao',
success_body: 'success',
timeout: 2000
}, options);
this.status = this.status.bind(this);
this.force = 'auto';
this.net = null;
this.listen();
}
VipStatus.prototype.listen = function() {
var _this = this;
if (fs.existsSync(this.options.sock_path)) {
fs.unlinkSync(this.options.sock_path);
}
return this.net = net.createServer(function(conn) {
return conn.on('data', function(data) {
_this.force = data.toString().trim().toLowerCase();
if (_this.force !== 'on' && _this.force !== 'off') {
return _this.force = 'auto';
}
});
}).listen(this.options.sock_path);
};
VipStatus.prototype.close = function(cb) {
var _this = this;
if (!this.net) {
return cb(null);
}
return this.net.close(function() {
if (fs.existsSync(_this.options.sock_path)) {
return fs.unlink(_this.options.sock_path, cb);
} else {
return cb(null);
}
});
};
response = function(resp, code, phrase) {
resp.setHeader('Content-Type', 'text/plain');
resp.statusCode = code;
resp.end(phrase);
};
VipStatus.prototype.status = function(req, resp, next) {
var end, timeout,
_this = this;
end = false;
if (req.url !== this.options.status_url) {
if (resp._hasConnectPatch) {
next();
} else {
next(req, resp);
}
return;
}
if (this.force === 'on') {
response(resp, 200, this.options.success_body);
} else if (this.force === 'off') {
response(resp, 503, 'Service Unavailable');
} else {
timeout = setTimeout(function() {
if (end) {
return;
}
response(resp, 504, 'Gateway Timeout');
end = true;
}, this.options.timeout);
this.options.check_health(function(err) {
if (end) {
return;
}
if (err) {
response(resp, 500, "Internal Server Error\r\n" + err);
} else {
response(resp, 200, _this.options.success_body);
}
end = true;
clearTimeout(timeout);
});
}
};
return VipStatus;
})();
module.exports = function(options) {
return new VipStatus(options);
};