-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmain.js
97 lines (87 loc) · 2.35 KB
/
main.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
console.log("Starting process...");
const args = process.argv.slice(2);
const { fork } = require("child_process");
const serverPath = "./runserver.js";
const http = require("http");
let maintenance_port = null;
// Listen for exit command from the console
function listenForExitCommand() {
process.stdin.resume();
process.stdin.on("data", function(e) {
if (e.length && e[0] === 0x03) {
process.exit();
}
});
}
// Function to run the server
function runServer() {
const owot = fork(serverPath, args);
let gracefulStop = false;
let immediateRestart = false;
let maintenance = false;
process.stdin.pause();
owot.on("close", function(code) {
code += "";
console.log(`Process exited. [${code}; 0x${code.toString(16).toUpperCase().padStart(8, 0)}]`);
if (!gracefulStop) {
if (!immediateRestart) {
listenForExitCommand();
}
console.log("Restarting server...");
if (immediateRestart) {
runServer();
} else {
setTimeout(runServer, 2000);
}
}
if (maintenance) {
maintenanceMode();
}
});
owot.on("message", function(msg) {
if (msg === "EXIT") {
gracefulStop = true;
}
if (msg === "RESTART") {
immediateRestart = true;
}
if (msg === "MAINT") {
gracefulStop = true;
maintenance = true;
listenForExitCommand();
}
if (msg.startsWith("PORT=")) {
maintenance_port = parseInt(msg.slice(5));
}
});
}
runServer();
// Function to start maintenance mode
function maintenanceMode() {
if (!maintenance_port || isNaN(maintenance_port)) {
throw new Error("Cannot fire up maintenance message server: Invalid port");
}
const time = new Date();
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const timeStr = `${months[time.getUTCMonth()]} ${time.getUTCDate()}, ${time.getUTCFullYear()}`;
const server = http.createServer(function(req, res) {
try {
const text = `
<html>
<head><title>Maintenance</title></head>
<span>Our World Of Text is currently down for maintenance.</span><br>
<span>Maintenance began on ${timeStr}</span>
</html>`;
res.write(text);
res.end();
} catch (e) {
console.log(e);
}
});
server.listen(maintenance_port, function() {
const addr = server.address();
const ip = addr.address;
const port = addr.port;
console.log(`Maintenance: [${ip}]:${port}`);
});
}