mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-18 07:33:12 +09:00
Daemonize slave
Rework client.js to support running multiple instances at once and be managed remotely and implement the neccessary communication infrastructure for this. Due to circular dependencies on the implementation of this the master branch is significantly broken after this.
This commit is contained in:
1 parent
5858d97857
commit
7a2abaa5db
29 files changed
+2811
-800
No files matched your search
@@ -1,40 +0,0 @@
|
||||
const needle = require("needle");
|
||||
|
||||
module.exports = function(config){
|
||||
const instances = [];
|
||||
|
||||
if(config){
|
||||
return function getInstanceName(instanceID){
|
||||
return new Promise((resolve, reject) => {
|
||||
let instance = instances[instanceID];
|
||||
if(!instance){
|
||||
needle.get(config.masterURL + '/api/slaves', { compressed: true }, (err, response) => {
|
||||
if(err || response.statusCode != 200) {
|
||||
console.log("Unable to get JSON master/api/slaves, master might be unaccessible");
|
||||
} else if (response && response.body) {
|
||||
if(Buffer.isBuffer(response.body)) {console.log(response.body.toString("utf-8")); reject(new Error())}
|
||||
try {
|
||||
for (let index in response.body)
|
||||
instances[index] = response.body[index].instanceName;
|
||||
} catch (e){
|
||||
console.log(e);
|
||||
return null;
|
||||
}
|
||||
instance = instances[instanceID]
|
||||
if (!instance) instance = instanceID; //somehow the master doesn't know the instance
|
||||
resolve(instance);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resolve(instance);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return async function thisAintGonnaWork(){
|
||||
let err = new Error("getInstanceName from lib/clusterTools needs to be called with {config} to work");
|
||||
console.log(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
/**
|
||||
|
||||
Functions frequently needed from different places in the cluster. Ex:
|
||||
* Getting an instance's displayname from their ID
|
||||
|
||||
*/
|
||||
|
||||
module.exports = ({config} = {}) => ({
|
||||
/**
|
||||
async function to get an instances displayname from their instanceID
|
||||
|
||||
arg1 is the instanceID
|
||||
Promise resolves with a string, either the displayName or instanceID if not found.
|
||||
*/
|
||||
getInstanceName: require("./getInstanceName")(config),
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Errors thrown in Clusterio
|
||||
* @module
|
||||
*/
|
||||
|
||||
class CommandError extends Error { }
|
||||
class RequestError extends Error { }
|
||||
|
||||
// Signal for messages that fail validation
|
||||
class InvalidMessage extends Error { }
|
||||
|
||||
// Errror class for known errors occuring during startup
|
||||
class StartupError extends Error { }
|
||||
|
||||
module.exports = {
|
||||
CommandError,
|
||||
RequestError,
|
||||
InvalidMessage,
|
||||
StartupError,
|
||||
}
|
||||
@@ -612,7 +612,7 @@ class FactorioServer extends events.EventEmitter {
|
||||
* @returns {string} response from server.
|
||||
*/
|
||||
async sendRcon(message) {
|
||||
this._check(["init", "running"])
|
||||
this._check(["running"])
|
||||
if (!this._rconReady) {
|
||||
await events.once(this, 'rcon-ready');
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
const fileOps = require("lib/fileOps");
|
||||
// const config = require("./../config");
|
||||
|
||||
module.exports = function(config) {
|
||||
return {
|
||||
sync: function(){
|
||||
let instances;
|
||||
try {
|
||||
instances = fileOps.getDirectoriesSync(config.instanceDirectory);
|
||||
} catch (e) {
|
||||
// there are no instances created yet, probably missing the folder
|
||||
instances = [];
|
||||
}
|
||||
return instances;
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
module.exports = {
|
||||
...require('lib/link/link'),
|
||||
...require('lib/link/messages'),
|
||||
};
|
||||
@@ -0,0 +1,399 @@
|
||||
"use strict";
|
||||
const events = require("events");
|
||||
const io = require("socket.io-client");
|
||||
|
||||
const schema = require("lib/schema");
|
||||
const errors = require("lib/errors");
|
||||
const messages = require("lib/link/messages");
|
||||
|
||||
// Some definitions for the terminology used here:
|
||||
// link: Either side of a master - client connection
|
||||
// connection: the master server side of a link
|
||||
// client: the side that is not the master server of a link
|
||||
// message: the complete object sent using the 'message' event
|
||||
// data: the data property of a message, essentially the payload.
|
||||
// type: the type property of a message, identifies what to expect in data.
|
||||
|
||||
/**
|
||||
* Common interface for server and client connections
|
||||
*/
|
||||
class Link {
|
||||
constructor(source, target, socket) {
|
||||
this.source = source;
|
||||
this.target = target;
|
||||
this.socket = socket;
|
||||
|
||||
this._seq = 1;
|
||||
this._waiters = new Map();
|
||||
this._handlers = new Map();
|
||||
this._validators = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a received message on the link
|
||||
*
|
||||
* Validates and invokes the handler and/or waiters for a message that has
|
||||
* been received. An unhandled message is considered to be an error.
|
||||
*
|
||||
* @throws {InvalidMessage}
|
||||
* if validation failed, is missing, the message is invalid, or no
|
||||
* handlers/waiters were invoked to handle the message.
|
||||
*/
|
||||
processMessage(message) {
|
||||
if (!schema.message(message)) {
|
||||
throw new errors.InvalidMessage("Malformed message");
|
||||
}
|
||||
|
||||
let validator = this._validators.get(message.type);
|
||||
if (!validator) {
|
||||
throw new errors.InvalidMessage(`No validator for ${message.type}`);
|
||||
}
|
||||
|
||||
if (!validator(message)) {
|
||||
// TODO better logging of errors encountered validating
|
||||
console.error(validator.errors);
|
||||
throw new errors.InvalidMessage(`Validation failed for ${message.type}`);
|
||||
}
|
||||
|
||||
let hadHandlers = this._processHandler(message);
|
||||
let hadWaiters = this._processWaiters(message);
|
||||
|
||||
if (!hadWaiters && !hadHandlers) {
|
||||
// XXX console.error(`Unhandled message: ${JSON.stringify(message, null, 4)}`);
|
||||
throw new errors.InvalidMessage(`Unhandled message ${message.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke the handler for this message if it exists
|
||||
*
|
||||
* @returns {Boolean} true if a handler was invoked.
|
||||
*/
|
||||
_processHandler(message) {
|
||||
let handler = this._handlers.get(message.type);
|
||||
if (handler) {
|
||||
handler(message);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the waiters for this message if any
|
||||
*
|
||||
* @returns {Boolean} true if a waiter was triggered.
|
||||
*/
|
||||
_processWaiters(message) {
|
||||
let { seq, type, data } = message;
|
||||
let waiters = this._waiters.get(type);
|
||||
if (!waiters || !waiters.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let matched = [];
|
||||
waitersLoop: for (let index = 0; index < waiters.length; index++) {
|
||||
let waiter = waiters[index];
|
||||
for (let [key, value] of Object.entries(waiter.data)) {
|
||||
if (data[key] !== value) {
|
||||
continue waitersLoop;
|
||||
}
|
||||
}
|
||||
|
||||
waiter.resolve(message);
|
||||
matched.push(index);
|
||||
}
|
||||
|
||||
matched.reverse();
|
||||
for (let index of matched) {
|
||||
waiters.splice(index, 1);
|
||||
}
|
||||
|
||||
return matched.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set handler for a message type
|
||||
*
|
||||
* Set function called upon receiving a message of the given type.
|
||||
*
|
||||
* @param {string} type - Type of message to listen to
|
||||
* @param {function} handler -
|
||||
* Callack to invoke on messages of the given type.
|
||||
* @param {function} validator -
|
||||
* Function validating the message have the correct format.
|
||||
*/
|
||||
setHandler(type, handler, validator) {
|
||||
if (this._handlers.has(type)) {
|
||||
throw new Error(`${type} already has a handler`);
|
||||
}
|
||||
|
||||
if (!validator) {
|
||||
throw new Error("validator is required");
|
||||
}
|
||||
|
||||
this.setValidator(type, validator);
|
||||
this._handlers.set(type, handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set validator for a message type
|
||||
*
|
||||
* Set function called upon receiving a message of the given type in
|
||||
* order to validate the message. The function should return true if
|
||||
* the message is valid and false otherwise.
|
||||
*
|
||||
* @param {string} type - Type of message to validate
|
||||
* @param {function} validator - Validation function.
|
||||
*/
|
||||
setValidator(type, validator) {
|
||||
if (this._validators.has(type)) {
|
||||
throw new Error(`${type} already has a validator`);
|
||||
}
|
||||
|
||||
this._validators.set(type, validator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message over the link
|
||||
*
|
||||
* @returns the sequence number of the message sent
|
||||
*/
|
||||
send(type, data) {
|
||||
this.socket.send({ seq: this._seq, type, data });
|
||||
return this._seq++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a message matching given type and data
|
||||
*
|
||||
* Waits for a message over the link that matches the type given as well
|
||||
* as any properties specified in data. For example specifying { foo:
|
||||
* 21 } as the data will cause it to wait until a message with the right
|
||||
* type and a foo property value of 21 in the data payload.
|
||||
*/
|
||||
async waitFor(type, data) {
|
||||
if (!this._validators.has(type)) {
|
||||
throw new Error(`no validator for ${type}`);
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this._waiters.has(type)) {
|
||||
this._waiters.set(type, [{ data, resolve }]);
|
||||
} else {
|
||||
this._waiters.get(type).push({ data, resolve });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the connection with the given reason.
|
||||
*
|
||||
* Sends a close message and disconnects from the socket.
|
||||
*/
|
||||
close(reason) {
|
||||
this.send('close', { reason });
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Disconnect from the socket
|
||||
*
|
||||
* Abstract function that subclases override to implement disconnection
|
||||
* from the socket.
|
||||
*/
|
||||
disconnect() {
|
||||
throw new Error("Abstract function");
|
||||
}
|
||||
}
|
||||
|
||||
class Connection extends Link {
|
||||
constructor(target, socket) {
|
||||
super('master', target, socket);
|
||||
|
||||
this._seq = 3; // XXX this is private to Link
|
||||
this.socket.on('message', payload => {
|
||||
try {
|
||||
this.processMessage(payload);
|
||||
} catch (err) {
|
||||
if (err instanceof errors.InvalidMessage) {
|
||||
this.close(`Invalid message: ${err.message}`);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
});
|
||||
this.socket.on('disconnect', this.disconnect.bind(this));
|
||||
|
||||
this.setHandler('close', payload => {
|
||||
let address = this.socket.handshake.address
|
||||
console.log(`SOCKET | received close from control ${address}: ${payload.data.reason}`);
|
||||
this.socket.disconnect(true);
|
||||
}, schema.close);
|
||||
|
||||
socket.send({ seq: 2, type: 'ready', data: {} });
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.socket.disconnect(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class Client extends Link {
|
||||
constructor(source, url, token) {
|
||||
super(source, 'master', null);
|
||||
|
||||
this._url = url;
|
||||
this._token = token;
|
||||
|
||||
this._state = "new";
|
||||
this._events = new events.EventEmitter();
|
||||
|
||||
this.setHandler('close', message => {
|
||||
console.log(`SOCKET | received close from server: ${message.data.reason}`);
|
||||
this.socket.close();
|
||||
return; // XXX what now?
|
||||
}, schema.close);
|
||||
}
|
||||
|
||||
_check(expectedStates) {
|
||||
if (!expectedStates.includes(this._state)) {
|
||||
throw new Error(
|
||||
`Expected state ${expectedStates} but state is ${this._state}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async connect() {
|
||||
this._check(["new"]);
|
||||
this._state = "handshake";
|
||||
|
||||
// Open socket.io connection to master
|
||||
console.log(`SOCKET | connecting to ${this._url}`)
|
||||
let url = new URL(this._url);
|
||||
url.searchParams.append('token', this._token);
|
||||
|
||||
// I really have to question the choice of having the path connected
|
||||
// to be passed as separate parameter instead of the namespace.
|
||||
let urlPath = url.pathname + "socket.io";
|
||||
url.pathname = "";
|
||||
this.socket = io(url.href, {
|
||||
path: urlPath,
|
||||
reconnectionAttempts: 2,
|
||||
|
||||
// For now we do not verify TLS certificates since the default setup is
|
||||
// to create a self-signed certificate.
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
|
||||
_attachSocketHandlers();
|
||||
|
||||
// Wait for the connection to be ready
|
||||
await events.once(this._events, 'ready');
|
||||
}
|
||||
|
||||
_attachSocketHandlers() {
|
||||
this.socket.on("error", err => {
|
||||
console.error("SOCKET | Error:", err);
|
||||
this.socket.close();
|
||||
});
|
||||
|
||||
/*this.socket.on("connect_error", err => {
|
||||
console.log("SOCKET | Connect error:", err);
|
||||
});*/
|
||||
this.socket.on("connect_timeout", () => {
|
||||
console.log("SOCKET | Connect timeout");
|
||||
});
|
||||
this.socket.on("reconnect", attempt => {
|
||||
console.log(`SOCKET | Reconnect no. ${attempt} succeeded`);
|
||||
});
|
||||
this.socket.on("reconnect_attempt", () => {
|
||||
console.log("SOCKET | Attempting reconnect");
|
||||
});
|
||||
this.socket.on("reconnecting", attempt => {
|
||||
console.log(`SOCKET | Attempting reconnect no. ${attempt}`);
|
||||
});
|
||||
/*this.socket.on("reconnect_error", err => {
|
||||
console.log("SOCKET | Reconnect error:", err);
|
||||
});*/
|
||||
this.socket.on("reconnect_failed", () => {
|
||||
console.log("SOCKET | Reconnecting failed");
|
||||
});
|
||||
/*this.socket.on("ping", () => {
|
||||
console.log("SOCKET | Ping");
|
||||
});
|
||||
this.socket.on("pong", (ms) => {
|
||||
// XXX Latency might be useful
|
||||
console.log(`SOCKET | Pong latency ${ms}ms`);
|
||||
});*/
|
||||
this.socket.on("connect", () => {
|
||||
console.log("SOCKET | connected");
|
||||
});
|
||||
|
||||
// Handle messages
|
||||
this.socket.on("message", message => {
|
||||
if (this._state === "handshake") {
|
||||
this._processHandshake(message);
|
||||
} else if (this._state === "ready") {
|
||||
try {
|
||||
this.processMessage(message);
|
||||
} catch (err) {
|
||||
if (err instanceof errors.InvalidMessage) {
|
||||
this.close(`Invalid message: ${err.message}`);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Received message in unexpected state ${this._state}`);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
disconnect(reason) {
|
||||
this.socket.close();
|
||||
// XXX what now?
|
||||
}
|
||||
|
||||
_processHandshake(message) {
|
||||
if (!schema.serverHandshake(message)) {
|
||||
console.log("SOCKET | closing after received invalid handshake:", message);
|
||||
this.close("Invalid handshake");
|
||||
return;
|
||||
}
|
||||
|
||||
let { seq, type, data } = message;
|
||||
if (type == 'hello') {
|
||||
console.log(`SOCKET | received hello from master version ${data.version}`);
|
||||
this.register();
|
||||
|
||||
} else if (type === 'ready') {
|
||||
console.log("SOCKET | received ready from master");
|
||||
this._state = "ready";
|
||||
this._events.emit('ready');
|
||||
|
||||
} else if (type === 'close') {
|
||||
console.log(`SOCKET | received close from server: ${data.reason}`);
|
||||
this._events.emit('error', new Error(`server closed during handshake: ${data.reason}`));
|
||||
this.socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the link with the server
|
||||
*
|
||||
* This function is expected to be overriden by sub-classes and send the
|
||||
* register message over the socket when invoked.
|
||||
*/
|
||||
register() {
|
||||
throw Error("Abstract function");
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Link,
|
||||
Connection,
|
||||
Client,
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
"use strict";
|
||||
const schema = require("lib/schema");
|
||||
const errors = require("lib/errors");
|
||||
|
||||
/**
|
||||
* Represents a request sent over the link
|
||||
*
|
||||
* A request-response message that can be innitated by either party of the
|
||||
* link.
|
||||
*/
|
||||
class Request {
|
||||
constructor({
|
||||
type, sources, targets, requestProperties = {}, responseProperties = {}
|
||||
}) {
|
||||
this.type = type;
|
||||
this.sources = sources;
|
||||
this.targets = targets;
|
||||
|
||||
this.requestType = type + '_request';
|
||||
this.responseType = type + '_response';
|
||||
|
||||
this._requestValidator = schema.compile({
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
properties: {
|
||||
"type": { const: this.requestType },
|
||||
"data": {
|
||||
additionalProperties: false,
|
||||
required: Object.keys(requestProperties),
|
||||
properties: requestProperties,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this._responseValidator = schema.compile({
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
properties: {
|
||||
"type": { const: this.responseType },
|
||||
"data": {
|
||||
anyOf: [
|
||||
{
|
||||
additionalProperties: false,
|
||||
required: ["seq", ...Object.keys(responseProperties)],
|
||||
properties: {
|
||||
"seq": { type: "integer" },
|
||||
...responseProperties,
|
||||
},
|
||||
},
|
||||
{
|
||||
additionalProperties: false,
|
||||
required: ["seq", "error"],
|
||||
properties: {
|
||||
"seq": { type: "integer" },
|
||||
"error": { type: "string" },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach to a link
|
||||
*
|
||||
* Set a the validator for the response on the given link if it's a
|
||||
* source and sets the handler for the request if it is a target.
|
||||
*
|
||||
* Does nothing if the link is neither a source nor a target for this
|
||||
* request.
|
||||
*
|
||||
* @param {Link} link - The link to attach to.
|
||||
* @param {Function} handler -
|
||||
* Async function to invoke with link set as this to handle the
|
||||
* request request. Only used on the target side.
|
||||
* @throws {Error} if the handler is needed and not defined.
|
||||
*/
|
||||
attach(link, handler) {
|
||||
// Source side.
|
||||
if (this.sources.includes(link.source) && this.targets.includes(link.target)) {
|
||||
link.setValidator(this.responseType, this._responseValidator);
|
||||
}
|
||||
|
||||
// Target side. Note: Source and target is reversed here.
|
||||
if (this.targets.includes(link.source) && this.sources.includes(link.target)) {
|
||||
if (!handler) {
|
||||
throw new Error(`Missing handler for ${this.requestType} on ${link.target}-${link.source} link`);
|
||||
}
|
||||
|
||||
link.setHandler(this.requestType, message => {
|
||||
handler.call(link, message).then(response => {
|
||||
if (response === undefined) {
|
||||
// XXX Should we allow implicit responses like this?
|
||||
response = {};
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(response, 'seq')) {
|
||||
throw new errors.RequestError("response contains reserved property 'seq'");
|
||||
}
|
||||
link.send(this.responseType, { seq: message.seq, ...response });
|
||||
|
||||
}).catch(err => {
|
||||
if (!(err instanceof errors.RequestError)) {
|
||||
console.error(`Unexpected error while responding to ${this.requestType}`, err);
|
||||
}
|
||||
link.send(this.responseType, { seq: message.seq, error: err.message });
|
||||
});
|
||||
}, this._requestValidator);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send request over the given link
|
||||
*
|
||||
* Sends the given data over the link as the request payload and waits
|
||||
* for the response.
|
||||
*
|
||||
* @returns {object} response data
|
||||
*/
|
||||
async send(link, data = {}) {
|
||||
// XXX validate link target/source?
|
||||
let seq = link.send(this.requestType, data);
|
||||
let responseMessage = await link.waitFor(this.responseType, { seq });
|
||||
if (responseMessage.data.error) {
|
||||
throw new errors.RequestError(responseMessage.data.error);
|
||||
}
|
||||
return responseMessage.data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a request sent to the master that is forwarded to an instance
|
||||
*
|
||||
* This is a two part request with a master part and a slave part. The
|
||||
* master part is done by the forwardInstanceRequest method on the master
|
||||
* side of link which finds the slave the requuested instance is on and
|
||||
* forwards it there using the foward method.
|
||||
*
|
||||
* The slave part is done by the forwardInstanceRequest on the slave side of
|
||||
* the link and finds the instance and then calls the handler with it and
|
||||
* the message.
|
||||
*/
|
||||
class InstanceRequest {
|
||||
constructor({
|
||||
type, sources, requestProperties = {}, responseProperties = {}
|
||||
}) {
|
||||
this._masterRequest = new Request({
|
||||
type: type + '_master',
|
||||
sources,
|
||||
targets: ['master'],
|
||||
requestProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
...requestProperties,
|
||||
},
|
||||
responseProperties,
|
||||
});
|
||||
this._slaveRequest = new Request({
|
||||
type: type + '_slave',
|
||||
sources: ['master'],
|
||||
targets: ['slave'],
|
||||
requestProperties: {
|
||||
"instance_id": { type: "integer" },
|
||||
...requestProperties,
|
||||
},
|
||||
responseProperties,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach to a link
|
||||
*
|
||||
* Attach master/slave part of the instance request. If this is the
|
||||
* slave side the handler argument is required.
|
||||
*
|
||||
* Does nothing if the link is neither a source nor a target for the
|
||||
* slave or master request.
|
||||
*
|
||||
* @param {Link} link - The link to attach to.
|
||||
* @param {Function} handler -
|
||||
* Async function to to handle the instance request. It is passed on
|
||||
* to forwardInstanceRequest on the slave side.
|
||||
* @throws {Error} if the handler is needed and not defined.
|
||||
*/
|
||||
attach(link, handler) {
|
||||
this._masterRequest.attach(link, async (message) => {
|
||||
return await link.forwardInstanceRequest(message, this);
|
||||
});
|
||||
this._slaveRequest.attach(link, async (message) => {
|
||||
return await link.forwardInstanceRequest(message, handler);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward the message over the link
|
||||
*
|
||||
* This method is expected to be called by forwardInstanceRequest on the
|
||||
* master with the slave link that the instance is on.
|
||||
*/
|
||||
async forward(link, message) {
|
||||
let response = await this._slaveRequest.send(link, message.data);
|
||||
delete response.seq;
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send request over the given link
|
||||
*
|
||||
* Sends the given data over the link to the master and waits for it to
|
||||
* forward the request to the slave with the instance on and return the
|
||||
* result of it.
|
||||
*
|
||||
* @returns {object} response data
|
||||
*/
|
||||
async send(link, data = {}) {
|
||||
return await this._masterRequest.send(link, data);
|
||||
}
|
||||
}
|
||||
|
||||
let requests = {}
|
||||
|
||||
// Management requests
|
||||
requests.listSlaves = new Request({
|
||||
type: 'list_slaves',
|
||||
sources: ['control'],
|
||||
targets: ['master'],
|
||||
responseProperties: {
|
||||
"list": {
|
||||
type: "array",
|
||||
items: {
|
||||
additionalProperties: false,
|
||||
required: ["agent", "version", "name", "id", "connected"],
|
||||
properties: {
|
||||
"agent": { type: "string" },
|
||||
"version": { type: "string" },
|
||||
"name": { type: "string" },
|
||||
"id": { type: "integer" },
|
||||
"connected": { type: "boolean" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
requests.listInstances = new Request({
|
||||
type: 'list_instances',
|
||||
sources: ['control'],
|
||||
targets: ['master'],
|
||||
responseProperties: {
|
||||
"list": {
|
||||
type: "array",
|
||||
items: {
|
||||
additionalProperties: false,
|
||||
required: ["name", "id", "slave_id"],
|
||||
properties: {
|
||||
"name": { type: "string" },
|
||||
"id": { type: "integer" },
|
||||
"slave_id": { type: "integer" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
requests.createInstanceCommand = new Request({
|
||||
type: 'create_instance',
|
||||
sources: ['control'],
|
||||
targets: ['master'],
|
||||
requestProperties: {
|
||||
"name": { type: "string" },
|
||||
"slave_id": { type: "integer" },
|
||||
},
|
||||
});
|
||||
|
||||
requests.createInstance = new Request({
|
||||
type: 'create_instance',
|
||||
sources: ['master'],
|
||||
targets: ['slave'],
|
||||
requestProperties: {
|
||||
"id": { type: "integer" },
|
||||
"options": {
|
||||
additionalProperties: false,
|
||||
required: [
|
||||
"name", "description", "visibility", "username", "token", "game_password",
|
||||
"verify_user_identity", "allow_commands", "auto_pause",
|
||||
],
|
||||
properties: {
|
||||
"name": { type: "string" },
|
||||
"description": { type: "string" },
|
||||
"visibility": { type: "object" },
|
||||
"username": { type: "string" },
|
||||
"token": { type: "string" },
|
||||
"game_password": { type: "string" },
|
||||
"verify_user_identity": { type: "boolean" },
|
||||
"allow_commands": { type: "string" },
|
||||
"auto_pause": { type: "boolean" },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
requests.createSave = new InstanceRequest({
|
||||
type: 'create_save',
|
||||
sources: ['control'],
|
||||
});
|
||||
|
||||
requests.startInstance = new InstanceRequest({
|
||||
type: 'start_instance',
|
||||
sources: ['control'],
|
||||
});
|
||||
|
||||
requests.stopInstance = new InstanceRequest({
|
||||
type: 'stop_instance',
|
||||
sources: ['control'],
|
||||
});
|
||||
|
||||
requests.deleteInstance = new InstanceRequest({
|
||||
type: 'delete_instance',
|
||||
sources: ['control'],
|
||||
});
|
||||
|
||||
requests.sendRcon = new InstanceRequest({
|
||||
type: 'send_rcon',
|
||||
sources: ['control'],
|
||||
requestProperties: {
|
||||
"command": { type: "string" },
|
||||
},
|
||||
responseProperties: {
|
||||
"result": { type: "string" },
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
class Event {
|
||||
constructor({ type, sources, targets, eventProperties = {} }) {
|
||||
this.type = type;
|
||||
this.sources = sources;
|
||||
this.targets = targets;
|
||||
|
||||
this.eventType = type + '_event';
|
||||
this._eventValidator = schema.compile({
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
properties: {
|
||||
"type": { const: this.eventType },
|
||||
"data": {
|
||||
additionalProperties: false,
|
||||
required: Object.keys(eventProperties),
|
||||
properties: eventProperties,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
attach(link, handler) {
|
||||
// Target side. Note: Source and target is reversed here.
|
||||
if (this.targets.includes(link.source) && this.sources.includes(link.target)) {
|
||||
if (!handler) {
|
||||
throw new Error(`Missing handler for ${this.eventType} on ${link.target}-${link.source} link`);
|
||||
}
|
||||
|
||||
link.setHandler(this.eventType, message => {
|
||||
// XXX Should event handlers even be allowed to be async?
|
||||
handler.call(link, message).catch(err => {
|
||||
console.error(`Unexpected error while handling ${this.eventType}`, err);
|
||||
});
|
||||
}, this._eventValidator);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send event over the given link
|
||||
*
|
||||
* Sends the given event data over the link.
|
||||
*/
|
||||
send(link, data = {}) {
|
||||
link.send(this.eventType, data);
|
||||
}
|
||||
}
|
||||
|
||||
let events = {};
|
||||
events.updateInstances = new Event({
|
||||
type: 'update_instances',
|
||||
sources: ['slave'],
|
||||
targets: ['master'],
|
||||
eventProperties: {
|
||||
"instances": {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["id", "name"],
|
||||
properties: {
|
||||
"id": { type: "integer" },
|
||||
"name": { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Attaches all requests and events to the given link
|
||||
*
|
||||
* Loops through all requests and events defined and attaches all of
|
||||
* them to the link. For requests the handler used is looked up on the
|
||||
* link instance as the name of the request + 'RequestHandler'. For
|
||||
* events the the handler used is looked up on the link instance as the
|
||||
* name of the event + 'EventHandler'.
|
||||
*/
|
||||
function attachAllMessages(link) {
|
||||
for (let [name, request] of Object.entries(requests)) {
|
||||
request.attach(link, link[name + 'RequestHandler']);
|
||||
}
|
||||
|
||||
for (let [name, event] of Object.entries(events)) {
|
||||
event.attach(link, link[name + 'EventHandler']);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
Request,
|
||||
InstanceRequest,
|
||||
Event,
|
||||
|
||||
attachAllMessages,
|
||||
|
||||
requests,
|
||||
events,
|
||||
}
|
||||
@@ -36,8 +36,7 @@ modManager.listMods(config, instance);
|
||||
*/
|
||||
async function listMods(config, instance) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const instances = require("./../getInstances")(config).sync();
|
||||
if (instances.includes(instance.name)) {
|
||||
if (true) {
|
||||
factorioAPI.init(false, instance.path("instanceMods"), instance.path("saves"), instance.server.version);
|
||||
factorioAPI.authenticate({
|
||||
username: config.username,
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
const ajv = new (require('ajv'))({
|
||||
verbose: true,
|
||||
format: "full",
|
||||
extendRefs: "fail",
|
||||
strictDefaluts: true,
|
||||
strictKeywords: true,
|
||||
})
|
||||
|
||||
|
||||
const closeSchema = {
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
title: "Close Message",
|
||||
description: "Format for a close messages on a link",
|
||||
properties: {
|
||||
"type": { const: "close" },
|
||||
"data": {
|
||||
additionalProperties: false,
|
||||
required: ["reason"],
|
||||
properties: {
|
||||
"reason": { type: "string" },
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const close = ajv.compile(closeSchema);
|
||||
|
||||
/**
|
||||
* The base format for any message sent over the link
|
||||
*/
|
||||
const messageSchema = {
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
title: "Message",
|
||||
description: "Format for messages on a link",
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
required: ["seq", "type", "data"],
|
||||
properties: {
|
||||
"seq": { type: "integer" },
|
||||
"type": { type: "string" },
|
||||
"data": { type: "object" },
|
||||
},
|
||||
}
|
||||
|
||||
const message = ajv.compile(messageSchema);
|
||||
|
||||
const serverActions = [
|
||||
{},
|
||||
];
|
||||
|
||||
const actionResponse = {
|
||||
additionalProperties: false,
|
||||
required: ["action", "id", "status", "message"],
|
||||
properties: {
|
||||
"action": { enum: ["TODO"] },
|
||||
"id": { type: "integer" },
|
||||
"status": { enum: ["started", "done", "error"] },
|
||||
"message": { type: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
const serverHandshake = ajv.compile({
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
title: "Server Handshake",
|
||||
description: "Message sent from the server to a client during the handshake",
|
||||
allOf: [ messageSchema ],
|
||||
anyOf: [
|
||||
{
|
||||
properties: {
|
||||
"type": { const: "hello" },
|
||||
"data": {
|
||||
additionalProperties: false,
|
||||
required: ["version"],
|
||||
properties: {
|
||||
"version": { type: "string" },
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
properties: {
|
||||
"type": { const: "ready" },
|
||||
"data": {
|
||||
additionalProperties: false,
|
||||
/* XXX anything here?
|
||||
required: ["version"],
|
||||
properties: {
|
||||
"version": { type: "string" },
|
||||
}*/
|
||||
},
|
||||
},
|
||||
},
|
||||
closeSchema,
|
||||
],
|
||||
});
|
||||
|
||||
const clientHandshake = ajv.compile({
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
title: "Client Message",
|
||||
description: "Message sent from a client to the server",
|
||||
allOf: [ messageSchema ],
|
||||
anyOf: [
|
||||
{
|
||||
properties: {
|
||||
"type": { const: "register_slave" },
|
||||
"data": {
|
||||
additionalProperties: false,
|
||||
required: ["agent", "version", "name", "id"],
|
||||
properties: {
|
||||
"agent": { type: "string" },
|
||||
"version": { type: "string" },
|
||||
"name": { type: "string" },
|
||||
"id": { type: "integer" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
properties: {
|
||||
"type": { const: "register_control" },
|
||||
"data": {
|
||||
additionalProperties: false,
|
||||
required: ["agent", "version"],
|
||||
properties: {
|
||||
"agent": { type: "string" },
|
||||
"version": { type: "string" },
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
closeSchema,
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
module.exports = {
|
||||
compile: ajv.compile.bind(ajv),
|
||||
|
||||
message,
|
||||
close,
|
||||
|
||||
serverHandshake,
|
||||
clientHandshake,
|
||||
}
|
||||
Reference in new issue
Block a user