Prefix clusterio/lib imports with lib

Use lib* prefix for the modules impored from the lib package to help
distinguish them more from ordinary variables.  Fix up the naming
convention for files to be consistently lowercase_underscore for
JavaScript files.
This commit is contained in:
Hornwitser committed 2020-10-23 21:22:43 +02:00
1 parent fbbaf3dd3a
commit 24397b75cc
55 files changed
+692 -668

No files matched your search

+115 -115
View File
@@ -13,12 +13,12 @@ const chalk = require("chalk");
const events = require("events");
const path = require("path");
const link = require("@clusterio/lib/link");
const errors = require("@clusterio/lib/errors");
const config = require("@clusterio/lib/config");
const plugin = require("@clusterio/lib/plugin");
const command = require("@clusterio/lib/command");
const sharedCommands = require("@clusterio/lib/shared_commands");
const libLink = require("@clusterio/lib/link");
const libErrors = require("@clusterio/lib/errors");
const libConfig = require("@clusterio/lib/config");
const libPlugin = require("@clusterio/lib/plugin");
const libCommand = require("@clusterio/lib/command");
const libSharedCommands = require("@clusterio/lib/shared_commands");
/**
@@ -59,16 +59,16 @@ function formatOutputColored(output) {
return time + info + output.message;
}
const slaveCommands = new command.CommandTree({ name: "slave", description: "Slave management" });
slaveCommands.add(new command.Command({
const slaveCommands = new libCommand.CommandTree({ name: "slave", description: "Slave management" });
slaveCommands.add(new libCommand.Command({
definition: [["list", "l"], "List slaves connected to the master"],
handler: async function(args, control) {
let response = await link.messages.listSlaves.send(control);
let response = await libLink.messages.listSlaves.send(control);
console.log(asTable(response.list));
},
}));
slaveCommands.add(new command.Command({
slaveCommands.add(new libCommand.Command({
definition: ["generate-token", "Generate token for a slave", (yargs) => {
yargs.option("id", { type: "number", nargs: 1, describe: "Slave id", demandOption: true });
}],
@@ -78,7 +78,7 @@ slaveCommands.add(new command.Command({
},
}));
slaveCommands.add(new command.Command({
slaveCommands.add(new libCommand.Command({
definition: ["create-config", "Create slave config", (yargs) => {
yargs.option("id", { type: "number", nargs: 1, describe: "Slave id", default: null });
yargs.option("name", { type: "string", nargs: 1, describe: "Slave name", default: null });
@@ -90,7 +90,7 @@ slaveCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
let response = await link.messages.createSlaveConfig.send(control, {
let response = await libLink.messages.createSlaveConfig.send(control, {
id: args.id, name: args.name, generate_token: args.generateToken,
});
@@ -103,7 +103,7 @@ slaveCommands.add(new command.Command({
await fs.outputFile(args.output, content, { flag: "wx" });
} catch (err) {
if (err.code === "EEXIST") {
throw new errors.CommandError(`File ${args.output} already exists`);
throw new libErrors.CommandError(`File ${args.output} already exists`);
}
throw err;
}
@@ -112,18 +112,18 @@ slaveCommands.add(new command.Command({
}));
const instanceCommands = new command.CommandTree({
const instanceCommands = new libCommand.CommandTree({
name: "instance", alias: ["i"], description: "Instance management",
});
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: [["list", "l"], "List instances known to the master"],
handler: async function(args, control) {
let response = await link.messages.listInstances.send(control);
let response = await libLink.messages.listInstances.send(control);
console.log(asTable(response.list));
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["create <name>", "Create an instance", (yargs) => {
// XXX TODO: set any specific options?
yargs.positional("name", { describe: "Instance name", type: "string" });
@@ -132,27 +132,27 @@ instanceCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
let instanceConfig = new config.InstanceConfig();
let instanceConfig = new libConfig.InstanceConfig();
await instanceConfig.init();
if (args.id) {
instanceConfig.set("instance.id", args.id);
}
instanceConfig.set("instance.name", args.name);
let serialized_config = instanceConfig.serialize();
let response = await link.messages.createInstance.send(control, { serialized_config });
let response = await libLink.messages.createInstance.send(control, { serialized_config });
},
}));
const instanceConfigCommands = new command.CommandTree({
const instanceConfigCommands = new libCommand.CommandTree({
name: "config", alias: ["c"], description: "Instance config management",
});
instanceConfigCommands.add(new command.Command({
instanceConfigCommands.add(new libCommand.Command({
definition: ["list <instance>", "List configuration for an instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to list config for", type: "string" });
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
let response = await link.messages.getInstanceConfig.send(control, { instance_id: instanceId });
let instanceId = await libCommand.resolveInstance(control, args.instance);
let response = await libLink.messages.getInstanceConfig.send(control, { instance_id: instanceId });
for (let group of response.serialized_config.groups) {
for (let [name, value] of Object.entries(group.fields)) {
@@ -162,15 +162,15 @@ instanceConfigCommands.add(new command.Command({
},
}));
instanceConfigCommands.add(new command.Command({
instanceConfigCommands.add(new libCommand.Command({
definition: ["set <instance> <field> <value>", "Set field in instance config", (yargs) => {
yargs.positional("instance", { describe: "Instance to set config on", type: "string" });
yargs.positional("field", { describe: "Field to set", type: "string" });
yargs.positional("value", { describe: "Value to set", type: "string" });
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
await link.messages.setInstanceConfigField.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
await libLink.messages.setInstanceConfigField.send(control, {
instance_id: instanceId,
field: args.field,
value: args.value,
@@ -178,7 +178,7 @@ instanceConfigCommands.add(new command.Command({
},
}));
instanceConfigCommands.add(new command.Command({
instanceConfigCommands.add(new libCommand.Command({
definition: ["set-prop <instance> <field> <prop> <value>", "Set property of field in instance config", (yargs) => {
yargs.positional("instance", { describe: "Instance to set config on", type: "string" });
yargs.positional("field", { describe: "Field to set", type: "string" });
@@ -186,8 +186,8 @@ instanceConfigCommands.add(new command.Command({
yargs.positional("value", { describe: "JSON parsed value to set", type: "string" });
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
await link.messages.setInstanceConfigProp.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
await libLink.messages.setInstanceConfigProp.send(control, {
instance_id: instanceId,
field: args.field,
prop: args.prop,
@@ -197,48 +197,48 @@ instanceConfigCommands.add(new command.Command({
}));
instanceCommands.add(instanceConfigCommands);
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["assign <instance> <slave>", "Assign instance to a slave", (yargs) => {
yargs.positional("instance", { describe: "Instance to assign", type: "string" });
yargs.positional("slave", { describe: "Slave to assign to", type: "string" });
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
let slaveId = await command.resolveSlave(control, args.slave);
await link.messages.assignInstanceCommand.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
let slaveId = await libCommand.resolveSlave(control, args.slave);
await libLink.messages.assignInstanceCommand.send(control, {
instance_id: instanceId,
slave_id: slaveId,
});
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["create-save <instance>", "Create a new save on an instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to create on", type: "string" });
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
await link.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await link.messages.createSave.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
await libLink.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await libLink.messages.createSave.send(control, {
instance_id: instanceId,
});
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["export-data <instance>", "Export item icons and locale from instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to export from", type: "string" });
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
await link.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await link.messages.exportData.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
await libLink.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await libLink.messages.exportData.send(control, {
instance_id: instanceId,
});
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["start <instance>", "Start instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to start", type: "string" });
yargs.options({
@@ -247,16 +247,16 @@ instanceCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
await link.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await link.messages.startInstance.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
await libLink.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await libLink.messages.startInstance.send(control, {
instance_id: instanceId,
save: args.save || null,
});
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["load-scenario <instance> <scenario>", "Start instance by loading a scenario", (yargs) => {
yargs.positional("instance", { describe: "Instance to start", type: "string" });
yargs.positional("scenario", { describe: "Scenario to load", type: "string" });
@@ -265,47 +265,47 @@ instanceCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
await link.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await link.messages.loadScenario.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
await libLink.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await libLink.messages.loadScenario.send(control, {
instance_id: instanceId,
scenario: args.scenario || null,
});
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["stop <instance>", "Stop instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to stop", type: "string" });
}],
handler: async function(args, control) {
let instanceId = await command.resolveInstance(control, args.instance);
await link.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await link.messages.stopInstance.send(control, {
let instanceId = await libCommand.resolveInstance(control, args.instance);
await libLink.messages.setInstanceOutputSubscriptions.send(control, { instance_ids: [instanceId] });
let response = await libLink.messages.stopInstance.send(control, {
instance_id: instanceId,
});
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["delete <instance>", "Delete instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to delete", type: "string" });
}],
handler: async function(args, control) {
let response = await link.messages.deleteInstance.send(control, {
instance_id: await command.resolveInstance(control, args.instance),
let response = await libLink.messages.deleteInstance.send(control, {
instance_id: await libCommand.resolveInstance(control, args.instance),
});
},
}));
instanceCommands.add(new command.Command({
instanceCommands.add(new libCommand.Command({
definition: ["send-rcon <instance> <command>", "Send RCON command", (yargs) => {
yargs.positional("instance", { describe: "Instance to send to", type: "string" });
yargs.positional("command", { describe: "command to send", type: "string" });
}],
handler: async function(args, control) {
let response = await link.messages.sendRcon.send(control, {
instance_id: await command.resolveInstance(control, args.instance),
let response = await libLink.messages.sendRcon.send(control, {
instance_id: await libCommand.resolveInstance(control, args.instance),
command: args.command,
});
@@ -314,26 +314,26 @@ instanceCommands.add(new command.Command({
},
}));
const permissionCommands = new command.CommandTree({ name: "permission", description: "Permission inspection" });
permissionCommands.add(new command.Command({
const permissionCommands = new libCommand.CommandTree({ name: "permission", description: "Permission inspection" });
permissionCommands.add(new libCommand.Command({
definition: [["list", "l"], "List permissions in the cluster"],
handler: async function(args, control) {
let response = await link.messages.listPermissions.send(control);
let response = await libLink.messages.listPermissions.send(control);
console.log(asTable(response.list));
},
}));
const roleCommands = new command.CommandTree({ name: "role", description: "Role management" });
roleCommands.add(new command.Command({
const roleCommands = new libCommand.CommandTree({ name: "role", description: "Role management" });
roleCommands.add(new libCommand.Command({
definition: [["list", "l"], "List roles in the cluster"],
handler: async function(args, control) {
let response = await link.messages.listRoles.send(control);
let response = await libLink.messages.listRoles.send(control);
console.log(asTable(response.list));
},
}));
roleCommands.add(new command.Command({
roleCommands.add(new libCommand.Command({
definition: ["create <name>", "Create a new role", (yargs) => {
yargs.positional("name", { describe: "Name of role to create", type: "string" });
yargs.options({
@@ -342,7 +342,7 @@ roleCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
let response = await link.messages.createRole.send(control, {
let response = await libLink.messages.createRole.send(control, {
name: args.name,
description: args.description,
permissions: args.permissions,
@@ -351,7 +351,7 @@ roleCommands.add(new command.Command({
},
}));
roleCommands.add(new command.Command({
roleCommands.add(new libCommand.Command({
definition: ["edit <role>", "Edit existing role", (yargs) => {
yargs.positional("role", { describe: "Role to edit", type: "string" });
yargs.options({
@@ -362,7 +362,7 @@ roleCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
let role = await command.retrieveRole(control, args.role);
let role = await libCommand.retrieveRole(control, args.role);
if (args.name !== undefined) {
role.name = args.name;
@@ -373,44 +373,44 @@ roleCommands.add(new command.Command({
if (args.permissions !== undefined) {
role.permissions = args.permissions;
}
await link.messages.updateRole.send(control, role);
await libLink.messages.updateRole.send(control, role);
if (args.grantDefault) {
await link.messages.grantDefaultRolePermissions.send(control, { id: role.id });
await libLink.messages.grantDefaultRolePermissions.send(control, { id: role.id });
}
},
}));
roleCommands.add(new command.Command({
roleCommands.add(new libCommand.Command({
definition: ["delete <role>", "Delete role", (yargs) => {
yargs.positional("role", { describe: "Role to delete", type: "string" });
}],
handler: async function(args, control) {
let role = await command.retrieveRole(control, args.role);
await link.messages.deleteRole.send(control, { id: role.id });
let role = await libCommand.retrieveRole(control, args.role);
await libLink.messages.deleteRole.send(control, { id: role.id });
},
}));
const userCommands = new command.CommandTree({ name: "user", alias: ["u"], description: "User management" });
userCommands.add(new command.Command({
const userCommands = new libCommand.CommandTree({ name: "user", alias: ["u"], description: "User management" });
userCommands.add(new libCommand.Command({
definition: [["list", "l"], "List user in the cluster"],
handler: async function(args, control) {
let response = await link.messages.listUsers.send(control);
let response = await libLink.messages.listUsers.send(control);
console.log(asTable(response.list));
},
}));
userCommands.add(new command.Command({
userCommands.add(new libCommand.Command({
definition: ["create <name>", "Create a user", (yargs) => {
yargs.positional("name", { describe: "Name of user to create", type: "string" });
}],
handler: async function(args, control) {
await link.messages.createUser.send(control, { name: args.name });
await libLink.messages.createUser.send(control, { name: args.name });
},
}));
userCommands.add(new command.Command({
userCommands.add(new libCommand.Command({
definition: ["set-admin <user>", "Promote or demote a user to admin", (yargs) => {
yargs.positional("user", { describe: "Name of user set admin status for", type: "string" });
yargs.options({
@@ -419,13 +419,13 @@ userCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
await link.messages.setUserAdmin.send(control, {
await libLink.messages.setUserAdmin.send(control, {
name: args.user, create: args.create, admin: !args.revoke,
});
},
}));
userCommands.add(new command.Command({
userCommands.add(new libCommand.Command({
definition: ["set-whitelisted <user>", "Add or remove user from the whitelist", (yargs) => {
yargs.positional("user", { describe: "Name of user to set whitelist status for", type: "string" });
yargs.options({
@@ -434,13 +434,13 @@ userCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
await link.messages.setUserWhitelisted.send(control, {
await libLink.messages.setUserWhitelisted.send(control, {
name: args.user, create: args.create, whitelisted: !args.remove,
});
},
}));
userCommands.add(new command.Command({
userCommands.add(new libCommand.Command({
definition: ["set-banned <user>", "Ban or pardon user from banlist", (yargs) => {
yargs.positional("user", { describe: "Name of user to set ban status for", type: "string" });
yargs.options({
@@ -450,19 +450,19 @@ userCommands.add(new command.Command({
});
}],
handler: async function(args, control) {
await link.messages.setUserBanned.send(control, {
await libLink.messages.setUserBanned.send(control, {
name: args.user, create: args.create, banned: !args.pardon, reason: args.reason,
});
},
}));
userCommands.add(new command.Command({
userCommands.add(new libCommand.Command({
definition: ["set-roles <user> [roles...]", "Replace user roles", (yargs) => {
yargs.positional("user", { describe: "Name of user to change roles for", type: "string" });
yargs.positional("roles", { describe: "roles to assign", type: "string" });
}],
handler: async function(args, control) {
let response = await link.messages.listRoles.send(control);
let response = await libLink.messages.listRoles.send(control);
let resolvedRoles = [];
for (let roleName of args.roles) {
@@ -481,29 +481,29 @@ userCommands.add(new command.Command({
}
if (!found) {
throw new errors.CommandError(`No role named ${roleName}`);
throw new libErrors.CommandError(`No role named ${roleName}`);
}
}
}
await link.messages.updateUserRoles.send(control, { name: args.user, roles: resolvedRoles });
await libLink.messages.updateUserRoles.send(control, { name: args.user, roles: resolvedRoles });
},
}));
userCommands.add(new command.Command({
userCommands.add(new libCommand.Command({
definition: ["delete <user>", "Delete user", (yargs) => {
yargs.positional("user", { describe: "Name of user to delete", type: "string" });
}],
handler: async function(args, control) {
await link.messages.deleteUser.send(control, { name: args.user });
await libLink.messages.deleteUser.send(control, { name: args.user });
},
}));
const debugCommands = new command.CommandTree({ name: "debug", description: "Debugging utilities" });
debugCommands.add(new command.Command({
const debugCommands = new libCommand.CommandTree({ name: "debug", description: "Debugging utilities" });
debugCommands.add(new libCommand.Command({
definition: ["dump-ws", "Dump WebSocket messages sent and received by master", (yargs) => { }],
handler: async function(args, control) {
await link.messages.debugDumpWs.send(control);
await libLink.messages.debugDumpWs.send(control);
return new Promise(() => {});
},
}));
@@ -513,7 +513,7 @@ debugCommands.add(new command.Command({
* Connector for control connection to master server
* @private
*/
class ControlConnector extends link.WebSocketClientConnector {
class ControlConnector extends libLink.WebSocketClientConnector {
constructor(url, reconnectDelay, token) {
super(url, reconnectDelay);
this._token = token;
@@ -535,11 +535,11 @@ class ControlConnector extends link.WebSocketClientConnector {
* Connects to the master server over WebSocket and sends commands to it.
* @static
*/
class Control extends link.Link {
class Control extends libLink.Link {
constructor(connector, controlPlugins) {
super("control", "master", connector);
link.attachAllMessages(this);
libLink.attachAllMessages(this);
/**
* Mapping of plugin names to their instance for loaded plugins.
@@ -547,7 +547,7 @@ class Control extends link.Link {
*/
this.plugins = controlPlugins;
for (let controlPlugin of controlPlugins.values()) {
plugin.attachPluginMessages(this, controlPlugin.info, controlPlugin);
libPlugin.attachPluginMessages(this, controlPlugin.info, controlPlugin);
}
}
@@ -564,9 +564,9 @@ class Control extends link.Link {
this.connector.setTimeout(30);
try {
await link.messages.prepareDisconnect.send(this);
await libLink.messages.prepareDisconnect.send(this);
} catch (err) {
if (!(err instanceof errors.SessionLost)) {
if (!(err instanceof libErrors.SessionLost)) {
throw err;
}
}
@@ -593,8 +593,8 @@ async function startControl() {
default: "plugin-list.json",
type: "string",
})
.command("plugin", "Manage available plugins", sharedCommands.pluginCommand)
.command("control-config", "Manage Control config", config.configCommand)
.command("plugin", "Manage available plugins", libSharedCommands.pluginCommand)
.command("control-config", "Manage Control config", libConfig.configCommand)
.wrap(yargs.terminalWidth())
.help(false) // Disable help to avoid triggering it on the first parse.
;
@@ -614,12 +614,12 @@ async function startControl() {
// If the command is plugin management we don't try to load plugins
if (args._[0] === "plugin") {
await sharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
await libSharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
return;
}
// Add all cluster management commands including ones from plugins
const rootCommands = new command.CommandTree({ name: "clusterioctl", description: "Manage cluster" });
const rootCommands = new libCommand.CommandTree({ name: "clusterioctl", description: "Manage cluster" });
rootCommands.add(slaveCommands);
rootCommands.add(instanceCommands);
rootCommands.add(permissionCommands);
@@ -628,9 +628,9 @@ async function startControl() {
rootCommands.add(debugCommands);
console.log("Loading Plugin info");
let pluginInfos = await plugin.loadPluginInfos(pluginList);
config.registerPluginConfigGroups(pluginInfos);
config.finalizeConfigs();
let pluginInfos = await libPlugin.loadPluginInfos(pluginList);
libConfig.registerPluginConfigGroups(pluginInfos);
libConfig.finalizeConfigs();
let controlPlugins = new Map();
for (let pluginInfo of pluginInfos) {
@@ -659,7 +659,7 @@ async function startControl() {
;
console.log(`Loading config from ${args.config}`);
let controlConfig = new config.ControlConfig();
let controlConfig = new libConfig.ControlConfig();
try {
await controlConfig.load(JSON.parse(await fs.readFile(args.config)));
@@ -680,14 +680,14 @@ async function startControl() {
// Handle the control-config command before trying to connect.
if (args._[0] === "control-config") {
await config.handleConfigCommand(args, controlConfig, args.config);
await libConfig.handleConfigCommand(args, controlConfig, args.config);
return;
}
// Determine which command is being executed.
let commandPath = [...args._];
let targetCommand = rootCommands;
while (commandPath.length && targetCommand instanceof command.CommandTree) {
while (commandPath.length && targetCommand instanceof libCommand.CommandTree) {
targetCommand = targetCommand.get(commandPath.shift());
}
@@ -707,8 +707,8 @@ async function startControl() {
try {
await controlConnector.connect();
} catch(err) {
if (err instanceof errors.AuthenticationFailed) {
throw new errors.StartupError(err.message);
if (err instanceof libErrors.AuthenticationFailed) {
throw new libErrors.StartupError(err.message);
}
throw err;
}
@@ -727,11 +727,11 @@ async function startControl() {
} catch (err) {
keepOpen = false;
if (err instanceof errors.CommandError) {
if (err instanceof libErrors.CommandError) {
console.error(`Error running command: ${err.message}`);
process.exitCode = 1;
} else if (err instanceof errors.RequestError) {
} else if (err instanceof libErrors.RequestError) {
console.error(`Error sending request: ${err.message}`);
process.exitCode = 1;
@@ -763,7 +763,7 @@ I version of clusterio. Expect things to break. I
`
);
startControl().catch(err => {
if (!(err instanceof errors.StartupError)) {
if (!(err instanceof libErrors.StartupError)) {
console.error(`
+----------------------------------------------------------------+
| Unexpected error occured while starting control, please report |
+8 -8
View File
@@ -7,8 +7,8 @@
* @module lib/command
*/
"use strict";
const link = require("@clusterio/lib/link");
const errors = require("@clusterio/lib/errors");
const libLink = require("@clusterio/lib/link");
const libErrors = require("@clusterio/lib/errors");
/**
* Represents a command that can be runned by clusterioctl
@@ -150,7 +150,7 @@ async function resolveSlave(client, slaveName) {
if (/^-?\d+$/.test(slaveName)) {
slaveId = parseInt(slaveName, 10);
} else {
let response = await link.messages.listSlaves.send(client);
let response = await libLink.messages.listSlaves.send(client);
for (let slave of response.list) {
if (slave.name === slaveName) {
slaveId = slave.id;
@@ -159,7 +159,7 @@ async function resolveSlave(client, slaveName) {
}
if (slaveId === undefined) {
throw new errors.CommandError(`No slave named ${slaveName}`);
throw new libErrors.CommandError(`No slave named ${slaveName}`);
}
}
@@ -182,7 +182,7 @@ async function resolveInstance(client, instanceName) {
if (/^-?\d+$/.test(instanceName)) {
instanceId = parseInt(instanceName, 10);
} else {
let response = await link.messages.listInstances.send(client);
let response = await libLink.messages.listInstances.send(client);
for (let instance of response.list) {
if (instance.name === instanceName) {
instanceId = instance.id;
@@ -191,7 +191,7 @@ async function resolveInstance(client, instanceName) {
}
if (instanceId === undefined) {
throw new errors.CommandError(`No instance named ${instanceName}`);
throw new libErrors.CommandError(`No instance named ${instanceName}`);
}
}
@@ -210,7 +210,7 @@ async function resolveInstance(client, instanceName) {
* @static
*/
async function retrieveRole(client, roleName) {
let response = await link.messages.listRoles.send(client);
let response = await libLink.messages.listRoles.send(client);
let resolvedRole;
if (/^-?\d+$/.test(roleName)) {
@@ -232,7 +232,7 @@ async function retrieveRole(client, roleName) {
}
if (!resolvedRole) {
throw new errors.CommandError(`No role named ${roleName}`);
throw new libErrors.CommandError(`No role named ${roleName}`);
}
return resolvedRole;
+2 -2
View File
@@ -6,7 +6,7 @@ const ini = require("ini");
const Jimp = require("jimp");
const JSZip = require("jszip");
const buildMod = require("@clusterio/lib/build_mod");
const libBuildMod = require("@clusterio/lib/build_mod");
/**
* Generate the export mod needed for exportData
@@ -29,7 +29,7 @@ async function generateExportMod(server) {
}
}
await buildMod.build({
await libBuildMod.build({
clean: false,
build: true,
pack: true,
+2 -2
View File
@@ -7,7 +7,7 @@ const jszip = require("jszip");
const path = require("path");
const semver = require("semver");
const hash = require("@clusterio/lib/hash");
const libHash = require("@clusterio/lib/hash");
const knownScenarios = {
@@ -225,7 +225,7 @@ async function patch(savePath, modules) {
// No info file present, try to detect if it's a known compatible scenario.
} else {
let controlStream = root.file("control.lua").nodeStream("nodebuffer");
let controlHash = await hash.hashStream(controlStream);
let controlHash = await libHash.hashStream(controlStream);
if (controlHash in knownScenarios) {
patchInfo = {
+2 -2
View File
@@ -9,7 +9,7 @@ const crypto = require("crypto");
const ini = require("ini");
const rconClient = require("rcon-client");
const errors = require("@clusterio/lib/errors");
const libErrors = require("@clusterio/lib/errors");
/**
@@ -705,7 +705,7 @@ class FactorioServer extends events.EventEmitter {
if (this._state !== "stopping") {
if (this._unexpected.length === 0) {
if (signal === "SIGKILL") {
this.emit("error", new errors.EnvironmentError(
this.emit("error", new libErrors.EnvironmentError(
"Factorio server was unexpectedly killed, is the system low on memory?"
));
-3
View File
@@ -1,3 +0,0 @@
"use strict";
const fileOps = require("./fileOps");
module.exports = fileOps;
@@ -1,5 +1,5 @@
/**
* @module lib/fileOps
* @module lib/file_ops
*/
"use strict";
const fs = require("fs-extra");
+7 -7
View File
@@ -3,8 +3,8 @@
const events = require("events");
const WebSocket = require("isomorphic-ws");
const schema = require("@clusterio/lib/schema");
const errors = require("@clusterio/lib/errors");
const libSchema = require("@clusterio/lib/schema");
const libErrors = require("@clusterio/lib/errors");
/**
@@ -60,10 +60,10 @@ class WebSocketBaseConnector extends events.EventEmitter {
}
_processHeartbeat(message) {
if (!schema.heartbeat(message)) {
if (!libSchema.heartbeat(message)) {
console.log("SOCKET | closing after received invalid heartbeat:", message);
this._socket.close(1002, "Invalid heartbeat");
console.log(schema.heartbeat.errors);
console.log(libSchema.heartbeat.errors);
return;
}
@@ -100,7 +100,7 @@ class WebSocketBaseConnector extends events.EventEmitter {
*/
send(type, data) {
if (!["handshake", "connected", "closing"].includes(this._state)) {
throw new errors.SessionLost("No session");
throw new libErrors.SessionLost("No session");
}
let message = { seq: this._seq, type, data };
this._sendBuffer.push(message);
@@ -287,7 +287,7 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
console.log(`SOCKET | Close (code: ${event.code}, reason: ${event.reason})`);
// Authentication failed
if (event.code === 4003) {
this.emit("error", new errors.AuthenticationFailed(event.reason));
this.emit("error", new libErrors.AuthenticationFailed(event.reason));
this._state = "closing";
}
@@ -345,7 +345,7 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
}
_processHandshake(message) {
if (!schema.serverHandshake(message)) {
if (!libSchema.serverHandshake(message)) {
console.log("SOCKET | closing after received invalid handshake:", message);
this._socket.close(1002, "Invalid handshake");
return;
+10 -10
View File
@@ -1,8 +1,8 @@
// Implementation of Link class
"use strict";
const schema = require("@clusterio/lib/schema");
const errors = require("@clusterio/lib/errors");
const libSchema = require("@clusterio/lib/schema");
const libErrors = require("@clusterio/lib/errors");
const messages = require("./messages");
// Some definitions for the terminology used here:
@@ -34,7 +34,7 @@ class Link {
try {
this.processMessage(payload);
} catch (err) {
if (err instanceof errors.InvalidMessage) {
if (err instanceof libErrors.InvalidMessage) {
console.error(`Invalid message on ${this.source}-${this.target} link: ${err.message}`);
if (err.errors) {
console.error(err.errors);
@@ -48,7 +48,7 @@ class Link {
connector.on("invalidate", () => {
for (let waiterType of this._waiters.values()) {
for (let waiter of waiterType) {
waiter.reject(new errors.SessionLost("Session Lost"));
waiter.reject(new libErrors.SessionLost("Session Lost"));
}
}
@@ -58,7 +58,7 @@ class Link {
connector.on("close", () => {
for (let waiterType of this._waiters.values()) {
for (let waiter of waiterType) {
waiter.reject(new errors.SessionLost("Session Closed"));
waiter.reject(new libErrors.SessionLost("Session Closed"));
}
}
@@ -78,17 +78,17 @@ class Link {
* handlers/waiters were invoked to handle the message.
*/
processMessage(message) {
if (!schema.message(message)) {
throw new errors.InvalidMessage("Malformed", schema.message.errors);
if (!libSchema.message(message)) {
throw new libErrors.InvalidMessage("Malformed", libSchema.message.errors);
}
let validator = this._validators.get(message.type);
if (!validator) {
throw new errors.InvalidMessage(`No validator for ${message.type} on ${this.source}-${this.target}`);
throw new libErrors.InvalidMessage(`No validator for ${message.type} on ${this.source}-${this.target}`);
}
if (!validator(message)) {
throw new errors.InvalidMessage(`Validation failed for ${message.type}`, validator.errors);
throw new libErrors.InvalidMessage(`Validation failed for ${message.type}`, validator.errors);
}
let hadHandlers = this._processHandler(message);
@@ -96,7 +96,7 @@ class Link {
if (!hadWaiters && !hadHandlers) {
// XXX console.error(`Unhandled message: ${JSON.stringify(message, null, 4)}`);
throw new errors.InvalidMessage(`Unhandled message ${message.type}`);
throw new libErrors.InvalidMessage(`Unhandled message ${message.type}`);
}
}
+7 -7
View File
@@ -1,7 +1,7 @@
// Message definitions for links
"use strict";
const schema = require("@clusterio/lib/schema");
const errors = require("@clusterio/lib/errors");
const libSchema = require("@clusterio/lib/schema");
const libErrors = require("@clusterio/lib/errors");
/**
* Represents a message that can be sent over the link
@@ -88,7 +88,7 @@ class Request extends Message {
throw new Error(`Invalid forwardTo value ${forwardTo}`);
}
this._requestValidator = schema.compile({
this._requestValidator = libSchema.compile({
$schema: "http://json-schema.org/draft-07/schema#",
properties: {
"type": { const: this.requestType },
@@ -100,7 +100,7 @@ class Request extends Message {
},
});
this._responseValidator = schema.compile({
this._responseValidator = libSchema.compile({
$schema: "http://json-schema.org/draft-07/schema#",
properties: {
"type": { const: this.responseType },
@@ -195,7 +195,7 @@ class Request extends Message {
link.connector.send(this.responseType, { ...response, seq: message.seq });
}).catch(err => {
if (!(err instanceof errors.RequestError)) {
if (!(err instanceof libErrors.RequestError)) {
console.error(`Unexpected error while responding to ${this.requestType}`, err);
}
link.connector.send(this.responseType, { seq: message.seq, error: err.message });
@@ -223,7 +223,7 @@ class Request extends Message {
let seq = link.connector.send(this.requestType, data);
let responseMessage = await link.waitFor(this.responseType, { seq });
if (responseMessage.data.error) {
throw new errors.RequestError(responseMessage.data.error);
throw new libErrors.RequestError(responseMessage.data.error);
}
return responseMessage.data;
}
@@ -702,7 +702,7 @@ class Event extends Message {
}
this.eventType = type + "_event";
this._eventValidator = schema.compile({
this._eventValidator = libSchema.compile({
$schema: "http://json-schema.org/draft-07/schema#",
properties: {
"type": { const: this.eventType },
@@ -1,6 +1,6 @@
/**
* Utilities for dealing with Lua
* @module lib/luaTools
* @module lib/lua_tools
*/
"use strict";
File renamed without changes.
+3 -3
View File
@@ -5,7 +5,7 @@
"use strict";
const path = require("path");
const errors = require("@clusterio/lib/errors");
const libErrors = require("@clusterio/lib/errors");
/**
@@ -409,11 +409,11 @@ async function loadPluginInfos(pluginList) {
pluginPackage = require(path.posix.join(pluginPath, "package.json"));
} catch (err) {
throw new errors.PluginError(pluginName, err);
throw new libErrors.PluginError(pluginName, err);
}
if (pluginInfo.name !== pluginName) {
throw new errors.EnvironmentError(
throw new libErrors.EnvironmentError(
`Expected plugin at ${pluginPath} to be named ${pluginName} but got ${pluginInfo.name}`
);
}
+101 -101
View File
@@ -42,17 +42,17 @@ let pluginList = {};
let devMiddleware;
// homebrew modules
const generateSSLcert = require("./src/generate_ssl_cert");
const generateSslCert = require("./src/generate_ssl_cert");
const routes = require("./src/routes");
const database = require("@clusterio/lib/database");
const schema = require("@clusterio/lib/schema");
const link = require("@clusterio/lib/link");
const errors = require("@clusterio/lib/errors");
const plugin = require("@clusterio/lib/plugin");
const prometheus = require("@clusterio/lib/prometheus");
const config = require("@clusterio/lib/config");
const users = require("@clusterio/lib/users");
const sharedCommands = require("@clusterio/lib/shared_commands");
const libDatabase = require("@clusterio/lib/database");
const libSchema = require("@clusterio/lib/schema");
const libLink = require("@clusterio/lib/link");
const libErrors = require("@clusterio/lib/errors");
const libPlugin = require("@clusterio/lib/plugin");
const libPrometheus = require("@clusterio/lib/prometheus");
const libConfig = require("@clusterio/lib/config");
const libUsers = require("@clusterio/lib/users");
const libSharedCommands = require("@clusterio/lib/shared_commands");
const express = require("express");
const compression = require("compression");
@@ -100,34 +100,34 @@ function serveWeb(route) {
app.use(express.static(path.join(__dirname, "static")));
app.use(express.static("static")); // Used for data export files
const endpointHitCounter = new prometheus.Counter(
const endpointHitCounter = new libPrometheus.Counter(
"clusterio_master_http_endpoint_hits_total",
"How many requests a particular HTTP endpoint has gotten",
{ labels: ["route"] }
);
const wsMessageCounter = new prometheus.Counter(
const wsMessageCounter = new libPrometheus.Counter(
"clusterio_master_websocket_message_total",
"How many messages have been received over WebSocket on the master server",
{ labels: ["direction"] }
);
const wsConnectionsCounter = new prometheus.Counter(
const wsConnectionsCounter = new libPrometheus.Counter(
"clusterio_master_websocket_connections_total",
"How many WebSocket connections have been initiated on the master server"
);
const wsRejectedConnectionsCounter = new prometheus.Counter(
const wsRejectedConnectionsCounter = new libPrometheus.Counter(
"clusterio_master_websocket_rejected_connections_total",
"How many WebSocket connections have been rejected during the handshake on the master server"
);
const wsActiveConnectionsGauge = new prometheus.Gauge(
const wsActiveConnectionsGauge = new libPrometheus.Gauge(
"clusterio_master_websocket_active_connections",
"How many WebSocket connections are currently open to the master server"
);
const wsActiveSlavesGauge = new prometheus.Gauge(
const wsActiveSlavesGauge = new libPrometheus.Gauge(
"clusterio_master_active_slaves",
"How many slaves are currently connected to the master"
);
@@ -137,7 +137,7 @@ async function getMetrics(req, res, next) {
endpointHitCounter.labels(req.route.path).inc();
let results = [];
let pluginResults = await plugin.invokeHook(masterPlugins, "onMetrics");
let pluginResults = await libPlugin.invokeHook(masterPlugins, "onMetrics");
for (let metricIterator of pluginResults) {
for await (let metric of metricIterator) {
results.push(metric);
@@ -147,10 +147,10 @@ async function getMetrics(req, res, next) {
let requests = [];
for (let slaveConnection of slaveConnections.values()) {
// XXX this needs a timeout
requests.push(link.messages.getMetrics.send(slaveConnection));
requests.push(libLink.messages.getMetrics.send(slaveConnection));
}
for await (let result of await prometheus.defaultRegistry.collect()) {
for await (let result of await libPrometheus.defaultRegistry.collect()) {
results.push(result);
}
@@ -169,15 +169,15 @@ async function getMetrics(req, res, next) {
}
for (let result of resultMap.values()) {
results.push(prometheus.deserializeResult(result));
results.push(libPrometheus.deserializeResult(result));
}
wsActiveConnectionsGauge.set(activeConnectors.size);
wsActiveSlavesGauge.set(slaveConnections.size);
let text = await prometheus.exposition(results);
res.set("Content-Type", prometheus.exposition.contentType);
let text = await libPrometheus.exposition(results);
res.set("Content-Type", libPrometheus.exposition.contentType);
res.send(text);
}
app.get("/metrics", (req, res, next) => getMetrics(req, res, next).catch(next));
@@ -241,7 +241,7 @@ app.put("/api/upload-export",
(req, res, next) => uploadExport(req, res, next).catch(next)
);
const masterConnectedClientsCount = new prometheus.Gauge(
const masterConnectedClientsCount = new libPrometheus.Gauge(
"clusterio_master_connected_clients_count", "How many clients are currently connected to this master server",
{
labels: ["type"], callback: async function(gauge) {
@@ -264,7 +264,7 @@ const db = {};
async function loadMap(databaseDirectory, file) {
let databasePath = path.resolve(databaseDirectory, file);
console.log(`Loading ${databasePath}`);
return await database.loadJsonArrayAsMap(databasePath);
return await libDatabase.loadJsonArrayAsMap(databasePath);
}
async function loadInstances(databaseDirectory, file) {
@@ -275,7 +275,7 @@ async function loadInstances(databaseDirectory, file) {
try {
let serialized = JSON.parse(await fs.readFile(filePath));
for (let serializedConfig of serialized) {
let instanceConfig = new config.InstanceConfig();
let instanceConfig = new libConfig.InstanceConfig();
await instanceConfig.load(serializedConfig);
let status = instanceConfig.get("instance.assigned_slave") === null ? "unassigned" : "unknown";
instances.set(instanceConfig.get("instance.id"), { config: instanceConfig, status });
@@ -296,12 +296,12 @@ async function loadUsers(databaseDirectory, file) {
try {
let content = JSON.parse(await fs.readFile(path.join(databaseDirectory, file)));
for (let serializedRole of content.roles) {
let role = new users.Role(serializedRole);
let role = new libUsers.Role(serializedRole);
loadedRoles.set(role.id, role);
}
for (let serializedUser of content.users) {
let user = new users.User(serializedUser, loadedRoles);
let user = new libUsers.User(serializedUser, loadedRoles);
loadedUsers.set(user.name, user);
}
@@ -311,8 +311,8 @@ async function loadUsers(databaseDirectory, file) {
}
// Create default roles if loading failed
users.ensureDefaultAdminRole(loadedRoles);
users.ensureDefaultPlayerRole(loadedRoles);
libUsers.ensureDefaultAdminRole(loadedRoles);
libUsers.ensureDefaultPlayerRole(loadedRoles);
}
db.roles = loadedRoles;
@@ -333,7 +333,7 @@ function createUser(name) {
}
let defaultRoleId = masterConfig.get("master.default_role_id");
let user = new users.User({ name, roles: [defaultRoleId] }, db.roles);
let user = new libUsers.User({ name, roles: [defaultRoleId] }, db.roles);
db.users.set(name, user);
return user;
}
@@ -348,7 +348,7 @@ function createUser(name) {
async function saveMap(databaseDirectory, file, map) {
let databasePath = path.resolve(databaseDirectory, file);
console.log(`Saving ${databasePath}`);
await database.saveMapAsJsonArray(databasePath, map);
await libDatabase.saveMapAsJsonArray(databasePath, map);
}
async function saveInstances(databaseDirectory, file, instances) {
@@ -394,7 +394,7 @@ async function shutdown() {
await saveInstances(masterConfig.get("master.database_directory"), "instances.json", db.instances);
await saveUsers(masterConfig.get("master.database_directory"), "users.json");
await plugin.invokeHook(masterPlugins, "onShutdown");
await libPlugin.invokeHook(masterPlugins, "onShutdown");
stopAcceptingNewSessions = true;
@@ -418,7 +418,7 @@ async function shutdown() {
try {
await task;
} catch (err) {
if (!(err instanceof errors.SessionLost)) {
if (!(err instanceof libErrors.SessionLost)) {
console.log("Unexpected error disconnecting connector");
console.log(err);
}
@@ -455,32 +455,32 @@ async function shutdown() {
*
* @extends module:lib/link.Link
*/
class BaseConnection extends link.Link {
class BaseConnection extends libLink.Link {
constructor(target, connector) {
super("master", target, connector);
link.attachAllMessages(this);
libLink.attachAllMessages(this);
for (let masterPlugin of masterPlugins.values()) {
plugin.attachPluginMessages(this, masterPlugin.info, masterPlugin);
libPlugin.attachPluginMessages(this, masterPlugin.info, masterPlugin);
}
}
async forwardRequestToInstance(message, request) {
let instance = db.instances.get(message.data.instance_id);
if (!instance) {
throw new errors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
}
let slaveId = instance.config.get("instance.assigned_slave");
if (slaveId === null) {
throw new errors.RequestError("Instance is not assigned to a slave");
throw new libErrors.RequestError("Instance is not assigned to a slave");
}
let connection = slaveConnections.get(slaveId);
if (!connection) {
throw new errors.RequestError("Slave containing instance is not connected");
throw new libErrors.RequestError("Slave containing instance is not connected");
}
if (request.plugin && !connection.plugins.has(request.plugin)) {
throw new errors.RequestError(`Slave containing instance does not have ${request.plugin} plugin`);
throw new libErrors.RequestError(`Slave containing instance does not have ${request.plugin} plugin`);
}
return await request.send(connection, message.data);
@@ -516,16 +516,16 @@ class BaseConnection extends link.Link {
}
async prepareDisconnectRequestHandler(message, request) {
await plugin.invokeHook(masterPlugins, "onPrepareSlaveDisconnect", this);
await libPlugin.invokeHook(masterPlugins, "onPrepareSlaveDisconnect", this);
this.connector.setClosing();
return await super.prepareDisconnectRequestHandler(message, request);
}
async disconnect(code, reason) {
try {
await link.messages.prepareDisconnect.send(this);
await libLink.messages.prepareDisconnect.send(this);
} catch (err) {
if (!(err instanceof errors.SessionLost)) {
if (!(err instanceof libErrors.SessionLost)) {
console.error("Unexpected error preparing disconnect");
console.error(err);
}
@@ -592,7 +592,7 @@ class ControlConnection extends BaseConnection {
}
async createSlaveConfigRequestHandler(message) {
let slaveConfig = new config.SlaveConfig();
let slaveConfig = new libConfig.SlaveConfig();
await slaveConfig.init();
slaveConfig.set("slave.master_url", getMasterUrl());
@@ -624,12 +624,12 @@ class ControlConnection extends BaseConnection {
// XXX should probably add a hook for slave reuqests?
async createInstanceRequestHandler(message) {
let instanceConfig = new config.InstanceConfig();
let instanceConfig = new libConfig.InstanceConfig();
await instanceConfig.load(message.data.serialized_config);
let instanceId = instanceConfig.get("instance.id");
if (db.instances.has(instanceId)) {
throw new errors.RequestError(`Instance with ID ${instanceId} already exists`);
throw new libErrors.RequestError(`Instance with ID ${instanceId} already exists`);
}
db.instances.set(instanceId, { config: instanceConfig, status: "unassigned" });
}
@@ -637,7 +637,7 @@ class ControlConnection extends BaseConnection {
async deleteInstanceRequestHandler(message, request) {
let instance = db.instances.get(message.data.instance_id);
if (!instance) {
throw new errors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
}
if (instance.config.get("instance.assigned_slave") !== null) {
@@ -649,7 +649,7 @@ class ControlConnection extends BaseConnection {
async getInstanceConfigRequestHandler(message) {
let instance = db.instances.get(message.data.instance_id);
if (!instance) {
throw new errors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
}
return {
@@ -662,7 +662,7 @@ class ControlConnection extends BaseConnection {
if (slaveId) {
let connection = slaveConnections.get(slaveId);
if (connection) {
await link.messages.assignInstance.send(connection, {
await libLink.messages.assignInstance.send(connection, {
instance_id: instance.config.get("instance.id"),
serialized_config: instance.config.serialize(),
});
@@ -673,16 +673,16 @@ class ControlConnection extends BaseConnection {
async setInstanceConfigFieldRequestHandler(message) {
let instance = db.instances.get(message.data.instance_id);
if (!instance) {
throw new errors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
}
if (message.data.field === "instance.assigned_slave") {
throw new errors.RequestError("instance.assigned_slave must be set through the assign-slave interface");
throw new libErrors.RequestError("instance.assigned_slave must be set through the assign-slave interface");
}
if (message.data.field === "instance.id") {
// XXX is this worth implementing? It's race condition galore.
throw new errors.RequestError("Setting instance.id is not supported");
throw new libErrors.RequestError("Setting instance.id is not supported");
}
instance.config.set(message.data.field, message.data.value);
@@ -692,7 +692,7 @@ class ControlConnection extends BaseConnection {
async setInstanceConfigPropRequestHandler(message) {
let instance = db.instances.get(message.data.instance_id);
if (!instance) {
throw new errors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
}
let { field, prop, value } = message.data;
@@ -703,7 +703,7 @@ class ControlConnection extends BaseConnection {
async assignInstanceCommandRequestHandler(message, request) {
let instance = db.instances.get(message.data.instance_id);
if (!instance) {
throw new errors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${message.data.instance_id} does not exist`);
}
// XXX: Should the instance be stopped if it's running on another slave?
@@ -715,12 +715,12 @@ class ControlConnection extends BaseConnection {
// target slave be connected to the master while doing the
// assignment, but it is IMHO a better user experience if this
// is the case.
throw new errors.RequestError("Target slave is not connected to the master server");
throw new libErrors.RequestError("Target slave is not connected to the master server");
}
instance.config.set("instance.assigned_slave", message.data.slave_id);
return await link.messages.assignInstance.send(connection, {
return await libLink.messages.assignInstance.send(connection, {
instance_id: instance.config.get("instance.id"),
serialized_config: instance.config.serialize(),
});
@@ -732,7 +732,7 @@ class ControlConnection extends BaseConnection {
async listPermissionsRequestHandler(message) {
let list = [];
for (let permission of users.permissions.values()) {
for (let permission of libUsers.permissions.values()) {
list.push({
name: permission.name,
title: permission.title,
@@ -760,7 +760,7 @@ class ControlConnection extends BaseConnection {
// Start at 5 to leave space for future default roles
let id = Math.max(5, lastId+1);
db.roles.set(id, new users.Role({ id, ...message.data }));
db.roles.set(id, new libUsers.Role({ id, ...message.data }));
return { id };
}
@@ -768,7 +768,7 @@ class ControlConnection extends BaseConnection {
let { id, name, description, permissions } = message.data;
let role = db.roles.get(id);
if (!role) {
throw new errors.RequestError(`Role with ID ${id} does not exist`);
throw new libErrors.RequestError(`Role with ID ${id} does not exist`);
}
role.name = name;
@@ -779,7 +779,7 @@ class ControlConnection extends BaseConnection {
async grantDefaultRolePermissionsRequestHandler(message) {
let role = db.roles.get(message.data.id);
if (!role) {
throw new errors.RequestError(`Role with ID ${message.data.id} does not exist`);
throw new libErrors.RequestError(`Role with ID ${message.data.id} does not exist`);
}
role.grantDefaultPermissions();
@@ -789,7 +789,7 @@ class ControlConnection extends BaseConnection {
let id = message.data.id;
let role = db.roles.get(id);
if (!role) {
throw new errors.RequestError(`Role with ID ${id} does not exist`);
throw new libErrors.RequestError(`Role with ID ${id} does not exist`);
}
db.roles.delete(id);
@@ -820,14 +820,14 @@ class ControlConnection extends BaseConnection {
async updateUserRolesRequestHandler(message) {
let user = db.users.get(message.data.name);
if (!user) {
throw new errors.RequestError(`User '${message.data.name}' does not exist`);
throw new libErrors.RequestError(`User '${message.data.name}' does not exist`);
}
let resolvedRoles = new Set();
for (let roleId of message.data.roles) {
let role = db.roles.get(roleId);
if (!role) {
throw new errors.RequestError(`Role with ID ${roleId} does not exist`);
throw new libErrors.RequestError(`Role with ID ${roleId} does not exist`);
}
resolvedRoles.add(role);
@@ -844,12 +844,12 @@ class ControlConnection extends BaseConnection {
this.user.checkPermission("core.user.create");
user = createUser(name);
} else {
throw new errors.RequestError(`User '${name}' does not exist`);
throw new libErrors.RequestError(`User '${name}' does not exist`);
}
}
user.isAdmin = admin;
this.broadcastEventToSlaves({ data: { name, admin }}, link.messages.adminlistUpdate);
this.broadcastEventToSlaves({ data: { name, admin }}, libLink.messages.adminlistUpdate);
}
async setUserBannedRequestHandler(message) {
@@ -860,13 +860,13 @@ class ControlConnection extends BaseConnection {
this.user.checkPermission("core.user.create");
user = createUser(name);
} else {
throw new errors.RequestError(`User '${name}' does not exist`);
throw new libErrors.RequestError(`User '${name}' does not exist`);
}
}
user.isBanned = banned;
user.banReason = reason;
this.broadcastEventToSlaves({ data: { name, banned, reason }}, link.messages.banlistUpdate);
this.broadcastEventToSlaves({ data: { name, banned, reason }}, libLink.messages.banlistUpdate);
}
async setUserWhitelistedRequestHandler(message) {
@@ -877,28 +877,28 @@ class ControlConnection extends BaseConnection {
this.user.checkPermission("core.user.create");
user = createUser(name);
} else {
throw new errors.RequestError(`User '${name}' does not exist`);
throw new libErrors.RequestError(`User '${name}' does not exist`);
}
}
user.isWhitelisted = whitelisted;
this.broadcastEventToSlaves({ data: { name, whitelisted }}, link.messages.whitelistUpdate);
this.broadcastEventToSlaves({ data: { name, whitelisted }}, libLink.messages.whitelistUpdate);
}
async deleteUserRequestHandler(message) {
let user = db.users.get(message.data.name);
if (!user) {
throw new errors.RequestError(`User '${message.data.name}' does not exist`);
throw new libErrors.RequestError(`User '${message.data.name}' does not exist`);
}
if (user.is_admin) {
this.broadcastEventToSlaves({ data: { name, admin: false }}, link.messages.adminlistUpdate);
this.broadcastEventToSlaves({ data: { name, admin: false }}, libLink.messages.adminlistUpdate);
}
if (user.is_whitelisted) {
this.broadcastEventToSlaves({ data: { name, whitelisted: false }}, link.messages.whitelistUpdate);
this.broadcastEventToSlaves({ data: { name, whitelisted: false }}, libLink.messages.whitelistUpdate);
}
if (user.is_banned) {
this.broadcastEventToSlaves({ data: { name, banned: false, reason: "" }}, link.messages.banlistUpdate);
this.broadcastEventToSlaves({ data: { name, banned: false, reason: "" }}, libLink.messages.banlistUpdate);
}
db.users.delete(message.data.name);
}
@@ -906,7 +906,7 @@ class ControlConnection extends BaseConnection {
async debugDumpWsRequestHandler(message) {
this.ws_dumper = data => {
if (this.connector.connected) {
link.messages.debugWsMessage.send(this, data);
libLink.messages.debugWsMessage.send(this, data);
}
};
this.connector._socket.clusterio_ignore_dump = true;
@@ -959,14 +959,14 @@ class SlaveConnection extends BaseConnection {
let prev = instance.status;
instance.status = message.data.status;
console.log(`Clusterio | Instance ${instance.config.get("instance.name")} State: ${instance.status}`);
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
await libPlugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
}
async updateInstancesEventHandler(message) {
// Push updated instance configs
for (let instance of db.instances.values()) {
if (instance.config.get("instance.assigned_slave") === this._id) {
await link.messages.assignInstance.send(this, {
await libLink.messages.assignInstance.send(this, {
instance_id: instance.config.get("instance.id"),
serialized_config: instance.config.serialize(),
});
@@ -975,7 +975,7 @@ class SlaveConnection extends BaseConnection {
// Assign instances the slave has but master does not
for (let instance of message.data.instances) {
let instanceConfig = new config.InstanceConfig();
let instanceConfig = new libConfig.InstanceConfig();
await instanceConfig.load(instance.serialized_config);
let masterInstance = db.instances.get(instanceConfig.get("instance.id"));
@@ -984,7 +984,7 @@ class SlaveConnection extends BaseConnection {
if (masterInstance.status !== instance.status) {
let prev = masterInstance.status;
masterInstance.status = instance.status;
await plugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
await libPlugin.invokeHook(masterPlugins, "onInstanceStatusChanged", instance, prev);
}
continue;
}
@@ -994,7 +994,7 @@ class SlaveConnection extends BaseConnection {
config: instanceConfig,
status: instance.status,
});
await link.messages.assignInstance.send(this, {
await libLink.messages.assignInstance.send(this, {
instance_id: instanceConfig.get("instance.id"),
serialized_config: instanceConfig.serialize(),
});
@@ -1017,14 +1017,14 @@ class SlaveConnection extends BaseConnection {
}
}
link.messages.syncUserLists.send(this, { adminlist, banlist, whitelist });
libLink.messages.syncUserLists.send(this, { adminlist, banlist, whitelist });
}
async instanceOutputEventHandler(message) {
let { instance_id, output } = message.data;
for (let controlConnection of controlConnections) {
if (controlConnection.instanceOutputSubscriptions.has(instance_id)) {
link.messages.instanceOutput.send(controlConnection, message.data);
libLink.messages.instanceOutput.send(controlConnection, message.data);
}
}
}
@@ -1043,7 +1043,7 @@ class SlaveConnection extends BaseConnection {
}
let instance = db.instances.get(instance_id);
await plugin.invokeHook(masterPlugins, "onPlayerEvent", instance, message.data);
await libPlugin.invokeHook(masterPlugins, "onPlayerEvent", instance, message.data);
}
}
@@ -1070,7 +1070,7 @@ function isInteger(value) {
*
* @extends module:lib/link.WebSocketBaseConnector
*/
class WebSocketServerConnector extends link.WebSocketBaseConnector {
class WebSocketServerConnector extends libLink.WebSocketBaseConnector {
constructor(socket, sessionId) {
super();
@@ -1341,7 +1341,7 @@ async function handleHandshake(message, socket, req, attachHandler) {
return;
}
if (!schema.clientHandshake(message)) {
if (!libSchema.clientHandshake(message)) {
console.log(`SOCKET | closing ${req.socket.remoteAddress} after receiving invalid handshake:`, message);
wsRejectedConnectionsCounter.inc();
socket.close(1002, "Bad handshake");
@@ -1460,7 +1460,7 @@ async function loadPlugins(pluginInfos) {
pluginList[pluginInfo.name] = pluginInfo.version;
let pluginLoadStarted = Date.now();
let MasterPlugin = plugin.BaseMasterPlugin;
let MasterPlugin = libPlugin.BaseMasterPlugin;
try {
if (pluginInfo.masterEntrypoint) {
({ MasterPlugin } = require(path.posix.join(pluginInfo.requirePath, pluginInfo.masterEntrypoint)));
@@ -1473,7 +1473,7 @@ async function loadPlugins(pluginInfos) {
plugins.set(pluginInfo.name, masterPlugin);
} catch (err) {
throw new errors.PluginError(pluginInfo.name, err);
throw new libErrors.PluginError(pluginInfo.name, err);
}
console.log(`Clusterio | Loaded plugin ${pluginInfo.name} in ${Date.now() - pluginLoadStarted}ms`);
@@ -1503,7 +1503,7 @@ function listen(server, ...args) {
});
function wrapError(err) {
reject(new errors.StartupError(
reject(new libErrors.StartupError(
`Server listening failed: ${err.message}`
));
}
@@ -1561,8 +1561,8 @@ async function startServer() {
default: "plugin-list.json",
type: "string",
})
.command("plugin", "Manage available plugins", sharedCommands.pluginCommand)
.command("config", "Manage Master config", config.configCommand)
.command("plugin", "Manage available plugins", libSharedCommands.pluginCommand)
.command("config", "Manage Master config", libConfig.configCommand)
.command("bootstrap", "Bootstrap access to cluster", yargs => {
yargs
.command("create-admin <name>", "Create a cluster admin")
@@ -1595,18 +1595,18 @@ async function startServer() {
// If the command is plugin management we don't try to load plugins
let command = args._[0];
if (command === "plugin") {
await sharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
await libSharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
return;
}
console.log("Loading Plugin info");
pluginInfos = await plugin.loadPluginInfos(pluginList);
config.registerPluginConfigGroups(pluginInfos);
config.finalizeConfigs();
pluginInfos = await libPlugin.loadPluginInfos(pluginList);
libConfig.registerPluginConfigGroups(pluginInfos);
libConfig.finalizeConfigs();
masterConfigPath = args.config;
console.log(`Loading config from ${masterConfigPath}`);
masterConfig = new config.MasterConfig();
masterConfig = new libConfig.MasterConfig();
try {
await masterConfig.load(JSON.parse(await fs.readFile(masterConfigPath)));
@@ -1629,7 +1629,7 @@ async function startServer() {
}
if (command === "config") {
await config.handleConfigCommand(args, masterConfig, masterConfigPath);
await libConfig.handleConfigCommand(args, masterConfig, masterConfigPath);
return;
} else if (command === "bootstrap") {
@@ -1647,7 +1647,7 @@ async function startServer() {
admin = createUser(args.name);
}
let adminRole = users.ensureDefaultAdminRole(db.roles);
let adminRole = libUsers.ensureDefaultAdminRole(db.roles);
admin.roles.add(adminRole);
admin.isAdmin = true;
await saveUsers(masterConfig.get("master.database_directory"), "users.json");
@@ -1659,7 +1659,7 @@ async function startServer() {
process.exitCode = 1;
return;
}
let controlConfig = new config.ControlConfig();
let controlConfig = new libConfig.ControlConfig();
await controlConfig.init();
controlConfig.set("control.master_url", getMasterUrl());
@@ -1728,7 +1728,7 @@ async function startServer() {
let tls_key = masterConfig.get("master.tls_private_key");
// Create a self signed certificate if the certificate files doesn't exist
if (httpsPort && !await fs.exists(tls_cert) && !await fs.exists(tls_key)) {
await generateSSLcert({
await generateSslCert({
bits: masterConfig.get("master.tls_bits"),
sslCertPath: tls_cert,
sslPrivKeyPath: tls_key,
@@ -1763,7 +1763,7 @@ async function startServer() {
privateKey = await fs.readFile(tls_key);
} catch (err) {
throw new errors.StartupError(
throw new libErrors.StartupError(
`Error loading ssl certificate: ${err.message}`
);
}
@@ -1799,13 +1799,13 @@ I version of clusterio. Expect things to break. I
`
);
startServer().catch(err => {
if (err instanceof errors.StartupError) {
if (err instanceof libErrors.StartupError) {
console.error(`
+----------------------------------+
| Unable to to start master server |
+----------------------------------+`
);
} else if (err instanceof errors.PluginError) {
} else if (err instanceof libErrors.PluginError) {
console.error(`
Error: ${err.pluginName} plugin threw an unexpected error
during startup, please report it to the plugin author.
+9 -9
View File
@@ -1,6 +1,6 @@
const link = require("@clusterio/lib/link");
const plugin = require("@clusterio/lib/plugin");
const errors = require("@clusterio/lib/errors");
const libLink = require("@clusterio/lib/link");
const libPlugin = require("@clusterio/lib/plugin");
const libErrors = require("@clusterio/lib/errors");
/**
* Format a parsed Factorio output message
@@ -35,7 +35,7 @@ function formatOutput(output) {
* Connector for control connection to master server
* @private
*/
export class ControlConnector extends link.WebSocketClientConnector {
export class ControlConnector extends libLink.WebSocketClientConnector {
constructor(url, reconnectDelay, token) {
super(url, reconnectDelay);
this._token = token;
@@ -57,10 +57,10 @@ export class ControlConnector extends link.WebSocketClientConnector {
* Connects to the master server over WebSocket and sends commands to it.
* @static
*/
export class Control extends link.Link {
export class Control extends libLink.Link {
constructor(connector, controlPlugins) {
super("control", "master", connector);
link.attachAllMessages(this);
libLink.attachAllMessages(this);
/**
* Mapping of plugin names to their instance for loaded plugins.
@@ -68,7 +68,7 @@ export class Control extends link.Link {
*/
this.plugins = controlPlugins;
for (let controlPlugin of controlPlugins.values()) {
plugin.attachPluginMessages(this, controlPlugin.info, controlPlugin);
libPlugin.attachPluginMessages(this, controlPlugin.info, controlPlugin);
}
}
@@ -88,9 +88,9 @@ export class Control extends link.Link {
this.connector.setTimeout(30);
try {
await link.messages.prepareDisconnect.send(this);
await libLink.messages.prepareDisconnect.send(this);
} catch (err) {
if (!(err instanceof errors.SessionLost)) {
if (!(err instanceof libErrors.SessionLost)) {
throw err;
}
}
+79 -79
View File
@@ -24,36 +24,36 @@ const util = require("util");
const version = require("./package").version;
// internal libraries
const fileOps = require("@clusterio/lib/fileOps");
const factorio = require("@clusterio/lib/factorio");
const link = require("@clusterio/lib/link");
const plugin = require("@clusterio/lib/plugin");
const errors = require("@clusterio/lib/errors");
const prometheus = require("@clusterio/lib/prometheus");
const luaTools = require("@clusterio/lib/luaTools");
const config = require("@clusterio/lib/config");
const sharedCommands = require("@clusterio/lib/shared_commands");
const libFileOps = require("@clusterio/lib/file_ops");
const libFactorio = require("@clusterio/lib/factorio");
const libLink = require("@clusterio/lib/link");
const libPlugin = require("@clusterio/lib/plugin");
const libErrors = require("@clusterio/lib/errors");
const libPrometheus = require("@clusterio/lib/prometheus");
const libLuaTools = require("@clusterio/lib/lua_tools");
const libConfig = require("@clusterio/lib/config");
const libSharedCommands = require("@clusterio/lib/shared_commands");
const instanceRconCommandsCounter = new prometheus.Counter(
const instanceRconCommandsCounter = new libPrometheus.Counter(
"clusterio_instance_rcon_commands_total",
"How many commands have been sent to the instance",
{ labels: ["instance_id"] }
);
const instanceFactorioCpuTime = new prometheus.Gauge(
const instanceFactorioCpuTime = new libPrometheus.Gauge(
"clusterio_instance_factorio_cpu_time_total",
"Factorio CPU time spent in seconds.",
{ labels: ["instance_id"] }
);
const instanceFactorioMemoryUsage = new prometheus.Gauge(
const instanceFactorioMemoryUsage = new libPrometheus.Gauge(
"clusterio_instance_factorio_resident_memory_bytes",
"Factorio resident memory size in bytes.",
{ labels: ["instance_id"] }
);
const instanceFactorioAutosaveSize = new prometheus.Gauge(
const instanceFactorioAutosaveSize = new libPrometheus.Gauge(
"clusterio_instance_factorio_autosave_bytes",
"Size of Factorio server autosave in bytes.",
{ labels: ["instance_id"] }
@@ -105,10 +105,10 @@ const serverSettingsActions = {
/**
* Keeps track of the runtime parameters of an instance
*/
class Instance extends link.Link{
class Instance extends libLink.Link{
constructor(slave, connector, dir, factorioDir, instanceConfig) {
super("instance", "slave", connector);
link.attachAllMessages(this);
libLink.attachAllMessages(this);
this._slave = slave;
this._dir = dir;
@@ -116,7 +116,7 @@ class Instance extends link.Link{
this.config = instanceConfig;
this._configFieldChanged = (group, field, prev) => {
let hook = () => plugin.invokeHook(this.plugins, "onInstanceConfigFieldChanged", group, field, prev);
let hook = () => libPlugin.invokeHook(this.plugins, "onInstanceConfigFieldChanged", group, field, prev);
if (group.name === "factorio" && field === "settings") {
this.updateFactorioSettings(group.get(field), prev).finally(hook);
@@ -137,7 +137,7 @@ class Instance extends link.Link{
};
this._running = false;
this.server = new factorio.FactorioServer(
this.server = new libFactorio.FactorioServer(
factorioDir, this._dir, serverOptions
);
@@ -148,9 +148,9 @@ class Instance extends link.Link{
};
this.server.on("output", (output) => {
link.messages.instanceOutput.send(this, { instance_id: this.config.get("instance.id"), output });
libLink.messages.instanceOutput.send(this, { instance_id: this.config.get("instance.id"), output });
plugin.invokeHook(this.plugins, "onOutput", output);
libPlugin.invokeHook(this.plugins, "onOutput", output);
});
this.server.on("error", err => {
@@ -164,11 +164,11 @@ class Instance extends link.Link{
});
this.server.on("ipc-player_event", event => {
link.messages.playerEvent.send(this, {
libLink.messages.playerEvent.send(this, {
instance_id: this.config.get("instance.id"),
...event,
});
plugin.invokeHook(this.plugins, "onPlayerEvent", event);
libPlugin.invokeHook(this.plugins, "onPlayerEvent", event);
});
}
@@ -178,7 +178,7 @@ class Instance extends link.Link{
}
notifyStatus(status) {
link.messages.instanceStatusChanged.send(this, {
libLink.messages.instanceStatusChanged.send(this, {
instance_id: this.config.get("instance.id"), status,
});
}
@@ -190,9 +190,9 @@ class Instance extends link.Link{
this.config.off("fieldChanged", this._configFieldChanged);
// Clear metrics this instance is exporting
for (let collector of prometheus.defaultRegistry.collectors) {
for (let collector of libPrometheus.defaultRegistry.collectors) {
if (
collector instanceof prometheus.ValueCollector
collector instanceof libPrometheus.ValueCollector
&& collector.metric.labels.includes("instance_id")
) {
collector.removeAll({ instance_id: String(this.config.get("instance.id")) });
@@ -211,7 +211,7 @@ class Instance extends link.Link{
let instancePlugin = new InstancePlugin(pluginInfo, this, slave);
this.plugins.set(pluginInfo.name, instancePlugin);
await instancePlugin.init();
plugin.attachPluginMessages(this, pluginInfo, instancePlugin);
libPlugin.attachPluginMessages(this, pluginInfo, instancePlugin);
console.log(`Clusterio | Loaded plugin ${pluginInfo.name} in ${Date.now() - pluginLoadStarted}ms`);
}
@@ -241,7 +241,7 @@ class Instance extends link.Link{
for (let [name, plugin] of this.plugins) {
plugins[name] = plugin.info.version;
}
link.messages.instanceInitialized.send(this, { instance_id: this.config.get("instance.id"), plugins });
libLink.messages.instanceInitialized.send(this, { instance_id: this.config.get("instance.id"), plugins });
}
/**
@@ -362,7 +362,7 @@ class Instance extends link.Link{
async prepareSave(saveName) {
// Use latest save if no save was specified
if (saveName === null) {
saveName = await fileOps.getNewestFile(
saveName = await libFileOps.getNewestFile(
this.path("saves"), (name) => !name.endsWith(".tmp.zip")
);
}
@@ -440,7 +440,7 @@ class Instance extends link.Link{
}
}
await factorio.patch(this.path("saves", saveName), [...modules.values()]);
await libFactorio.patch(this.path("saves", saveName), [...modules.values()]);
return saveName;
}
@@ -464,7 +464,7 @@ class Instance extends link.Link{
await this.updateInstanceData();
}
await plugin.invokeHook(this.plugins, "onStart");
await libPlugin.invokeHook(this.plugins, "onStart");
this._running = true;
this.notifyStatus("running");
@@ -486,7 +486,7 @@ class Instance extends link.Link{
this.server.on("exit", () => this.notifyExit());
await this.server.startScenario(scenario);
await plugin.invokeHook(this.plugins, "onStart");
await libPlugin.invokeHook(this.plugins, "onStart");
this._running = true;
this.notifyStatus("running");
@@ -496,7 +496,7 @@ class Instance extends link.Link{
* Update instance information on the Factorio side
*/
async updateInstanceData() {
let name = luaTools.escapeString(this.config.get("instance.name"));
let name = libLuaTools.escapeString(this.config.get("instance.name"));
let id = this.config.get("instance.id");
await this.server.sendRcon(`/sc clusterio_private.update_instance(${id}, "${name}")`, true);
}
@@ -574,26 +574,26 @@ class Instance extends link.Link{
// XXX this needs more thought to it
if (this.server._state === "running") {
await plugin.invokeHook(this.plugins, "onStop");
await libPlugin.invokeHook(this.plugins, "onStop");
await this.server.stop();
}
}
async masterConnectionEventEventHandler(message) {
await plugin.invokeHook(this.plugins, "onMasterConnectionEvent", message.data.event);
await libPlugin.invokeHook(this.plugins, "onMasterConnectionEvent", message.data.event);
}
async prepareMasterDisconnectRequestHandler() {
await plugin.invokeHook(this.plugins, "onPrepareMasterDisconnect");
await libPlugin.invokeHook(this.plugins, "onPrepareMasterDisconnect");
}
async getMetricsRequestHandler() {
let results = [];
if (this._running) {
let pluginResults = await plugin.invokeHook(this.plugins, "onMetrics");
let pluginResults = await libPlugin.invokeHook(this.plugins, "onMetrics");
for (let metricIterator of pluginResults) {
for await (let metric of metricIterator) {
results.push(prometheus.serializeResult(metric));
results.push(libPrometheus.serializeResult(metric));
}
}
}
@@ -629,7 +629,7 @@ class Instance extends link.Link{
async loadScenarioRequestHandler(message) {
if (this.config.get("factorio.enable_save_patching")) {
this.notifyExit();
throw new errors.RequestError("Load scenario cannot be used with save patching enabled");
throw new libErrors.RequestError("Load scenario cannot be used with save patching enabled");
}
try {
@@ -674,7 +674,7 @@ class Instance extends link.Link{
console.log("Exporting data .....");
await symlinkMods(this, "sharedMods", console);
let zip = await factorio.exportData(this.server);
let zip = await libFactorio.exportData(this.server);
let content = await zip.generateAsync({ type: "nodebuffer" });
let url = new URL(this._slave.config.get("slave.master_url"));
@@ -745,7 +745,7 @@ class Instance extends link.Link{
async function discoverInstances(instanceInfos, instancesDir, logger) {
for (let entry of await fs.readdir(instancesDir, { withFileTypes: true })) {
if (entry.isDirectory()) {
let instanceConfig = new config.InstanceConfig();
let instanceConfig = new libConfig.InstanceConfig();
let configPath = path.join(instancesDir, entry.name, "instance.json");
try {
@@ -775,17 +775,17 @@ async function discoverInstances(instanceInfos, instancesDir, logger) {
}
}
class InstanceConnection extends link.Link {
class InstanceConnection extends libLink.Link {
constructor(connector, slave, instanceId) {
super("slave", "instance", connector);
this.slave = slave;
this.instanceId = instanceId;
this.plugins = new Map();
this.status = "stopped";
link.attachAllMessages(this);
libLink.attachAllMessages(this);
for (let pluginInfo of slave.pluginInfos) {
plugin.attachPluginMessages(this, pluginInfo, null);
libPlugin.attachPluginMessages(this, pluginInfo, null);
}
}
@@ -833,7 +833,7 @@ class InstanceConnection extends link.Link {
}
}
class SlaveConnector extends link.WebSocketClientConnector {
class SlaveConnector extends libLink.WebSocketClientConnector {
constructor(slaveConfig, pluginInfos) {
super(slaveConfig.get("slave.master_url"), slaveConfig.get("slave.reconnect_delay"));
this.slaveConfig = slaveConfig;
@@ -863,16 +863,16 @@ class SlaveConnector extends link.WebSocketClientConnector {
*
* Connects to the master server over the WebSocket and manages intsances.
*/
class Slave extends link.Link {
class Slave extends libLink.Link {
// I don't like God classes, but the alternative of putting all this state
// into global variables is not much better.
constructor(connector, slaveConfig, pluginInfos) {
super("slave", "master", connector);
link.attachAllMessages(this);
libLink.attachAllMessages(this);
this.pluginInfos = pluginInfos;
for (let pluginInfo of pluginInfos) {
plugin.attachPluginMessages(this, pluginInfo, null);
libPlugin.attachPluginMessages(this, pluginInfo, null);
}
this.config = slaveConfig;
@@ -941,7 +941,7 @@ class Slave extends link.Link {
for (let event of ["connect", "drop", "close"]) {
this.connector.on(event, () => {
for (let instanceConnection of this.instanceConnections.values()) {
link.messages.masterConnectionEvent.send(instanceConnection, { event });
libLink.messages.masterConnectionEvent.send(instanceConnection, { event });
}
});
}
@@ -966,16 +966,16 @@ class Slave extends link.Link {
async forwardRequestToInstance(message, request) {
let instanceId = message.data.instance_id;
if (!this.instanceInfos.has(instanceId)) {
throw new errors.RequestError(`Instance with ID ${instanceId} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${instanceId} does not exist`);
}
let instanceConnection = this.instanceConnections.get(instanceId);
if (!instanceConnection) {
throw new errors.RequestError(`Instance ID ${instanceId} is not running`);
throw new libErrors.RequestError(`Instance ID ${instanceId} is not running`);
}
if (request.plugin && !instanceConnection.plugins.has(request.plugin)) {
throw new errors.RequestError(`Instance ID ${instanceId} does not have ${request.plugin} plugin loaded`);
throw new libErrors.RequestError(`Instance ID ${instanceId} does not have ${request.plugin} plugin loaded`);
}
return await request.send(instanceConnection, message.data);
@@ -1022,8 +1022,8 @@ class Slave extends link.Link {
}
};
updateList(this.adminlist, message.data.adminlist, "admin", link.messages.adminlistUpdate);
updateList(this.whitelist, message.data.whitelist, "whitelisted", link.messages.whitelistUpdate);
updateList(this.adminlist, message.data.adminlist, "admin", libLink.messages.adminlistUpdate);
updateList(this.whitelist, message.data.whitelist, "whitelisted", libLink.messages.whitelistUpdate);
let updatedBanlist = new Map(message.data.banlist);
let addedOrChanged = new Map(updatedBanlist);
@@ -1038,14 +1038,14 @@ class Slave extends link.Link {
for (let [name, reason] of addedOrChanged) {
this.banlist.set(name, reason);
this.broadcastEventToInstance(
{ data: { name, banned: true, reason }}, link.messages.banlistUpdate
{ data: { name, banned: true, reason }}, libLink.messages.banlistUpdate
);
}
for (let name of removed) {
this.banlist.delete(name);
this.broadcastEventToInstance(
{ data: { name, banned: false, reason: "" }}, link.messages.banlistUpdate
{ data: { name, banned: false, reason: "" }}, libLink.messages.banlistUpdate
);
}
}
@@ -1086,7 +1086,7 @@ class Slave extends link.Link {
// TODO: Notify of update if instance is running
} else {
let instanceConfig = new config.InstanceConfig();
let instanceConfig = new libConfig.InstanceConfig();
await instanceConfig.load(serialized_config);
// XXX: race condition on multiple simultanious calls
@@ -1113,7 +1113,7 @@ class Slave extends link.Link {
);
// Notify master the instance is no longer usassigned
link.messages.instanceStatusChanged.send(this, { instance_id, status: "stopped" });
libLink.messages.instanceStatusChanged.send(this, { instance_id, status: "stopped" });
}
/**
@@ -1125,14 +1125,14 @@ class Slave extends link.Link {
async _connectInstance(instanceId) {
let instanceInfo = this.instanceInfos.get(instanceId);
if (!instanceInfo) {
throw new errors.RequestError(`Instance with ID ${instanceId} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${instanceId} does not exist`);
}
if (this.instanceConnections.has(instanceId)) {
throw new errors.RequestError(`Instance with ID ${instanceId} is running`);
throw new libErrors.RequestError(`Instance with ID ${instanceId} is running`);
}
let [connectionClient, connectionServer] = link.VirtualConnector.makePair();
let [connectionClient, connectionServer] = libLink.VirtualConnector.makePair();
let instanceConnection = new InstanceConnection(connectionServer, this, instanceId);
let instance = new Instance(
this, connectionClient, instanceInfo.path, this.config.get("slave.factorio_directory"), instanceInfo.config
@@ -1147,7 +1147,7 @@ class Slave extends link.Link {
async getMetricsRequestHandler() {
let requests = [];
for (let instanceConnection of this.instanceConnections.values()) {
requests.push(link.messages.getMetrics.send(instanceConnection));
requests.push(libLink.messages.getMetrics.send(instanceConnection));
}
let results = [];
@@ -1155,15 +1155,15 @@ class Slave extends link.Link {
results.push(...response.results);
}
for await (let result of prometheus.defaultRegistry.collect()) {
for await (let result of libPrometheus.defaultRegistry.collect()) {
if (result.metric.name.startsWith("process_")) {
results.push(prometheus.serializeResult(result, {
results.push(libPrometheus.serializeResult(result, {
addLabels: { "slave_id": String(this.config.get("slave.id")) },
metricName: result.metric.name.replace("process_", "clusterio_slave_"),
}));
} else {
results.push(prometheus.serializeResult(result));
results.push(libPrometheus.serializeResult(result));
}
}
@@ -1196,18 +1196,18 @@ class Slave extends link.Link {
async stopInstance(instanceId) {
let instanceConnection = this.instanceConnections.get(instanceId);
await link.messages.stopInstance.send(instanceConnection, { instance_id: instanceId });
await libLink.messages.stopInstance.send(instanceConnection, { instance_id: instanceId });
}
async deleteInstanceRequestHandler(message) {
let instanceId = message.data.instance_id;
if (this.instanceConnections.has(instanceId)) {
throw new errors.RequestError(`Instance with ID ${instanceId} is running`);
throw new libErrors.RequestError(`Instance with ID ${instanceId} is running`);
}
let instanceInfo = this.instanceInfos.get(instanceId);
if (!instanceInfo) {
throw new errors.RequestError(`Instance with ID ${instanceId} does not exist`);
throw new libErrors.RequestError(`Instance with ID ${instanceId} does not exist`);
}
await fs.remove(instanceInfo.path);
@@ -1230,13 +1230,13 @@ class Slave extends link.Link {
status: instanceConnection ? instanceConnection.status : "stopped",
});
}
link.messages.updateInstances.send(this, { instances: list });
libLink.messages.updateInstances.send(this, { instances: list });
}
async prepareDisconnectRequestHandler(message, request) {
this._disconnecting = true;
for (let instanceConnection of this.instanceConnections.values()) {
await link.messages.prepareMasterDisconnect.send(instanceConnection);
await libLink.messages.prepareMasterDisconnect.send(instanceConnection);
}
this.connector.setClosing();
return await super.prepareDisconnectRequestHandler(message, request);
@@ -1250,9 +1250,9 @@ class Slave extends link.Link {
this.connector.setTimeout(30);
try {
await link.messages.prepareDisconnect.send(this);
await libLink.messages.prepareDisconnect.send(this);
} catch (err) {
if (!(err instanceof errors.SessionLost)) {
if (!(err instanceof libErrors.SessionLost)) {
console.error("Unexpected error preparing disconnect");
console.error(err);
}
@@ -1391,8 +1391,8 @@ async function startSlave() {
default: "plugin-list.json",
type: "string",
})
.command("plugin", "Manage available plugins", sharedCommands.pluginCommand)
.command("config", "Manage Slave config", config.configCommand)
.command("plugin", "Manage available plugins", libSharedCommands.pluginCommand)
.command("config", "Manage Slave config", libConfig.configCommand)
.command("run", "Run slave")
.demandCommand(1, "You need to specify a command to run")
.strict()
@@ -1412,17 +1412,17 @@ async function startSlave() {
// If the command is plugin management we don't try to load plugins
let command = args._[0];
if (command === "plugin") {
await sharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
await libSharedCommands.handlePluginCommand(args, pluginList, args.pluginList);
return;
}
console.log("Loading Plugin info");
let pluginInfos = await plugin.loadPluginInfos(pluginList);
config.registerPluginConfigGroups(pluginInfos);
config.finalizeConfigs();
let pluginInfos = await libPlugin.loadPluginInfos(pluginList);
libConfig.registerPluginConfigGroups(pluginInfos);
libConfig.finalizeConfigs();
console.log(`Loading config from ${args.config}`);
let slaveConfig = new config.SlaveConfig();
let slaveConfig = new libConfig.SlaveConfig();
try {
await slaveConfig.load(JSON.parse(await fs.readFile(args.config)));
@@ -1437,7 +1437,7 @@ async function startSlave() {
}
if (command === "config") {
await config.handleConfigCommand(args, slaveConfig, args.config);
await libConfig.handleConfigCommand(args, slaveConfig, args.config);
return;
}
@@ -1518,7 +1518,7 @@ I version of clusterio. Expect things to break. I
`
);
startSlave().catch(err => {
if (err instanceof errors.AuthenticationFailed) {
if (err instanceof libErrors.AuthenticationFailed) {
console.error(err.message);
} else {