Merged dev into master

This commit is contained in:
Danielv123 committed 2017-03-02 15:01:06 +01:00
commit adff48d612
2 files changed
+144 -99

No files matched your search

+142 -97
View File
@@ -54,7 +54,9 @@ function messageInterface(command, callback) {
client.exec(command, callback);
} catch (err) {
console.log(err);
callback(err);
if(typeof callback == "function"){
callback(err);
}
}
}
}
@@ -99,29 +101,38 @@ if (!command || command == "help" || command == "--help") {
}
} else if (command == "start" && typeof instance == "string" && instance != "/" && !fs.existsSync(instancedirectory)) {
// if instance does not exist, create it
console.log("Creating instance...")
console.log("Creating instance...");
fs.mkdirSync(instancedirectory);
fs.mkdirSync(instancedirectory + "/script-output/");
fs.writeFileSync(instancedirectory + "/script-output/output.txt", "")
fs.writeFileSync(instancedirectory + "/script-output/orders.txt", "")
fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", "")
fs.mkdirSync(instancedirectory + "/mods/")
fs.mkdirSync(instancedirectory + "/saves/");
fs.writeFileSync(instancedirectory + "/script-output/output.txt", "");
fs.writeFileSync(instancedirectory + "/script-output/orders.txt", "");
fs.writeFileSync(instancedirectory + "/script-output/txbuffer.txt", "");
fs.mkdirSync(instancedirectory + "/mods/");
// fs.symlinkSync('../../../sharedMods', instancedirectory + "/mods", 'junction') // This is broken because it can only take a file as first argument, not a folder
fs.writeFileSync(instancedirectory + "/config.ini", "[path]\r\n\
read-data=__PATH__executable__/../../data\r\n\
write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\
");
var instconf = {
fs.copySync('sharedMods', instancedirectory + "/mods")
let instconf = {
"factorioPort": Math.floor(Math.random() * 65535),
"clientPort": Math.floor(Math.random() * 65535),
"clientPassword": Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 8),
}
console.log("Clusterio | Moving shared mods...")
console.log(instconf)
// create instance config
fs.writeFileSync(instancedirectory + "/config.json", JSON.stringify(instconf, null, 4));
var serversettings = {
"name": config.username + "'s clusterio " + instance,
let name = "Clusterio instance: " + instance;
if (config.username) {
name = config.username + "'s clusterio " + instance;
}
let serversettings = {
"name": name,
"description": config.description,
"tags": ["clusterio"],
"max_players": "20",
@@ -137,14 +148,12 @@ write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\
"autosave_slots": 5,
"afk_autokick_interval": 0,
"auto_pause": config.auto_pause,
}
fs.writeFileSync(instancedirectory + "/server-settings.json", JSON.stringify(serversettings, null, 4));
var createSave = child_process.spawnSync(
let createSave = child_process.spawnSync(
'./' + config.factorioDirectory + '/bin/x64/factorio', [
'-c', instancedirectory + '/config.ini',
'--create', instancedirectory + '/save.zip',
'--create', instancedirectory + '/saves/save.zip',
]
)
console.log("Instance created!")
@@ -155,57 +164,15 @@ write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\
} else {
process.exit(1)
}
// move mods from ./sharedMods to the instances mod directory
console.log("Clusterio | Moving shared mods...")
//ncp("./sharedMods/", instancedirectory + "/mods", function (err) {
fs.copySync('sharedMods', instancedirectory + "/mods")
process.on('SIGINT', function () {
console.log("Caught interrupt signal");
//serverprocess.stdin.write('/quit')
});
// Spawn factorio server
//var serverprocess = child_process.exec(commandline)
var serverprocess = child_process.spawn(
'./' + config.factorioDirectory + '/bin/x64/factorio', [
'-c', instancedirectory + '/config.ini',
'--start-server', instancedirectory + '/save.zip',
'--rcon-port', instanceconfig.clientPort,
'--rcon-password', instanceconfig.clientPassword,
'--server-settings', instancedirectory + '/server-settings.json',
'--port', instanceconfig.factorioPort
], {
'stdio': ['pipe', 'pipe', 'pipe']
console.log("Deleting .tmp.zip files");
let savefiles = fs.readdirSync(instancedirectory + "/saves/");
for(i = 0; i < savefiles.length; i++){
if(savefiles[i].substr(savefiles[i].length - 8, 8) == ".tmp.zip") {
fs.unlinkSync(instancedirectory + "/saves/" + savefiles[i]);
}
)
serverprocess.on('close', (code) => {
console.log(`child process exited with code ${code}`);
process.exit();
});
serverprocess.stdout.on('data', (chunk) => {
console.log('OUT: ' + chunk);
})
serverprocess.stderr.on('data', (chunk) => {
console.log('ERR: ' + chunk);
})
// connect to the server with rcon
// IP, port, password
var client = new Rcon({
host: 'localhost',
port: instanceconfig.clientPort,
password: instanceconfig.clientPassword,
timeout: 0
});
}
console.log("Deleting logs");
// clean old log file to avoid crash
// file exists, delete so we don't get in trouble
try {
@@ -218,37 +185,85 @@ write-data=__PATH__executable__/../../../instances/" + instance + "\r\n\
}
}
// check the logfile to see if the RCON interface is running as there is no way to continue without it
// we read the log every 2 seconds and stop looping when we start connecting to factorio
function checkRcon() {
fs.readFile(instancedirectory+"/factorio-current.log", function (err, data) {
// if (err) console.log(err);
if(data && data.indexOf('Starting RCON interface') > 0){
client.connect();
} else {
setTimeout(function(){
checkRcon();
},2000);
}
});
}
checkRcon();
client.on('authenticated', function () {
console.log('Clusterio | Authenticated!');
instanceManagement(); // start using rcons
}).on('connected', function () {
console.log('Clusterio | Connected!');
// getID();
}).on('disconnected', function () {
console.log('Clusterio | Disconnected!');
// now reconnect
client.connect();
// move mods from ./sharedMods to the instances mod directory
console.log("Clusterio | Moving shared mods...");
fs.copySync('sharedMods', instancedirectory + "/mods");
process.on('SIGINT', function () {
console.log("Caught interrupt signal");
messageInterface("/quit");
});
// set some globals
confirmedOrders = [];
lastSignalCheck = Date.now();
// Spawn factorio server
//var serverprocess = child_process.exec(commandline)
getNewestFile(instancedirectory + "/saves/", fs.readdirSync(instancedirectory + "/saves/"),function(latestSave) {
var serverprocess = child_process.spawn(
'./' + config.factorioDirectory + '/bin/x64/factorio', [
'-c', instancedirectory + '/config.ini',
'--start-server', latestSave.file,
'--rcon-port', instanceconfig.clientPort,
'--rcon-password', instanceconfig.clientPassword,
'--server-settings', instancedirectory + '/server-settings.json',
'--port', instanceconfig.factorioPort
], {
'stdio': ['pipe', 'pipe', 'pipe']
}
)
serverprocess.on('close', (code) => {
console.log(`child process exited with code ${code}`);
process.exit();
});
/*
serverprocess.stdout.on('data', (chunk) => {
console.log('OUT: ' + chunk);
})*/
serverprocess.stderr.on('data', (chunk) => {
console.log('ERR: ' + chunk);
})
// connect to the server with rcon
// IP, port, password
client = new Rcon({
host: 'localhost',
port: instanceconfig.clientPort,
password: instanceconfig.clientPassword,
timeout: 0
});
// check the logfile to see if the RCON interface is running as there is no way to continue without it
// we read the log every 2 seconds and stop looping when we start connecting to factorio
function checkRcon() {
fs.readFile(instancedirectory+"/factorio-current.log", function (err, data) {
// if (err) console.log(err);
if(data && data.indexOf('Starting RCON interface') > 0){
client.connect();
} else {
setTimeout(function(){
checkRcon();
},2000);
}
});
}
setTimeout(checkRcon, 5000);
client.on('authenticated', function () {
console.log('Clusterio | Authenticated!');
instanceManagement(); // start using rcons
}).on('connected', function () {
console.log('Clusterio | Connected!');
// getID();
}).on('disconnected', function () {
console.log('Clusterio | Disconnected!');
// now reconnect
client.connect();
});
// set some globals
confirmedOrders = [];
lastSignalCheck = Date.now();
})
}
function instanceManagement() {
@@ -353,7 +368,7 @@ function instanceManagement() {
require('getmac').getMac(function (err, mac) {
if (err) throw err
payload.mac = mac
console.log(payload)
// console.log(payload)
needle.post(config.masterIP + ":" + config.masterPort + '/getID', payload, function (err, response, body) {
if (response && response.body) {
// In the future we might be interested in whether or not we actually manage to send it, but honestly I don't care.
@@ -486,7 +501,7 @@ function instanceManagement() {
sadas = JSON.stringify(confirmedOrders)
confirmedOrders = [];
// send our RCON command with whatever we got
client.exec("/silent-command remote.call('clusterio', 'importMany', '" + sadas + "')");
messageInterface("/silent-command remote.call('clusterio', 'importMany', '" + sadas + "')");
}
}, 3000)
// COMBINATOR SIGNALS ---------------------------------------------------------
@@ -502,8 +517,8 @@ function instanceManagement() {
inventoryFrame[inventory[i].name] = Number(inventory[i].count);
}
inventoryFrame["signal-unixtime"] = Math.floor(Date.now()/1000);
console.log("RCONing inventory! " + JSON.stringify(inventoryFrame));
client.exec("/silent-command remote.call('clusterio', 'receiveInventory', '" + JSON.stringify(inventoryFrame) + "')");
// console.log("RCONing inventory! " + JSON.stringify(inventoryFrame));
messageInterface("/silent-command remote.call('clusterio', 'receiveInventory', '" + JSON.stringify(inventoryFrame) + "')");
}
});
}, 1000)
@@ -619,3 +634,33 @@ function hashMods(instanceName, callback) {
});
}
}
// gets newest file in a directory
// dir is directory
// files is array of filenames
// callback(filename string)
function getNewestFile(dir, files, callback) {
if (!callback) return;
if (!files || (files && files.length === 0)) {
callback();
}
var newest = { file: files[0] };
var checked = 0;
fs.stat(dir + newest.file, function(err, stats) {
newest.mtime = stats.mtime;
for (var i = 0; i < files.length; i++) {
var file = files[i];
(function(file) {
fs.stat(file, function(err, stats) {
++checked;
if (stats.mtime.getTime() > newest.mtime.getTime()) {
newest = { file : file, mtime : stats.mtime };
}
if (checked == files.length) {
callback(newest);
}
});
})(dir + file);
}
});
}
+2 -2
View File
@@ -18,6 +18,7 @@
"child_process": "^1.0.2",
"express": "^4.14.0",
"express-fileupload": "0.0.6",
"find-remove": "^1.0.0",
"follow-redirects": "^1.2.1",
"fs": "0.0.2",
"fs-extra": "^1.0.0",
@@ -29,7 +30,6 @@
"needle": "^1.1.0",
"portfinder": "^1.0.9",
"request": "^2.79.0",
"simple-rcon": "^0.3.1",
"sync-request": "^3.0.1"
"simple-rcon": "^0.3.1"
}
}