-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverUtils.js
More file actions
361 lines (302 loc) · 10.4 KB
/
serverUtils.js
File metadata and controls
361 lines (302 loc) · 10.4 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
const { spawn, exec } = require('child_process');
const fs = require('fs');
const consts = require("../consts");
const {freemem} = require('os');
const {getConfigAttribute} = require("./configUtils");
const path = require('path');
let serverProcess = null;
let serverStatus = 0;
async function isServerOn() {
try {
const serverPID = getConfigAttribute("os") != "Linux" ? await getStrayServerInstance_WINDOWS() : await getStrayServerInstance_LINUX();
return !!serverPID || serverStatus == 1;
} catch (error) {
return false;
}
}
function deleteServerOutput(){
try {
fs.rmSync(consts.serverLogsFilePath, { force: true });
} catch (error) {
console.error(error);
}
}
function isServerStarting(){
const serverLogs = getServerlogs();
if(serverLogs == null || serverLogs.includes("All dimensions are saved")){
return 0;
}
if(serverLogs.includes("Starting") && !serverLogs.includes("Done")){
serverStatus = 2;
return serverStatus;
}else if(serverLogs.includes("Done")){
serverStatus = 1;
return serverStatus;
}
else{
return 0;
}
}
function isEULAsigned() {
if (fs.existsSync(consts.eulaFilePath)){
if (fs.readFileSync(consts.eulaFilePath, 'utf8').includes('eula=true')) {
return true;
}
else
return false;
}
else
return false;
}
function signEULA() {
fs.writeFileSync(consts.eulaFilePath, 'eula=true');
}
function getServerlogs() {
try {
return fs.readFileSync(consts.serverLogsFilePath, { encoding: 'utf8', flag: 'r' })
} catch (error) {
return null;
}
}
async function runMCCommand(command) {
try{
if(!isServerOn()){
throw new Error("Can't run command, server is offline.")
}
serverProcess.stdin.write(`${command}\n`);
} catch(error){
console.error(error);
}
}
async function killStrayServerInstance(){
switch(getConfigAttribute("os")){
case "Windows_NT":
await killStrayServerInstance_WINDOWS();
serverStatus = 0;
deleteServerOutput();
break;
case "Linux":
await killStrayServerInstance_LINUX();
serverStatus = 0;
deleteServerOutput();
break;
case _:
await killStrayServerInstance_LINUX();
break;
}
}
function getStrayServerInstance_WINDOWS() {
return new Promise((resolve, reject) => {
const tasklist = spawn('tasklist', ['/FI', 'IMAGENAME eq java.exe']);
let output = '';
tasklist.stdout.on('data', (data) => {
output += data.toString();
});
tasklist.stderr.on('data', (data) => {
reject(`Error in tasklist: ${data.toString()}`);
});
tasklist.on('close', (code) => {
if (code !== 0) {
reject(`tasklist command failed with code ${code}`);
} else if (output.includes('java.exe')) {
const netstat = spawn('netstat', ['-ano']);
let netstatOutput = '';
netstat.stdout.on('data', (data) => {
netstatOutput += data.toString();
});
netstat.stderr.on('data', (data) => {
reject(`Error in netstat: ${data.toString()}`);
});
netstat.on('close', (code) => {
if (code !== 0) {
reject(`netstat command failed with code ${code}`);
} else {
const port = getConfigAttribute("port");
const regex = new RegExp(`TCP\\s+.*:${port}\\s+.*\\s+LISTENING\\s+(\\d+)`, 'i');
const match = netstatOutput.match(regex);
if (match) {
resolve(parseInt(match[1]));
} else {
reject(`No Minecraft server found on port ${port}`);
}
}
});
} else {
reject('No Minecraft server found with java.exe');
}
});
});
}
async function killStrayServerInstance_WINDOWS() {
try {
const strayServerPID = await getStrayServerInstance_WINDOWS();
const command = `taskkill /PID ${strayServerPID} /F`;
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
console.log(`Process with PID ${strayServerPID} killed successfully`);
});
} catch (error) {
console.error(error);
}
}
function getStrayServerInstance_LINUX() {
return new Promise((resolve, reject) => {
// Step 1: Get all Java process PIDs
const ps = spawn('ps', ['-C', 'java', '-o', 'pid=']);
let output = '';
ps.stdout.on('data', (data) => {
output += data.toString();
});
ps.stderr.on('data', (data) => {
reject(`Error in ps: ${data.toString()}`);
});
ps.on('close', (code) => {
if (code !== 0) {
return reject(`ps command failed with code ${code}`);
}
const javaPIDs = output.trim().split('\n').map(line => line.trim()).filter(Boolean);
if (javaPIDs.length === 0) {
return reject('No Java processes found.');
}
// Step 2: Check for listeners on the target port
const ss = spawn('ss', ['-tlnp']);
let ssOutput = '';
ss.stdout.on('data', (data) => {
ssOutput += data.toString();
});
ss.stderr.on('data', (data) => {
reject(`Error in ss: ${data.toString()}`);
});
ss.on('close', (code) => {
if (code !== 0) {
return reject(`ss command failed with code ${code}`);
}
const port = getConfigAttribute("mc_port"); // assumed defined
const lines = ssOutput.split('\n');
for (const line of lines) {
if (line.includes(`:${port}`) && line.includes('LISTEN') && line.includes('pid=')) {
const pidMatch = line.match(/pid=(\d+)/);
if (pidMatch) {
const pid = pidMatch[1];
if (javaPIDs.includes(pid)) {
return resolve(parseInt(pid, 10));
}
}
}
}
reject(`No Java process found listening on port ${port}`);
});
});
});
}
async function killStrayServerInstance_LINUX() {
try {
const strayServerPID = await getStrayServerInstance_LINUX();
const command = `kill -9 ${strayServerPID}`;
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
console.log(`Process with PID ${strayServerPID} killed successfully`);
});
} catch (error) {
console.error(error);
}
}
function validateMemory(){
try {
const launchConfig = require("../server-config.json");
const availableMemory = Math.floor(freemem() / 1048576);
if(availableMemory > parseInt(launchConfig["memory"].replace("M",""))){
console.log(`${launchConfig["memory"]} Available for use!`);
return true;
}else{
console.log(`${launchConfig["memory"]} not available for use!`);
return false;
}
} catch (error) {
console.error(error);
return false;
}
}
async function startServer() {
if(!validateMemory()){
throw new Error("Not enough memory for server to run");
}
const command = 'java';
const args = ['-Xmx1024M', '-Xms1024M', '-jar', consts.serverName, 'nogui'];
serverProcess = spawn(command, args, {
cwd: consts.serverDirectory, // Set the working directory
stdio: ['pipe', 'pipe', 'pipe'], // Use pipes for stdin, stdout, and stderr
});
fs.writeFileSync(consts.serverLogsFilePath, '');
serverProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
fs.appendFileSync(consts.serverLogsFilePath, data);
});
serverProcess.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
serverProcess.on('close', (code) => {
console.log(`Server process exited with code ${code}`);
});
}
async function startServerWithScript() {
if(!validateMemory()){
throw new Error("Not enough memory for server to run");
}
try{
if (!fs.existsSync(path.join(consts.serverDirectory, 'start.sh'))) {
throw new Error("start.sh script not found in server directory\n If you don't intend on using a script, set start_server_with_script to false in server-config.json");
}
serverProcess = spawn('sh', ['start.sh'], {
cwd: consts.serverDirectory,
stdio: ['pipe', 'pipe', 'pipe'],
});
fs.writeFileSync(consts.serverLogsFilePath, '');
serverProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
fs.appendFileSync(consts.serverLogsFilePath, data);
});
serverProcess.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
serverProcess.on('close', (code) => {
console.log(`Server process exited with code ${code}`);
});
}catch(error){
throw new Error(error);
}
}
async function doesServerJarAlreadyExist() {
return fs.existsSync("../server/server.jar");
}
module.exports = {
isServerOn,
getStrayServerInstance_WINDOWS,
getStrayServerInstance_LINUX,
killStrayServerInstance_WINDOWS,
killStrayServerInstance_LINUX,
startServer,
isServerStarting,
doesServerJarAlreadyExist,
getServerlogs,
runMCCommand,
killStrayServerInstance,
signEULA,
isEULAsigned,
startServerWithScript,
serverStatus,
};