Rename Ctl's usage of "control" to "ctl" (#1039)

Ctl ended up calling its main class for "Control" for historical
reasons, along with its config file and plugin entrypoint.

The plugin entrypoint was renamed to ctl in 808eda0513.  This
finishes that renaming by also renaming the main class, default config
file, config-control command, and main entrypoint.

The config-control command is renamed to config to be consistent with
the host and controller's config commands.

The term "control" is still kept in the config and message locations as
a common specifier for both ctl and web_ui.
This commit is contained in:
Hornwitser authored and GitHub committed 2026-09-14 20:18:41 +02:00
1 parent 1d1d9bb1c4
commit 5df5af7ca8
35 files changed
+383 -383

No files matched your search

+1 -1
View File
@@ -74,7 +74,7 @@ async function removeTestArtifacts() {
async function removeExecutionArtifacts() { async function removeExecutionArtifacts() {
const artifacts = [ const artifacts = [
"database", "instances", "logs", "mods", "database", "instances", "logs", "mods",
"config-control.json", "config-controller.json", "config-host.json", "config-ctl.json", "config-controller.json", "config-host.json",
"FactorioAdminToken.txt", "plugin-list.json", "FactorioAdminToken.txt", "plugin-list.json",
]; ];
+4 -4
View File
@@ -706,16 +706,16 @@ Loading a plugin that requires save patching or script commands is rejected whil
Defaults to true. Defaults to true.
## Control Configuration ## Ctl Configuration
### control.controller_url ### ctl.controller_url
URL to connect to the controller to. URL to connect to the controller to.
Defaults to null meaning complain about it not being set and exit. Defaults to null meaning complain about it not being set and exit.
### control.controller_token ### ctl.controller_token
Access token used for authenticating with the controller. Access token used for authenticating with the controller.
You can generate an access token with `clusteriocontroller bootstrap generate-user-token <username>`, or use the `clusteriocontroller bootstrap create-ctl-config <username>` to create a new ctl config with the correct url and token in it. You can generate an access token with `clusteriocontroller bootstrap generate-user-token <username>`, or use the `clusteriocontroller bootstrap create-ctl-config <username>` to create a new ctl config with the correct url and token in it.
@@ -723,7 +723,7 @@ You can generate an access token with `clusteriocontroller bootstrap generate-us
Defaults to null meaning complain about it not being set and exit. Defaults to null meaning complain about it not being set and exit.
### control.max_reconnect_delay ### ctl.max_reconnect_delay
Max duration in seconds to wait before attempting to reconnect with the controller after the connection is dropped. Max duration in seconds to wait before attempting to reconnect with the controller after the connection is dropped.
The actual delay on each reconnect will be a random number between 0 and this configured value to avoid all clients trying to reconnect at the same time. The actual delay on each reconnect will be a random number between 0 and this configured value to avoid all clients trying to reconnect at the same time.
+1 -1
View File
@@ -77,7 +77,7 @@ The documentation uses the binaries provided by the packages, but for the develo
By default node does not enable source maps, to get stack traces pointing to the `.ts` files you will need to pass `--enable-source-maps` to `node` or set the environment variable `NODE_OPTIONS=--enable-source-maps`. By default node does not enable source maps, to get stack traces pointing to the `.ts` files you will need to pass `--enable-source-maps` to `node` or set the environment variable `NODE_OPTIONS=--enable-source-maps`.
Note that to use `clusterioctl` you will have to create a control config first: Note that to use `clusterioctl` you will have to create a ctl config first:
node packages/controller bootstrap create-ctl-config [admin-user] node packages/controller bootstrap create-ctl-config [admin-user]
+1 -1
View File
@@ -14,7 +14,7 @@ All messages sent and received are validated with JSON schemas to catch potentia
Messages are sent by calling the `.send()` method of the message instance and passing a `Link` instance to send it over and the data to send. Messages are sent by calling the `.send()` method of the message instance and passing a `Link` instance to send it over and the data to send.
For the controller there's a `Link` instance for each host and control connection stored in the `WsServer` class. For the controller there's a `Link` instance for each host and control connection stored in the `WsServer` class.
For hosts the `Host` instance is a link to the controller, and each `Instance` instance is an in-memory link to the `Host` instance and has a corresponding `InstanceConnection` link stored on the `Host` instance. For hosts the `Host` instance is a link to the controller, and each `Instance` instance is an in-memory link to the `Host` instance and has a corresponding `InstanceConnection` link stored on the `Host` instance.
For ctl and web_ui there's a `Control` instance that acts as the link to the controller. For ctl there's a `Ctl` instance and web_ui there's a `Control` instance that acts as the link to the controller.
Messages received invokes message handlers that were registered when the link was brought up. Messages received invokes message handlers that were registered when the link was brought up.
These handlers are named after the name of the property the message is stored under with `EventHandler` appended for events and `RequestHandler` appended for requests. These handlers are named after the name of the property the message is stored under with `EventHandler` appended for events and `RequestHandler` appended for requests.
+5 -5
View File
@@ -28,7 +28,7 @@ The basic file structure of a plugin is the following.
+- package.json +- package.json
+- controller.js +- controller.js
+- instance.js +- instance.js
+- control.js +- ctl.js
+- test/ +- test/
| +- plugin.js | +- plugin.js
+- module/ +- module/
@@ -643,7 +643,7 @@ controller.hooks.metrics.attach(plugin.name, async () => fooRegistry.collect());
## Adding Custom Commands to clusterioctl ## Adding Custom Commands to clusterioctl
The control entrypoint for plugins allows you to extend clustectl with your own commands. The ctl entrypoint for plugins allows you to extend clustectl with your own commands.
The creation of custom commands typically starts with defining a command tree for the plugin: The creation of custom commands typically starts with defining a command tree for the plugin:
```js ```js
@@ -664,8 +664,8 @@ fooFrobberCommands.add(new Command({
describe: "type of frobnication", type: "string" describe: "type of frobnication", type: "string"
}); });
}], }],
handler: async function(args, control) { handler: async function(args, ctl) {
await info.messages.frobnicate.send(control, { await info.messages.frobnicate.send(ctl, {
instance_name: "Console", instance_name: "Console",
content: args.message, content: args.message,
}); });
@@ -674,7 +674,7 @@ fooFrobberCommands.add(new Command({
``` ```
For a command the `definition` is the arguments to pass to [yargs.command](http://yargs.js.org/docs/#api-reference-commandcmd-desc-builder-handler) (see also [yargs.positional](http://yargs.js.org/docs/#api-reference-positionalkey-opt) and [yargs.options](http://yargs.js.org/docs/#api-reference-optionskey-opt) for setting up positional and optional arguments to commands). For a command the `definition` is the arguments to pass to [yargs.command](http://yargs.js.org/docs/#api-reference-commandcmd-desc-builder-handler) (see also [yargs.positional](http://yargs.js.org/docs/#api-reference-positionalkey-opt) and [yargs.options](http://yargs.js.org/docs/#api-reference-optionskey-opt) for setting up positional and optional arguments to commands).
The `handler` is an async function that's invoked when the command is executed and it's passed the parsed command line arguments and a reference to the `Control` class of clusterioctl. The `handler` is an async function that's invoked when the command is executed and it's passed the parsed command line arguments and a reference to the `Ctl` class of clusterioctl.
Note that messages sent from clusterioctl needs to have `"control-controller"` as a part of the links array for it to be accepted by the controller, see [Defining Link Messages](#defining-link-messages) for how to define the messages that can be sent to the controller. Note that messages sent from clusterioctl needs to have `"control-controller"` as a part of the links array for it to be accepted by the controller, see [Defining Link Messages](#defining-link-messages) for how to define the messages that can be sent to the controller.
To have the command tree become part of clusterioctl it needs to be added to the rootCommand tree in the `addCommands` hook of the ctl entrypoint: To have the command tree become part of clusterioctl it needs to be added to the rootCommand tree in the `addCommands` hook of the ctl entrypoint:
+6 -6
View File
@@ -201,15 +201,15 @@ async function handleBootstrapCommand(
process.exitCode = 1; process.exitCode = 1;
return; return;
} }
let controlConfig = new lib.ControlConfig("control"); let ctlConfig = new lib.CtlConfig("control");
controlConfig.set("control.controller_url", Controller.calculateControllerUrl(controllerConfig)); ctlConfig.set("ctl.controller_url", Controller.calculateControllerUrl(controllerConfig));
controlConfig.set( ctlConfig.set(
"control.controller_token", "ctl.controller_token",
userManager.signUserToken(admin), userManager.signUserToken(admin),
); );
let content = JSON.stringify(controlConfig, null, "\t"); let content = JSON.stringify(ctlConfig, null, "\t");
if (args.output === "-") { if (args.output === "-") {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(content); console.log(content);
@@ -322,7 +322,7 @@ async function initialize(): Promise<InitializeParameters> {
.command("create-ctl-config <name>", "Create clusterioctl config for the given user", yargs => { .command("create-ctl-config <name>", "Create clusterioctl config for the given user", yargs => {
yargs.option("output", { yargs.option("output", {
describe: "Path to output config (- for stdout)", type: "string", describe: "Path to output config (- for stdout)", type: "string",
nargs: 1, default: "config-control.json", nargs: 1, default: "config-ctl.json",
}); });
}) })
.demandCommand(1, "You need to specify a command to run"); .demandCommand(1, "You need to specify a command to run");
+2 -2
View File
@@ -887,8 +887,8 @@ async function main() {
} }
if (answers.mode === "ctl") { if (answers.mode === "ctl") {
await execCtl(["control-config", "set", "control.controller_url", answers.controllerUrl]); await execCtl(["config", "set", "ctl.controller_url", answers.controllerUrl]);
await execCtl(["control-config", "set", "control.controller_token", answers.controllerToken]); await execCtl(["config", "set", "ctl.controller_token", answers.controllerToken]);
} }
/* eslint-disable no-console */ /* eslint-disable no-console */
+2 -2
View File
@@ -11,8 +11,8 @@ pluginCommands.add(new Command({
definition: ["my-command <foo>", "My command description that I really should change", (yargs) => { definition: ["my-command <foo>", "My command description that I really should change", (yargs) => {
yargs.positional("foo", { describe: "foo is foo!", type: "string" }); yargs.positional("foo", { describe: "foo is foo!", type: "string" });
}], }],
handler: async function(args, control) { handler: async function(args, ctl) {
const response = await control.sendTo("controller", new PluginExampleRequest(args.foo, [1, 2, 3])); const response = await ctl.sendTo("controller", new PluginExampleRequest(args.foo, [1, 2, 3]));
console.log(response); console.log(response);
console.log(args); console.log(args);
}, },
+3 -3
View File
@@ -62,9 +62,9 @@ export const plugin = {
ctlEntrypoint: "./dist/node/ctl.js", ctlEntrypoint: "./dist/node/ctl.js",
//%endif //%endif
//%if ctl & config //%if ctl & config
controlConfigFields: { ctlConfigFields: {
"__plugin_name__.myControlField": { "__plugin_name__.myCtlField": {
title: "My Control Field", title: "My Ctl Field",
description: "This should be removed from index.js", description: "This should be removed from index.js",
type: "string", type: "string",
initialValue: "Remove Me", initialValue: "Remove Me",
+3 -3
View File
@@ -1,4 +1,4 @@
import type { Control, CtlPluginContext } from "@clusterio/ctl"; import type { Ctl, CtlPluginContext } from "@clusterio/ctl";
import { CommandTree, Command } from "@clusterio/lib"; import { CommandTree, Command } from "@clusterio/lib";
//%// We do not check for multi context here because it doesn't make sense to have a ctl without messages //%// We do not check for multi context here because it doesn't make sense to have a ctl without messages
import { PluginExampleEvent, PluginExampleRequest } from "./messages.js"; import { PluginExampleEvent, PluginExampleRequest } from "./messages.js";
@@ -12,8 +12,8 @@ pluginCommands.add(new Command({
definition: ["my-command <foo>", "My command description that I really should change", (yargs) => { definition: ["my-command <foo>", "My command description that I really should change", (yargs) => {
yargs.positional("foo", { describe: "foo is foo!", type: "string" }); yargs.positional("foo", { describe: "foo is foo!", type: "string" });
}], }],
handler: async function(args: { foo: string }, control: Control) { handler: async function(args: { foo: string }, ctl: Ctl) {
const response = await control.sendTo("controller", new PluginExampleRequest(args.foo, [1, 2, 3])); const response = await ctl.sendTo("controller", new PluginExampleRequest(args.foo, [1, 2, 3]));
console.log(response); console.log(response);
console.log(args); console.log(args);
}, },
+5 -5
View File
@@ -22,8 +22,8 @@ declare module "@clusterio/lib" {
} }
//%endif //%endif
//%if ctl & config //%if ctl & config
export interface ControlConfigFields { export interface CtlConfigFields {
"__plugin_name__.myControlField": string; "__plugin_name__.myCtlField": string;
} }
//%endif //%endif
//%if multi_context | web //%if multi_context | web
@@ -106,9 +106,9 @@ export const plugin: lib.PluginDeclaration = {
ctlEntrypoint: "./dist/node/ctl.js", ctlEntrypoint: "./dist/node/ctl.js",
//%endif //%endif
//%if ctl & config //%if ctl & config
controlConfigFields: { ctlConfigFields: {
"__plugin_name__.myControlField": { "__plugin_name__.myCtlField": {
title: "My Control Field", title: "My Ctl Field",
description: "This should be removed from index.js", description: "This should be removed from index.js",
type: "string", type: "string",
initialValue: "Remove Me", initialValue: "Remove Me",
+5 -5
View File
@@ -17,7 +17,7 @@ Common options:
See the `plugin` command for managing this list. See the `plugin` command for managing this list.
* `--config <file>` JSON file to use for storing configuration for ctl. * `--config <file>` JSON file to use for storing configuration for ctl.
Defaults to `config-control.json` and will be created if it does not exist. Defaults to `config-ctl.json` and will be created if it does not exist.
See the `config` command for inspecting and modifying the configuration. See the `config` command for inspecting and modifying the configuration.
@@ -70,13 +70,13 @@ Since the `plugin-list.json` is shared between controller, host and ctl you usua
Lists the plugins set up to be available by name followed by path. Lists the plugins set up to be available by name followed by path.
### `config-control` ### `config`
Manage the ctl configuration. Manage the ctl configuration.
This allows setting the url and token to the controller to manage. This allows setting the url and token to the controller to manage.
#### `config-control set <config-entry> [value]` #### `config set <config-entry> [value]`
Set a config entry to the given value. Set a config entry to the given value.
If value is not provided the entry is set to null. If value is not provided the entry is set to null.
@@ -85,12 +85,12 @@ If the config entry is of type object the value must be a valid JSON serializati
See docs/configuration.md in the main repositiory for the available configuration. See docs/configuration.md in the main repositiory for the available configuration.
#### `config-control show <config-entry>` #### `config show <config-entry>`
Shows the value for a single config entry. Shows the value for a single config entry.
#### `config-control list` #### `config list`
Lists up all configuration entries with their currently configured values. Lists up all configuration entries with their currently configured values.
+45 -45
View File
@@ -23,7 +23,7 @@ import { BaseCtlPlugin, CtlHooks } from "./src/BaseCtlPlugin.js";
* Connector for control connection to controller * Connector for control connection to controller
* @private * @private
*/ */
class ControlConnector extends lib.WebSocketClientConnector { class CtlConnector extends lib.WebSocketClientConnector {
private _token: string; private _token: string;
constructor(url: string, maxReconnectDelay: number, token: string) { constructor(url: string, maxReconnectDelay: number, token: string) {
@@ -45,23 +45,23 @@ class ControlConnector extends lib.WebSocketClientConnector {
} }
/** /**
* Handles running the control * Handles running ctl
* *
* Connects to the controller over WebSocket and sends commands to it. * Connects to the controller over WebSocket and sends commands to it.
* @static * @static
*/ */
export class Control extends lib.Link { export class Ctl extends lib.Link {
/** Control config used for connecting to the controller. */ /** Ctl config used for connecting to the controller. */
config: lib.ControlConfig; config: lib.CtlConfig;
/** Keep the control connection alive after the command completes. */ /** Keep the control connection alive after the command completes. */
keepOpen = false; keepOpen = false;
constructor( constructor(
connector: ControlConnector, connector: CtlConnector,
controlConfig: lib.ControlConfig, ctlConfig: lib.CtlConfig,
) { ) {
super(connector); super(connector);
this.config = controlConfig; this.config = ctlConfig;
this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this)); this.handle(lib.LogMessageEvent, this.handleLogMessageEvent.bind(this));
this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this)); this.handle(lib.DebugWsMessageEvent, this.handleDebugWsMessageEvent.bind(this));
@@ -92,7 +92,7 @@ export class Control extends lib.Link {
async shutdown() { async shutdown() {
try { try {
await (this.connector as ControlConnector).disconnect(); await (this.connector as CtlConnector).disconnect();
} catch (err) { } catch (err) {
if (!(err instanceof lib.SessionLost)) { if (!(err instanceof lib.SessionLost)) {
throw err; throw err;
@@ -135,7 +135,7 @@ interface InitializeParameters {
shouldRun: boolean; shouldRun: boolean;
ctlHooks: CtlHooks; ctlHooks: CtlHooks;
rootCommands?: lib.CommandTree; rootCommands?: lib.CommandTree;
controlConfig?: lib.ControlConfig; ctlConfig?: lib.CtlConfig;
} }
export async function initialize( export async function initialize(
@@ -166,7 +166,7 @@ export async function initialize(
.option("config", { .option("config", {
nargs: 1, nargs: 1,
describe: "config file to get credentails from", describe: "config file to get credentails from",
default: "config-control.json", default: "config-ctl.json",
defaultDescription: "auto", defaultDescription: "auto",
type: "string", type: "string",
}) })
@@ -178,7 +178,7 @@ export async function initialize(
}) })
.option("bypass-lock-file", { hidden: true, type: "boolean", nargs: 0, default: false }) .option("bypass-lock-file", { hidden: true, type: "boolean", nargs: 0, default: false })
.command("plugin", "Manage available plugins", lib.pluginCommand) .command("plugin", "Manage available plugins", lib.pluginCommand)
.command("control-config", "Manage Control config", lib.configCommand) .command("config", "Manage ctl config", lib.configCommand)
.wrap(parser.terminalWidth()) .wrap(parser.terminalWidth())
.help(false) // Disable help to avoid triggering it on the first parse. .help(false) // Disable help to avoid triggering it on the first parse.
; ;
@@ -222,22 +222,22 @@ export async function initialize(
.parse(argv) as CtlArguments .parse(argv) as CtlArguments
; ;
const controlConfigPath = args.config; const ctlConfigPath = args.config;
const controlConfigLockPath = `${controlConfigPath}.lock`; const ctlConfigLockPath = `${ctlConfigPath}.lock`;
if (args.bypassLockFile) { if (args.bypassLockFile) {
await fs.unlink(controlConfigLockPath).catch(() => {}); // ignore error, file might not exist await fs.unlink(ctlConfigLockPath).catch(() => {}); // ignore error, file might not exist
} }
let controlConfig; let ctlConfig;
const controlConfigLock = new lib.LockFile(controlConfigLockPath); const ctlConfigLock = new lib.LockFile(ctlConfigLockPath);
logger.verbose(`Loading config from ${controlConfigPath}`); logger.verbose(`Loading config from ${ctlConfigPath}`);
try { try {
controlConfig = await lib.ControlConfig.fromFile("control", controlConfigPath); ctlConfig = await lib.CtlConfig.fromFile("control", ctlConfigPath);
} catch (err: any) { } catch (err: any) {
if (err.code === "ENOENT") { if (err.code === "ENOENT") {
logger.verbose("Config not found, initializing new config"); logger.verbose("Config not found, initializing new config");
controlConfig = new lib.ControlConfig("control", undefined, controlConfigPath); ctlConfig = new lib.CtlConfig("control", undefined, ctlConfigPath);
} else { } else {
throw new lib.StartupError(`Failed to load ${args.config}: ${err.stack ?? err.message ?? err}`); throw new lib.StartupError(`Failed to load ${args.config}: ${err.stack ?? err.message ?? err}`);
@@ -249,13 +249,13 @@ export async function initialize(
parser.exit(1, undefined as unknown as Error); // Type definition file is wrong. parser.exit(1, undefined as unknown as Error); // Type definition file is wrong.
} }
// Handle the control-config command before trying to connect. // Handle the config command before trying to connect.
if (args._[0] === "control-config") { if (args._[0] === "config") {
await lib.handleConfigCommand(args, controlConfig, controlConfigLock); await lib.handleConfigCommand(args, ctlConfig, ctlConfigLock);
return { args, controlConfig, ctlHooks, rootCommands, shouldRun: false }; return { args, ctlConfig, ctlHooks, rootCommands, shouldRun: false };
} }
return { args, controlConfig, ctlHooks, rootCommands, shouldRun: true }; return { args, ctlConfig, ctlHooks, rootCommands, shouldRun: true };
} }
export function selectTargetCommand(args: CtlArguments, rootCommands: lib.CommandTree): lib.Command { export function selectTargetCommand(args: CtlArguments, rootCommands: lib.CommandTree): lib.Command {
@@ -268,30 +268,30 @@ export function selectTargetCommand(args: CtlArguments, rootCommands: lib.Comman
return targetCommand; return targetCommand;
} }
async function startControl() { async function startCtl() {
const { const {
args, args,
shouldRun, shouldRun,
rootCommands, rootCommands,
controlConfig, ctlConfig,
} = await initialize(process.argv.slice(2)); } = await initialize(process.argv.slice(2));
if (!shouldRun || !rootCommands || !controlConfig) { if (!shouldRun || !rootCommands || !ctlConfig) {
return; return;
} }
if (!controlConfig.get("control.controller_url") || !controlConfig.get("control.controller_token")) { if (!ctlConfig.get("ctl.controller_url") || !ctlConfig.get("ctl.controller_token")) {
logger.error("Missing URL and/or token to connect with. See README.md for setting up access."); logger.error("Missing URL and/or token to connect with. See README.md for setting up access.");
process.exitCode = 1; process.exitCode = 1;
return; return;
} }
let controlConnector = new ControlConnector( let controlConnector = new CtlConnector(
controlConfig.get("control.controller_url")!, ctlConfig.get("ctl.controller_url")!,
controlConfig.get("control.max_reconnect_delay"), ctlConfig.get("ctl.max_reconnect_delay"),
controlConfig.get("control.controller_token")!, ctlConfig.get("ctl.controller_token")!,
); );
let control = new Control(controlConnector, controlConfig); let ctl = new Ctl(controlConnector, ctlConfig);
try { try {
await controlConnector.connect(); await controlConnector.connect();
} catch (err) { } catch (err) {
@@ -302,15 +302,15 @@ async function startControl() {
} }
// Handle interrupts // Handle interrupts
process.on("SIGINT", lib.createShutdownGuard(logger, "interrupt", control.shutdown.bind(control))); process.on("SIGINT", lib.createShutdownGuard(logger, "interrupt", ctl.shutdown.bind(ctl)));
process.on("SIGTERM", lib.createShutdownGuard(logger, "termination", control.shutdown.bind(control))); process.on("SIGTERM", lib.createShutdownGuard(logger, "termination", ctl.shutdown.bind(ctl)));
try { try {
const targetCommand = selectTargetCommand(args, rootCommands); const targetCommand = selectTargetCommand(args, rootCommands);
await targetCommand.run(args, control); await targetCommand.run(args, ctl);
} catch (err) { } catch (err) {
control.keepOpen = false; ctl.keepOpen = false;
if (err instanceof lib.CommandError) { if (err instanceof lib.CommandError) {
logger.error(`Error running command: ${err.message}`); logger.error(`Error running command: ${err.message}`);
process.exitCode = 1; process.exitCode = 1;
@@ -328,8 +328,8 @@ async function startControl() {
} }
} finally { } finally {
if (!control.keepOpen) { if (!ctl.keepOpen) {
await control.shutdown(); await ctl.shutdown();
} }
} }
} }
@@ -343,16 +343,16 @@ I version of clusterio. Expect things to break. I
+==========================================================+ +==========================================================+
` `
); );
startControl().catch(err => { startCtl().catch(err => {
if (err.errors) { if (err.errors) {
logger.fatal(JSON.stringify(err.errors, null, "\t")); logger.fatal(JSON.stringify(err.errors, null, "\t"));
} }
if (!(err instanceof lib.StartupError)) { if (!(err instanceof lib.StartupError)) {
logger.fatal(` logger.fatal(`
+------------------------------------------------------------+ +---------------------------------------------------------------+
| Unexpected error occured while starting control, please | | Unexpected error occured while starting clussterioctl, please |
| report it to https://github.com/clusterio/clusterio/issues | | report it to https://github.com/clusterio/clusterio/issues |
+------------------------------------------------------------+ +---------------------------------------------------------------+
${err.stack}` ${err.stack}`
); );
} else { } else {
+26 -26
View File
@@ -5,7 +5,7 @@ import os from "os";
import child_process from "child_process"; import child_process from "child_process";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js"; import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
@@ -14,15 +14,15 @@ const asTable = asTableModule.configure({ delimiter: " | " });
export const controllerCommands = new lib.CommandTree({ name: "controller", description: "Controller management" }); export const controllerCommands = new lib.CommandTree({ name: "controller", description: "Controller management" });
controllerCommands.add(new lib.Command({ controllerCommands.add(new lib.Command({
definition: ["stop", "Stop controller"], definition: ["stop", "Stop controller"],
handler: async function(_args: object, control: Control) { handler: async function(_args: object, ctl: Ctl) {
await control.send(new lib.ControllerStopRequest()); await ctl.send(new lib.ControllerStopRequest());
}, },
})); }));
controllerCommands.add(new lib.Command({ controllerCommands.add(new lib.Command({
definition: ["restart", "Restart controller"], definition: ["restart", "Restart controller"],
handler: async function(_args: object, control: Control) { handler: async function(_args: object, ctl: Ctl) {
await control.send(new lib.ControllerRestartRequest()); await ctl.send(new lib.ControllerRestartRequest());
}, },
})); }));
controllerCommands.add(new lib.Command({ controllerCommands.add(new lib.Command({
@@ -30,14 +30,14 @@ controllerCommands.add(new lib.Command({
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" }); yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" }); yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" });
}], }],
handler: async function(args: { restart: boolean, all: boolean }, control: Control) { handler: async function(args: { restart: boolean, all: boolean }, ctl: Ctl) {
if (args.all) { if (args.all) {
await control.send(new lib.UpdateAllRequest()); await ctl.send(new lib.UpdateAllRequest());
} else { } else {
await control.send(new lib.ControllerUpdateRequest()); await ctl.send(new lib.ControllerUpdateRequest());
} }
if (args.restart) { if (args.restart) {
await control.send(new lib.ControllerRestartRequest()); await ctl.send(new lib.ControllerRestartRequest());
} else { } else {
print("Controller updated; a restart is required to apply the changes."); print("Controller updated; a restart is required to apply the changes.");
} }
@@ -50,8 +50,8 @@ const controllerConfigCommands = new lib.CommandTree({
controllerConfigCommands.add(new lib.Command({ controllerConfigCommands.add(new lib.Command({
definition: ["list", "List controller configuration"], definition: ["list", "List controller configuration"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
let config = await control.send(new lib.ControllerConfigGetRequest()); let config = await ctl.send(new lib.ControllerConfigGetRequest());
for (let [name, value] of Object.entries(config)) { for (let [name, value] of Object.entries(config)) {
print(`${name} ${JSON.stringify(value)}`); print(`${name} ${JSON.stringify(value)}`);
@@ -67,13 +67,13 @@ controllerConfigCommands.add(new lib.Command({
"stdin": { describe: "read value from stdin", nargs: 0, type: "boolean" }, "stdin": { describe: "read value from stdin", nargs: 0, type: "boolean" },
}); });
}], }],
handler: async function(args: { field: string, value?: string, stdin?: boolean }, control: Control) { handler: async function(args: { field: string, value?: string, stdin?: boolean }, ctl: Ctl) {
if (args.stdin) { if (args.stdin) {
args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, ""); args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, "");
} else if (args.value === undefined) { } else if (args.value === undefined) {
args.value = ""; args.value = "";
} }
await control.send(new lib.ControllerConfigSetFieldRequest(args.field, args.value)); await ctl.send(new lib.ControllerConfigSetFieldRequest(args.field, args.value));
}, },
})); }));
@@ -86,7 +86,7 @@ controllerConfigCommands.add(new lib.Command({
"stdin": { describe: "read value from stdin", nargs: 0, type: "boolean" }, "stdin": { describe: "read value from stdin", nargs: 0, type: "boolean" },
}); });
}], }],
handler: async function(args: { field: string, prop: string, value?: string, stdin?: boolean }, control: Control) { handler: async function(args: { field: string, prop: string, value?: string, stdin?: boolean }, ctl: Ctl) {
if (args.stdin) { if (args.stdin) {
args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, ""); args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, "");
} }
@@ -102,7 +102,7 @@ controllerConfigCommands.add(new lib.Command({
} }
value = args.value; value = args.value;
} }
await control.send(new lib.ControllerConfigSetPropRequest(args.field, args.prop, value)); await ctl.send(new lib.ControllerConfigSetPropRequest(args.field, args.prop, value));
}, },
})); }));
controllerConfigCommands.add(new lib.Command({ controllerConfigCommands.add(new lib.Command({
@@ -113,8 +113,8 @@ controllerConfigCommands.add(new lib.Command({
default: "", default: "",
}); });
}], }],
handler: async function(args: { editor: string }, control: Control) { handler: async function(args: { editor: string }, ctl: Ctl) {
let config = await control.send(new lib.ControllerConfigGetRequest()); let config = await ctl.send(new lib.ControllerConfigGetRequest());
let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir()); let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir());
let editor = await getEditor(args.editor); let editor = await getEditor(args.editor);
if (editor === undefined) { if (editor === undefined) {
@@ -138,7 +138,7 @@ controllerConfigCommands.add(new lib.Command({
for (let index in final) { for (let index in final) {
if (index in final) { if (index in final) {
try { try {
await control.send(new lib.ControllerConfigSetFieldRequest( await ctl.send(new lib.ControllerConfigSetFieldRequest(
index, index,
final[index], final[index],
)); ));
@@ -167,8 +167,8 @@ const controllerPluginCommands = new lib.CommandTree({
}); });
controllerPluginCommands.add(new lib.Command({ controllerPluginCommands.add(new lib.Command({
definition: ["list", "List plugins on controller"], definition: ["list", "List plugins on controller"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
let url = new URL(control.config.get("control.controller_url")!); let url = new URL(ctl.config.get("ctl.controller_url")!);
url.pathname += "api/plugins"; url.pathname += "api/plugins";
let response = await fetch(url); let response = await fetch(url);
print(asTable(await response.json() as [])); print(asTable(await response.json() as []));
@@ -179,10 +179,10 @@ controllerPluginCommands.add(new lib.Command({
yargs.positional("plugin", { describe: "Plugin to update", type: "string" }); yargs.positional("plugin", { describe: "Plugin to update", type: "string" });
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" }); yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
}], }],
handler: async function(args: { plugin: string, restart: boolean }, control: Control) { handler: async function(args: { plugin: string, restart: boolean }, ctl: Ctl) {
await control.sendTo("controller", new lib.PluginUpdateRequest(args.plugin)); await ctl.sendTo("controller", new lib.PluginUpdateRequest(args.plugin));
if (args.restart) { if (args.restart) {
await control.send(new lib.ControllerRestartRequest()); await ctl.send(new lib.ControllerRestartRequest());
} else { } else {
print("Plugin updated; a restart is required to apply the changes."); print("Plugin updated; a restart is required to apply the changes.");
} }
@@ -193,10 +193,10 @@ controllerPluginCommands.add(new lib.Command({
yargs.positional("plugin", { describe: "Plugin to install", type: "string" }); yargs.positional("plugin", { describe: "Plugin to install", type: "string" });
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" }); yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
}], }],
handler: async function(args: { plugin: string, restart: boolean }, control: Control) { handler: async function(args: { plugin: string, restart: boolean }, ctl: Ctl) {
await control.sendTo("controller", new lib.PluginInstallRequest(args.plugin)); await ctl.sendTo("controller", new lib.PluginInstallRequest(args.plugin));
if (args.restart) { if (args.restart) {
await control.send(new lib.ControllerRestartRequest()); await ctl.send(new lib.ControllerRestartRequest());
} else { } else {
print("Plugin installed; a restart is required to apply the changes."); print("Plugin installed; a restart is required to apply the changes.");
} }
+5 -5
View File
@@ -1,12 +1,12 @@
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
export const debugCommands = new lib.CommandTree({ name: "debug", description: "Debugging utilities" }); export const debugCommands = new lib.CommandTree({ name: "debug", description: "Debugging utilities" });
debugCommands.add(new lib.Command({ debugCommands.add(new lib.Command({
definition: ["dump-ws", "Dump WebSocket messages sent and received by controller"], definition: ["dump-ws", "Dump WebSocket messages sent and received by controller"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
await control.send(new lib.DebugDumpWsRequest()); await ctl.send(new lib.DebugDumpWsRequest());
control.keepOpen = true; ctl.keepOpen = true;
}, },
})); }));
@@ -18,7 +18,7 @@ debugCommands.add(new lib.Command({
yargs.positional("exchange-string", { describe: "String to parse", type: "string" }); yargs.positional("exchange-string", { describe: "String to parse", type: "string" });
yargs.option("pretty", { alias: "p", type: "boolean", description: "Pretty output" }); yargs.option("pretty", { alias: "p", type: "boolean", description: "Pretty output" });
}], }],
handler: async function(args: { exchangeString: string, pretty: boolean }, control: Control) { handler: async function(args: { exchangeString: string, pretty: boolean }, ctl: Ctl) {
const result = lib.readMapExchangeString(args.exchangeString); const result = lib.readMapExchangeString(args.exchangeString);
if (args.pretty) { if (args.pretty) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
+45 -45
View File
@@ -6,7 +6,7 @@ import child_process from "child_process";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js"; import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
@@ -17,9 +17,9 @@ hostCommands.add(new lib.Command({
definition: ["stop <host>", "Stop the given host", (yargs) => { definition: ["stop <host>", "Stop the given host", (yargs) => {
yargs.positional("host", { describe: "Host to stop", type: "string" }); yargs.positional("host", { describe: "Host to stop", type: "string" });
}], }],
handler: async function(args: { host: string }, control: Control) { handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
await control.sendTo({ hostId }, new lib.HostStopRequest()); await ctl.sendTo({ hostId }, new lib.HostStopRequest());
}, },
})); }));
@@ -27,16 +27,16 @@ hostCommands.add(new lib.Command({
definition: ["restart <host>", "Restart the given host", (yargs) => { definition: ["restart <host>", "Restart the given host", (yargs) => {
yargs.positional("host", { describe: "Host to restart", type: "string" }); yargs.positional("host", { describe: "Host to restart", type: "string" });
}], }],
handler: async function(args: { host: string }, control: Control) { handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
await control.sendTo({ hostId }, new lib.HostRestartRequest()); await ctl.sendTo({ hostId }, new lib.HostRestartRequest());
}, },
})); }));
hostCommands.add(new lib.Command({ hostCommands.add(new lib.Command({
definition: [["list", "l"], "List hosts connected to the controller"], definition: [["list", "l"], "List hosts connected to the controller"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
let hosts = await control.send(new lib.HostListRequest()); let hosts = await ctl.send(new lib.HostListRequest());
print(asTable(hosts)); print(asTable(hosts));
}, },
})); }));
@@ -45,9 +45,9 @@ hostCommands.add(new lib.Command({
definition: ["generate-token", "Generate token for a host", (yargs) => { definition: ["generate-token", "Generate token for a host", (yargs) => {
yargs.option("id", { type: "number", nargs: 1, describe: "Host id" }); yargs.option("id", { type: "number", nargs: 1, describe: "Host id" });
}], }],
handler: async function(args: { id?: number }, control: Control) { handler: async function(args: { id?: number }, ctl: Ctl) {
let hostId = typeof args.id === "number" ? args.id : undefined; let hostId = typeof args.id === "number" ? args.id : undefined;
let response = await control.send(new lib.HostGenerateTokenRequest(hostId)); let response = await ctl.send(new lib.HostGenerateTokenRequest(hostId));
print(response); print(response);
}, },
})); }));
@@ -56,9 +56,9 @@ hostCommands.add(new lib.Command({
definition: ["revoke-token <host>", "Revoke all tokens for a host", (yargs) => { definition: ["revoke-token <host>", "Revoke all tokens for a host", (yargs) => {
yargs.positional("host", { describe: "Host to revoke tokens for", type: "string" }); yargs.positional("host", { describe: "Host to revoke tokens for", type: "string" });
}], }],
handler: async function(args: { host: string }, control: Control) { handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
await control.send(new lib.HostRevokeTokensRequest(hostId)); await ctl.send(new lib.HostRevokeTokensRequest(hostId));
}, },
})); }));
@@ -75,9 +75,9 @@ hostCommands.add(new lib.Command({
}], }],
handler: async function( handler: async function(
args: { id?: number, name?: string, generateToken: boolean, output: string }, args: { id?: number, name?: string, generateToken: boolean, output: string },
control: Control ctl: Ctl
) { ) {
let config = await control.send( let config = await ctl.send(
new lib.HostConfigCreateRequest(args.id, args.name, args.generateToken) new lib.HostConfigCreateRequest(args.id, args.name, args.generateToken)
); );
@@ -103,15 +103,15 @@ hostCommands.add(new lib.Command({
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" }); yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" }); yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" });
}], }],
handler: async function(args: { host: string, restart: boolean, all: boolean }, control: Control) { handler: async function(args: { host: string, restart: boolean, all: boolean }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
if (args.all) { if (args.all) {
await control.sendTo({ hostId }, new lib.UpdateAllRequest()); await ctl.sendTo({ hostId }, new lib.UpdateAllRequest());
} else { } else {
await control.sendTo({ hostId }, new lib.HostUpdateRequest()); await ctl.sendTo({ hostId }, new lib.HostUpdateRequest());
} }
if (args.restart) { if (args.restart) {
await control.sendTo({ hostId }, new lib.HostRestartRequest()); await ctl.sendTo({ hostId }, new lib.HostRestartRequest());
} else { } else {
print("Host updated; a restart is required to apply the changes."); print("Host updated; a restart is required to apply the changes.");
} }
@@ -126,9 +126,9 @@ hostConfigCommands.add(new lib.Command({
definition: ["list <host>", "List configuration for a host", (yargs) => { definition: ["list <host>", "List configuration for a host", (yargs) => {
yargs.positional("host", { describe: "Host to list config for", type: "string" }); yargs.positional("host", { describe: "Host to list config for", type: "string" });
}], }],
handler: async function(args: { host: string }, control: Control) { handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
let config = await control.sendTo({ hostId }, new lib.HostConfigGetRequest()); let config = await ctl.sendTo({ hostId }, new lib.HostConfigGetRequest());
for (let [name, value] of Object.entries(config)) { for (let [name, value] of Object.entries(config)) {
print(`${name} ${JSON.stringify(value)}`); print(`${name} ${JSON.stringify(value)}`);
@@ -147,15 +147,15 @@ hostConfigCommands.add(new lib.Command({
}], }],
handler: async function( handler: async function(
args: { host: string, field: string, value?: string, stdin?: boolean }, args: { host: string, field: string, value?: string, stdin?: boolean },
control: Control, ctl: Ctl,
) { ) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
if (args.stdin) { if (args.stdin) {
args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, ""); args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, "");
} else if (args.value === undefined) { } else if (args.value === undefined) {
args.value = ""; args.value = "";
} }
await control.sendTo({ hostId }, new lib.HostConfigSetFieldRequest(args.field, args.value)); await ctl.sendTo({ hostId }, new lib.HostConfigSetFieldRequest(args.field, args.value));
}, },
})); }));
@@ -171,9 +171,9 @@ hostConfigCommands.add(new lib.Command({
}], }],
handler: async function( handler: async function(
args: { host: string, field: string, prop: string, value?: string, stdin?: boolean }, args: { host: string, field: string, prop: string, value?: string, stdin?: boolean },
control: Control ctl: Ctl
) { ) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
if (args.stdin) { if (args.stdin) {
args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, ""); args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, "");
} }
@@ -189,7 +189,7 @@ hostConfigCommands.add(new lib.Command({
} }
value = args.value; value = args.value;
} }
await control.sendTo({ hostId }, new lib.HostConfigSetPropRequest(args.field, args.prop, value)); await ctl.sendTo({ hostId }, new lib.HostConfigSetPropRequest(args.field, args.prop, value));
}, },
})); }));
@@ -202,9 +202,9 @@ hostConfigCommands.add(new lib.Command({
default: "", default: "",
}); });
}], }],
handler: async function(args: { host: string, editor: string }, control: Control) { handler: async function(args: { host: string, editor: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
let config = await control.sendTo({ hostId }, new lib.HostConfigGetRequest()); let config = await ctl.sendTo({ hostId }, new lib.HostConfigGetRequest());
let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir()); let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir());
let editor = await getEditor(args.editor); let editor = await getEditor(args.editor);
if (editor === undefined) { if (editor === undefined) {
@@ -231,7 +231,7 @@ hostConfigCommands.add(new lib.Command({
for (let index in final) { for (let index in final) {
if (index in final) { if (index in final) {
try { try {
await control.sendTo({ hostId }, new lib.HostConfigSetFieldRequest( await ctl.sendTo({ hostId }, new lib.HostConfigSetFieldRequest(
index, index,
final[index], final[index],
)); ));
@@ -267,9 +267,9 @@ hostPluginCommands.add(new lib.Command({
definition: ["list <host>", "List plugins on a host", (yargs) => { definition: ["list <host>", "List plugins on a host", (yargs) => {
yargs.positional("host", { describe: "Host to list for", type: "string" }); yargs.positional("host", { describe: "Host to list for", type: "string" });
}], }],
handler: async function(args: { host: string }, control: Control) { handler: async function(args: { host: string }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
const plugins = await control.sendTo({ hostId }, new lib.PluginListRequest()); const plugins = await ctl.sendTo({ hostId }, new lib.PluginListRequest());
print(asTable(plugins.map(p => ({ print(asTable(plugins.map(p => ({
title: p.title, version: p.version, loaded: p.loaded, enabled: p.enabled, npmPackage: p.npmPackage, title: p.title, version: p.version, loaded: p.loaded, enabled: p.enabled, npmPackage: p.npmPackage,
})))); }))));
@@ -281,11 +281,11 @@ hostPluginCommands.add(new lib.Command({
yargs.positional("plugin", { describe: "Plugin to update", type: "string" }); yargs.positional("plugin", { describe: "Plugin to update", type: "string" });
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" }); yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
}], }],
handler: async function(args: { host: string, plugin: string, restart: boolean }, control: Control) { handler: async function(args: { host: string, plugin: string, restart: boolean }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
await control.sendTo({ hostId }, new lib.PluginUpdateRequest(args.plugin)); await ctl.sendTo({ hostId }, new lib.PluginUpdateRequest(args.plugin));
if (args.restart) { if (args.restart) {
await control.sendTo({ hostId }, new lib.HostRestartRequest()); await ctl.sendTo({ hostId }, new lib.HostRestartRequest());
} else { } else {
print("Plugin updated; a restart is required to apply the changes."); print("Plugin updated; a restart is required to apply the changes.");
} }
@@ -297,11 +297,11 @@ hostPluginCommands.add(new lib.Command({
yargs.positional("plugin", { describe: "Plugin to install", type: "string" }); yargs.positional("plugin", { describe: "Plugin to install", type: "string" });
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" }); yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
}], }],
handler: async function(args: { host: string, plugin: string, restart: boolean }, control: Control) { handler: async function(args: { host: string, plugin: string, restart: boolean }, ctl: Ctl) {
let hostId = await lib.resolveHost(control, args.host); let hostId = await lib.resolveHost(ctl, args.host);
await control.sendTo({ hostId }, new lib.PluginInstallRequest(args.plugin)); await ctl.sendTo({ hostId }, new lib.PluginInstallRequest(args.plugin));
if (args.restart) { if (args.restart) {
await control.sendTo({ hostId }, new lib.HostRestartRequest()); await ctl.sendTo({ hostId }, new lib.HostRestartRequest());
} else { } else {
print("Plugin installed; a restart is required to apply the changes."); print("Plugin installed; a restart is required to apply the changes.");
} }
+96 -96
View File
@@ -9,7 +9,7 @@ import util from "util";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js"; import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js";
@@ -21,8 +21,8 @@ export const instanceCommands = new lib.CommandTree({
}); });
instanceCommands.add(new lib.Command({ instanceCommands.add(new lib.Command({
definition: [["list", "l"], "List instances known to the controller"], definition: [["list", "l"], "List instances known to the controller"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
let list = await control.send(new lib.InstanceDetailsListRequest()); let list = await ctl.send(new lib.InstanceDetailsListRequest());
print(asTable(list)); print(asTable(list));
}, },
})); }));
@@ -36,13 +36,13 @@ instanceCommands.add(new lib.Command({
"from": { type: "number", nargs: 1, describe: "Clone config from instance id" }, "from": { type: "number", nargs: 1, describe: "Clone config from instance id" },
}); });
}], }],
handler: async function(args: { name: string, id?: number, from?: number, }, control: Control) { handler: async function(args: { name: string, id?: number, from?: number, }, ctl: Ctl) {
let instanceConfig = new lib.InstanceConfig("control"); let instanceConfig = new lib.InstanceConfig("control");
if (args.id !== undefined) { if (args.id !== undefined) {
instanceConfig.set("instance.id", args.id); instanceConfig.set("instance.id", args.id);
} }
instanceConfig.set("instance.name", args.name); instanceConfig.set("instance.name", args.name);
await control.send(new lib.InstanceCreateRequest( await ctl.send(new lib.InstanceCreateRequest(
instanceConfig.toRemote("controller", [ instanceConfig.toRemote("controller", [
"instance.id", "instance.name", "instance.id", "instance.name",
]), ]),
@@ -58,9 +58,9 @@ instanceConfigCommands.add(new lib.Command({
definition: ["list <instance>", "List configuration for an instance", (yargs) => { definition: ["list <instance>", "List configuration for an instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to list config for", type: "string" }); yargs.positional("instance", { describe: "Instance to list config for", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let config = await control.send(new lib.InstanceConfigGetRequest(instanceId)); let config = await ctl.send(new lib.InstanceConfigGetRequest(instanceId));
for (let [name, value] of Object.entries(config)) { for (let [name, value] of Object.entries(config)) {
print(`${name} ${JSON.stringify(value)}`); print(`${name} ${JSON.stringify(value)}`);
@@ -79,15 +79,15 @@ instanceConfigCommands.add(new lib.Command({
}], }],
handler: async function( handler: async function(
args: { instance: string, field: string, value?: string, stdin?: boolean }, args: { instance: string, field: string, value?: string, stdin?: boolean },
control: Control, ctl: Ctl,
) { ) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
if (args.stdin) { if (args.stdin) {
args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, ""); args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, "");
} else if (args.value === undefined) { } else if (args.value === undefined) {
args.value = ""; args.value = "";
} }
await control.send(new lib.InstanceConfigSetFieldRequest(instanceId, args.field, args.value)); await ctl.send(new lib.InstanceConfigSetFieldRequest(instanceId, args.field, args.value));
}, },
})); }));
@@ -103,9 +103,9 @@ instanceConfigCommands.add(new lib.Command({
}], }],
handler: async function( handler: async function(
args: { instance: string, field: string, prop: string, value?: string, stdin?: boolean }, args: { instance: string, field: string, prop: string, value?: string, stdin?: boolean },
control: Control ctl: Ctl
) { ) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
if (args.stdin) { if (args.stdin) {
args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, ""); args.value = (await lib.readStream(process.stdin)).toString().replace(/\r?\n$/, "");
} }
@@ -136,7 +136,7 @@ instanceConfigCommands.add(new lib.Command({
} }
value = args.value; value = args.value;
} }
await control.send(new lib.InstanceConfigSetPropRequest(instanceId, args.field, args.prop, value)); await ctl.send(new lib.InstanceConfigSetPropRequest(instanceId, args.field, args.prop, value));
}, },
})); }));
@@ -149,9 +149,9 @@ instanceConfigCommands.add(new lib.Command({
default: "", default: "",
}); });
}], }],
handler: async function(args: { instance: string, editor: string }, control: Control) { handler: async function(args: { instance: string, editor: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let config = await control.send(new lib.InstanceConfigGetRequest(instanceId)); let config = await ctl.send(new lib.InstanceConfigGetRequest(instanceId));
let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir()); let tmpFile = await lib.getTempFile("ctl-", "-tmp", os.tmpdir());
let editor = await getEditor(args.editor); let editor = await getEditor(args.editor);
if (editor === undefined) { if (editor === undefined) {
@@ -178,7 +178,7 @@ instanceConfigCommands.add(new lib.Command({
for (let index in final) { for (let index in final) {
if (index in final) { if (index in final) {
try { try {
await control.send(new lib.InstanceConfigSetFieldRequest( await ctl.send(new lib.InstanceConfigSetFieldRequest(
instanceId, instanceId,
index, index,
final[index], final[index],
@@ -211,10 +211,10 @@ instanceCommands.add(new lib.Command({
yargs.positional("instance", { describe: "Instance to assign", type: "string" }); yargs.positional("instance", { describe: "Instance to assign", type: "string" });
yargs.positional("host", { describe: "Host to assign to or unassign if none", type: "string" }); yargs.positional("host", { describe: "Host to assign to or unassign if none", type: "string" });
}], }],
handler: async function(args: { instance: string, host?: string }, control: Control) { handler: async function(args: { instance: string, host?: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let hostId = args.host ? await lib.resolveHost(control, args.host) : undefined; let hostId = args.host ? await lib.resolveHost(ctl, args.host) : undefined;
await control.send(new lib.InstanceAssignRequest(instanceId, hostId)); await ctl.send(new lib.InstanceAssignRequest(instanceId, hostId));
}, },
})); }));
@@ -250,9 +250,9 @@ instanceSaveCommands.add(new lib.Command({
definition: ["list <instance>", "list saves on an instance", (yargs) => { definition: ["list <instance>", "list saves on an instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to list saves on", type: "string" }); yargs.positional("instance", { describe: "Instance to list saves on", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let saves = await control.sendTo("controller", new lib.InstanceSaveDetailsListRequest()); let saves = await ctl.sendTo("controller", new lib.InstanceSaveDetailsListRequest());
saves = saves.filter(save => save.instanceId === instanceId); saves = saves.filter(save => save.instanceId === instanceId);
print(asTable(saves.map( print(asTable(saves.map(
({ mtimeMs, ...rest }) => ({ ...rest, mtime: new Date(mtimeMs).toLocaleString() }) ({ mtimeMs, ...rest }) => ({ ...rest, mtime: new Date(mtimeMs).toLocaleString() })
@@ -280,12 +280,12 @@ instanceSaveCommands.add(new lib.Command({
mapGenSettings?: string, mapGenSettings?: string,
mapSettings?: string, mapSettings?: string,
}, },
control: Control ctl: Ctl
) { ) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let { seed, mapGenSettings, mapSettings } = await loadMapSettings(args); let { seed, mapGenSettings, mapSettings } = await loadMapSettings(args);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
await control.sendTo( await ctl.sendTo(
{ instanceId }, { instanceId },
new lib.InstanceCreateSaveRequest(args.name, seed, mapGenSettings, mapSettings), new lib.InstanceCreateSaveRequest(args.name, seed, mapGenSettings, mapSettings),
); );
@@ -298,9 +298,9 @@ instanceSaveCommands.add(new lib.Command({
yargs.positional("old-name", { describe: "Old name of save.", type: "string" }); yargs.positional("old-name", { describe: "Old name of save.", type: "string" });
yargs.positional("new-name", { describe: "New name of save.", type: "string" }); yargs.positional("new-name", { describe: "New name of save.", type: "string" });
}], }],
handler: async function(args: { instance: string, oldName: string, newName: string }, control: Control) { handler: async function(args: { instance: string, oldName: string, newName: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.send(new lib.InstanceRenameSaveRequest(instanceId, args.oldName, args.newName)); await ctl.send(new lib.InstanceRenameSaveRequest(instanceId, args.oldName, args.newName));
}, },
})); }));
@@ -310,9 +310,9 @@ instanceSaveCommands.add(new lib.Command({
yargs.positional("source", { describe: "Save to copy.", type: "string" }); yargs.positional("source", { describe: "Save to copy.", type: "string" });
yargs.positional("destination", { describe: "Name of copy.", type: "string" }); yargs.positional("destination", { describe: "Name of copy.", type: "string" });
}], }],
handler: async function(args: { instance: string, source: string, destination: string }, control: Control) { handler: async function(args: { instance: string, source: string, destination: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.send(new lib.InstanceCopySaveRequest(instanceId, args.source, args.destination)); await ctl.send(new lib.InstanceCopySaveRequest(instanceId, args.source, args.destination));
}, },
})); }));
@@ -324,14 +324,14 @@ instanceSaveCommands.add(new lib.Command({
"name": { describe: "Name to give save on server", nargs: 1, type: "string" }, "name": { describe: "Name to give save on server", nargs: 1, type: "string" },
}); });
}], }],
handler: async function(args: { instance: string, filepath: string, name?: string }, control: Control) { handler: async function(args: { instance: string, filepath: string, name?: string }, ctl: Ctl) {
let filename = args.name || path.basename(args.filepath); let filename = args.name || path.basename(args.filepath);
if (!filename.endsWith(".zip")) { if (!filename.endsWith(".zip")) {
throw new lib.CommandError("Save name must end with .zip"); throw new lib.CommandError("Save name must end with .zip");
} }
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let url = new URL(control.config.get("control.controller_url")!); let url = new URL(ctl.config.get("ctl.controller_url")!);
url.pathname += "api/upload-save"; url.pathname += "api/upload-save";
url.searchParams.append("instance_id", String(instanceId)); url.searchParams.append("instance_id", String(instanceId));
url.searchParams.append("filename", filename); url.searchParams.append("filename", filename);
@@ -341,7 +341,7 @@ instanceSaveCommands.add(new lib.Command({
body: (await fs.open(args.filepath)).createReadStream(), body: (await fs.open(args.filepath)).createReadStream(),
duplex: "half", duplex: "half",
headers: { headers: {
"X-Access-Token": control.config.get("control.controller_token")!, "X-Access-Token": ctl.config.get("ctl.controller_token")!,
"Content-Type": "application/zip", "Content-Type": "application/zip",
}, },
}); });
@@ -389,11 +389,11 @@ instanceSaveCommands.add(new lib.Command({
targetSave: string, targetSave: string,
copy: boolean, copy: boolean,
}, },
control: Control ctl: Ctl
) { ) {
let sourceInstanceId = await lib.resolveInstance(control, args.sourceInstance); let sourceInstanceId = await lib.resolveInstance(ctl, args.sourceInstance);
let targetInstanceId = await lib.resolveInstance(control, args.targetInstance); let targetInstanceId = await lib.resolveInstance(ctl, args.targetInstance);
let storedName = await control.send( let storedName = await ctl.send(
new lib.InstanceTransferSaveRequest( new lib.InstanceTransferSaveRequest(
sourceInstanceId, sourceInstanceId,
args.sourceSave, args.sourceSave,
@@ -411,11 +411,11 @@ instanceSaveCommands.add(new lib.Command({
yargs.positional("instance", { describe: "Instance to download save from", type: "string" }); yargs.positional("instance", { describe: "Instance to download save from", type: "string" });
yargs.positional("save", { describe: "Save to download", type: "string" }); yargs.positional("save", { describe: "Save to download", type: "string" });
}], }],
handler: async function(args: { instance: string, save: string }, control: Control) { handler: async function(args: { instance: string, save: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
let streamId = await control.send(new lib.InstanceDownloadSaveRequest(instanceId, args.save)); let streamId = await ctl.send(new lib.InstanceDownloadSaveRequest(instanceId, args.save));
let url = new URL(control.config.get("control.controller_url")!); let url = new URL(ctl.config.get("ctl.controller_url")!);
url.pathname += `api/stream/${streamId}`; url.pathname += `api/stream/${streamId}`;
const filename = await lib.downloadFile(url, args.save, "rename"); const filename = await lib.downloadFile(url, args.save, "rename");
@@ -428,9 +428,9 @@ instanceSaveCommands.add(new lib.Command({
yargs.positional("instance", { describe: "Instance to delete save from", type: "string" }); yargs.positional("instance", { describe: "Instance to delete save from", type: "string" });
yargs.positional("save", { describe: "Save to delete", type: "string" }); yargs.positional("save", { describe: "Save to delete", type: "string" });
}], }],
handler: async function(args: { instance: string, save: string }, control: Control) { handler: async function(args: { instance: string, save: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.send(new lib.InstanceDeleteSaveRequest(instanceId, args.save)); await ctl.send(new lib.InstanceDeleteSaveRequest(instanceId, args.save));
}, },
})); }));
instanceCommands.add(instanceSaveCommands); instanceCommands.add(instanceSaveCommands);
@@ -439,10 +439,10 @@ instanceCommands.add(new lib.Command({
definition: ["export-data <instance>", "Export item icons and locale from instance", (yargs) => { definition: ["export-data <instance>", "Export item icons and locale from instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to export from", type: "string" }); yargs.positional("instance", { describe: "Instance to export from", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
await control.sendTo({ instanceId }, new lib.InstanceExportDataRequest()); await ctl.sendTo({ instanceId }, new lib.InstanceExportDataRequest());
}, },
})); }));
@@ -450,9 +450,9 @@ instanceCommands.add(new lib.Command({
definition: ["save-game <instance>", "Save the running game of an instance", (yargs) => { definition: ["save-game <instance>", "Save the running game of an instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to save the game on", type: "string" }); yargs.positional("instance", { describe: "Instance to save the game on", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.sendTo({ instanceId }, new lib.InstanceSaveGameRequest()); await ctl.sendTo({ instanceId }, new lib.InstanceSaveGameRequest());
}, },
})); }));
@@ -460,10 +460,10 @@ instanceCommands.add(new lib.Command({
definition: ["extract-players <instance>", "Extract players from running save into the cluster.", (yargs) => { definition: ["extract-players <instance>", "Extract players from running save into the cluster.", (yargs) => {
yargs.positional("instance", { describe: "Instance to extract players and online time from", type: "string" }); yargs.positional("instance", { describe: "Instance to extract players and online time from", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
await control.sendTo({ instanceId }, new lib.InstanceExtractPlayersRequest()); await ctl.sendTo({ instanceId }, new lib.InstanceExtractPlayersRequest());
}, },
})); }));
@@ -475,11 +475,11 @@ instanceCommands.add(new lib.Command({
"keep-open": { describe: "Keep console open", nargs: 0, type: "boolean", default: false }, "keep-open": { describe: "Keep console open", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: { instance: string, save?: string, keepOpen: boolean }, control: Control) { handler: async function(args: { instance: string, save?: string, keepOpen: boolean }, ctl: Ctl) {
const instanceId = await lib.resolveInstance(control, args.instance); const instanceId = await lib.resolveInstance(ctl, args.instance);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
await control.sendTo({ instanceId }, new lib.InstanceStartRequest(args.save)); await ctl.sendTo({ instanceId }, new lib.InstanceStartRequest(args.save));
control.keepOpen = args.keepOpen; ctl.keepOpen = args.keepOpen;
}, },
})); }));
instanceCommands.add(new lib.Command({ instanceCommands.add(new lib.Command({
@@ -490,11 +490,11 @@ instanceCommands.add(new lib.Command({
"keep-open": { describe: "Keep console open", nargs: 0, type: "boolean", default: false }, "keep-open": { describe: "Keep console open", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: { instance: string, save?: string, keepOpen: boolean }, control: Control) { handler: async function(args: { instance: string, save?: string, keepOpen: boolean }, ctl: Ctl) {
const instanceId = await lib.resolveInstance(control, args.instance); const instanceId = await lib.resolveInstance(ctl, args.instance);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
await control.sendTo({ instanceId }, new lib.InstanceRestartRequest(args.save)); await ctl.sendTo({ instanceId }, new lib.InstanceRestartRequest(args.save));
control.keepOpen = args.keepOpen; ctl.keepOpen = args.keepOpen;
}, },
})); }));
@@ -509,9 +509,9 @@ instanceCommands.add(new lib.Command({
}, },
}); });
}], }],
handler: async function(args: { force: boolean }, control: Control) { handler: async function(args: { force: boolean }, ctl: Ctl) {
// Get all instances // Get all instances
const instances = await control.send(new lib.InstanceDetailsListRequest()); const instances = await ctl.send(new lib.InstanceDetailsListRequest());
// Filter instances that should be started // Filter instances that should be started
const instancesToStart = instances.filter((instance: lib.InstanceDetails) => { const instancesToStart = instances.filter((instance: lib.InstanceDetails) => {
@@ -541,7 +541,7 @@ instanceCommands.add(new lib.Command({
// Start all filtered instances // Start all filtered instances
const startPromises = instancesToStart.map(async (instance: lib.InstanceDetails) => { const startPromises = instancesToStart.map(async (instance: lib.InstanceDetails) => {
try { try {
await control.sendTo({ instanceId: instance.id }, new lib.InstanceStartRequest()); await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStartRequest());
print(`✓ Started ${instance.name}`); print(`✓ Started ${instance.name}`);
} catch (error) { } catch (error) {
print(`✗ Failed to start ${instance.name}: ${error}`); print(`✗ Failed to start ${instance.name}: ${error}`);
@@ -575,15 +575,15 @@ instanceCommands.add(new lib.Command({
mapSettings?: string, mapSettings?: string,
keepOpen: boolean, keepOpen: boolean,
}, },
control: Control) { ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
let { seed, mapGenSettings, mapSettings } = await loadMapSettings(args); let { seed, mapGenSettings, mapSettings } = await loadMapSettings(args);
await control.sendTo( await ctl.sendTo(
{ instanceId }, { instanceId },
new lib.InstanceLoadScenarioRequest(args.scenario, seed, mapGenSettings, mapSettings), new lib.InstanceLoadScenarioRequest(args.scenario, seed, mapGenSettings, mapSettings),
); );
control.keepOpen = args.keepOpen; ctl.keepOpen = args.keepOpen;
}, },
})); }));
@@ -591,18 +591,18 @@ instanceCommands.add(new lib.Command({
definition: ["stop <instance>", "Stop instance", (yargs) => { definition: ["stop <instance>", "Stop instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to stop", type: "string" }); yargs.positional("instance", { describe: "Instance to stop", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
await control.sendTo({ instanceId }, new lib.InstanceStopRequest()); await ctl.sendTo({ instanceId }, new lib.InstanceStopRequest());
}, },
})); }));
instanceCommands.add(new lib.Command({ instanceCommands.add(new lib.Command({
definition: ["stop-all", "Stop all running instances", () => {}], definition: ["stop-all", "Stop all running instances", () => {}],
handler: async function(_args, control: Control) { handler: async function(_args, ctl: Ctl) {
// Get all instances // Get all instances
const instances = await control.send(new lib.InstanceDetailsListRequest()); const instances = await ctl.send(new lib.InstanceDetailsListRequest());
// Filter instances that should be stopped // Filter instances that should be stopped
const instancesToStop = instances const instancesToStop = instances
@@ -621,7 +621,7 @@ instanceCommands.add(new lib.Command({
// Stop all filtered instances // Stop all filtered instances
const stopPromises = instancesToStop.map(async (instance: lib.InstanceDetails) => { const stopPromises = instancesToStop.map(async (instance: lib.InstanceDetails) => {
try { try {
await control.sendTo({ instanceId: instance.id }, new lib.InstanceStopRequest()); await ctl.sendTo({ instanceId: instance.id }, new lib.InstanceStopRequest());
print(`✓ Stopped ${instance.name}`); print(`✓ Stopped ${instance.name}`);
} catch (error) { } catch (error) {
print(`✗ Failed to stop ${instance.name}: ${error}`); print(`✗ Failed to stop ${instance.name}: ${error}`);
@@ -637,10 +637,10 @@ instanceCommands.add(new lib.Command({
definition: ["kill <instance>", "Kill instance", (yargs) => { definition: ["kill <instance>", "Kill instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to kill", type: "string" }); yargs.positional("instance", { describe: "Instance to kill", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.setLogSubscriptions({ instanceIds: [instanceId] }); await ctl.setLogSubscriptions({ instanceIds: [instanceId] });
await control.sendTo({ instanceId }, new lib.InstanceKillRequest()); await ctl.sendTo({ instanceId }, new lib.InstanceKillRequest());
}, },
})); }));
@@ -648,9 +648,9 @@ instanceCommands.add(new lib.Command({
definition: ["delete <instance>", "Delete instance", (yargs) => { definition: ["delete <instance>", "Delete instance", (yargs) => {
yargs.positional("instance", { describe: "Instance to delete", type: "string" }); yargs.positional("instance", { describe: "Instance to delete", type: "string" });
}], }],
handler: async function(args: { instance: string }, control: Control) { handler: async function(args: { instance: string }, ctl: Ctl) {
let instanceId = await lib.resolveInstance(control, args.instance); let instanceId = await lib.resolveInstance(ctl, args.instance);
await control.send(new lib.InstanceDeleteRequest(instanceId)); await ctl.send(new lib.InstanceDeleteRequest(instanceId));
}, },
})); }));
@@ -659,9 +659,9 @@ instanceCommands.add(new lib.Command({
yargs.positional("instance", { describe: "Instance to send to", type: "string" }); yargs.positional("instance", { describe: "Instance to send to", type: "string" });
yargs.positional("command", { describe: "command to send", type: "string" }); yargs.positional("command", { describe: "command to send", type: "string" });
}], }],
handler: async function(args: { instance: string, command: string }, control: Control) { handler: async function(args: { instance: string, command: string }, ctl: Ctl) {
let result = await control.sendTo( let result = await ctl.sendTo(
{ instanceId: await lib.resolveInstance(control, args.instance) }, { instanceId: await lib.resolveInstance(ctl, args.instance) },
new lib.InstanceSendRconRequest(args.command), new lib.InstanceSendRconRequest(args.command),
); );
+10 -10
View File
@@ -2,7 +2,7 @@ import winston from "winston";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { ConsoleTransport, levels, logger } from "@clusterio/lib"; import { ConsoleTransport, levels, logger } from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
export const logCommands = new lib.CommandTree({ name: "log", description: "Log inspection" }); export const logCommands = new lib.CommandTree({ name: "log", description: "Log inspection" });
logCommands.add(new lib.Command({ logCommands.add(new lib.Command({
@@ -16,17 +16,17 @@ logCommands.add(new lib.Command({
}], }],
handler: async function( handler: async function(
args: { all: boolean, controller: boolean, host: string | null, instance: string | null }, args: { all: boolean, controller: boolean, host: string | null, instance: string | null },
control: Control ctl: Ctl
) { ) {
if (!args.all && !args.controller && !args.host && !args.instance) { if (!args.all && !args.controller && !args.host && !args.instance) {
logger.error("At least one of --all, --controller, --host and --instance must be passed"); logger.error("At least one of --all, --controller, --host and --instance must be passed");
process.exitCode = 1; process.exitCode = 1;
return; return;
} }
let instanceIds = args.instance ? [await lib.resolveInstance(control, args.instance)] : []; let instanceIds = args.instance ? [await lib.resolveInstance(ctl, args.instance)] : [];
let hostIds = args.host ? [await lib.resolveHost(control, args.host)] : []; let hostIds = args.host ? [await lib.resolveHost(ctl, args.host)] : [];
await control.setLogSubscriptions({ all: args.all, controller: args.controller, hostIds, instanceIds }); await ctl.setLogSubscriptions({ all: args.all, controller: args.controller, hostIds, instanceIds });
control.keepOpen = true; ctl.keepOpen = true;
}, },
})); }));
@@ -52,16 +52,16 @@ logCommands.add(new lib.Command({
limit: number, limit: number,
start: boolean, start: boolean,
}, },
control: Control ctl: Ctl
) { ) {
if (!args.all && !args.controller && !args.host && !args.instance) { if (!args.all && !args.controller && !args.host && !args.instance) {
logger.error("At least one of --all, --controller, --host and --instance must be passed"); logger.error("At least one of --all, --controller, --host and --instance must be passed");
process.exitCode = 1; process.exitCode = 1;
return; return;
} }
let instanceIds = args.instance ? [await lib.resolveInstance(control, args.instance)] : []; let instanceIds = args.instance ? [await lib.resolveInstance(ctl, args.instance)] : [];
let hostIds = args.host ? [await lib.resolveHost(control, args.host)] : []; let hostIds = args.host ? [await lib.resolveHost(ctl, args.host)] : [];
let result = await control.send(new lib.LogQueryRequest( let result = await ctl.send(new lib.LogQueryRequest(
args.all, args.all,
args.controller, args.controller,
hostIds, hostIds,
+15 -15
View File
@@ -7,7 +7,7 @@ import util from "util";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " }); const asTable = asTableModule.configure({ delimiter: " | " });
@@ -19,11 +19,11 @@ modCommands.add(new lib.Command({
yargs.positional("name", { describe: "Mod name to show details for", type: "string" }); yargs.positional("name", { describe: "Mod name to show details for", type: "string" });
yargs.positional("mod-version", { describe: "Version of the mod", type: "string" }); yargs.positional("mod-version", { describe: "Version of the mod", type: "string" });
}], }],
handler: async function(args: { name: string, modVersion: string }, control: Control) { handler: async function(args: { name: string, modVersion: string }, ctl: Ctl) {
if (!lib.isSourceVersion(args.modVersion)) { if (!lib.isSourceVersion(args.modVersion)) {
throw new lib.CommandError("mod-version must match format digit.digit.digit"); throw new lib.CommandError("mod-version must match format digit.digit.digit");
} }
let modInfo = await control.send(new lib.ModGetRequest(args.name, args.modVersion)); let modInfo = await ctl.send(new lib.ModGetRequest(args.name, args.modVersion));
for (let [field, value] of Object.entries(modInfo)) { for (let [field, value] of Object.entries(modInfo)) {
if (value instanceof Array) { if (value instanceof Array) {
print(`${field}:`); print(`${field}:`);
@@ -48,8 +48,8 @@ modCommands.add(new lib.Command({
}, },
}); });
}], }],
handler: async function(args: { fields: string[] }, control: Control) { handler: async function(args: { fields: string[] }, ctl: Ctl) {
let mods = await control.send(new lib.ModListRequest()); let mods = await ctl.send(new lib.ModListRequest());
if (!args.fields.includes("all")) { if (!args.fields.includes("all")) {
for (let entry of mods) { for (let entry of mods) {
for (let field of Object.keys(entry)) { for (let field of Object.keys(entry)) {
@@ -106,13 +106,13 @@ modCommands.add(new lib.Command({
sortOrder: "asc" | "desc", sortOrder: "asc" | "desc",
fields: string[], fields: string[],
}, },
control: Control ctl: Ctl
) { ) {
const searchVersion = lib.normaliseSourceVersion(String(args.factorioVersion)); const searchVersion = lib.normaliseSourceVersion(String(args.factorioVersion));
if (searchVersion === undefined) { if (searchVersion === undefined) {
throw new Error(`Invalid factorio version "${args.factorioVersion}"`); throw new Error(`Invalid factorio version "${args.factorioVersion}"`);
} }
let response = await control.send(new lib.ModSearchRequest( let response = await ctl.send(new lib.ModSearchRequest(
args.query, args.query,
lib.normaliseMajorMinorVersion(searchVersion), lib.normaliseMajorMinorVersion(searchVersion),
args.page, args.page,
@@ -143,13 +143,13 @@ modCommands.add(new lib.Command({
definition: ["upload <file>", "Upload mod to the cluster", (yargs) => { definition: ["upload <file>", "Upload mod to the cluster", (yargs) => {
yargs.positional("file", { describe: "File to upload", type: "string" }); yargs.positional("file", { describe: "File to upload", type: "string" });
}], }],
handler: async function(args: { file: string }, control: Control) { handler: async function(args: { file: string }, ctl: Ctl) {
let filename = path.basename(args.file); let filename = path.basename(args.file);
if (!filename.endsWith(".zip")) { if (!filename.endsWith(".zip")) {
throw new lib.CommandError("Mod filename must end with .zip"); throw new lib.CommandError("Mod filename must end with .zip");
} }
let url = new URL(control.config.get("control.controller_url")!); let url = new URL(ctl.config.get("ctl.controller_url")!);
url.pathname += "api/upload-mod"; url.pathname += "api/upload-mod";
url.searchParams.append("filename", filename); url.searchParams.append("filename", filename);
@@ -158,7 +158,7 @@ modCommands.add(new lib.Command({
body: (await fs.open(args.file)).createReadStream(), body: (await fs.open(args.file)).createReadStream(),
duplex: "half", duplex: "half",
headers: { headers: {
"X-Access-Token": control.config.get("control.controller_token")!, "X-Access-Token": ctl.config.get("ctl.controller_token")!,
"Content-Type": "application/zip", "Content-Type": "application/zip",
}, },
}); });
@@ -190,13 +190,13 @@ modCommands.add(new lib.Command({
yargs.positional("name", { describe: "Internal name of mod to download", type: "string" }); yargs.positional("name", { describe: "Internal name of mod to download", type: "string" });
yargs.positional("mod-version", { describe: "Version of mod to download", type: "string" }); yargs.positional("mod-version", { describe: "Version of mod to download", type: "string" });
}], }],
handler: async function(args: { name: string, modVersion: string }, control: Control) { handler: async function(args: { name: string, modVersion: string }, ctl: Ctl) {
if (!lib.isSourceVersion(args.modVersion)) { if (!lib.isSourceVersion(args.modVersion)) {
throw new lib.CommandError("mod-version must match format digit.digit.digit"); throw new lib.CommandError("mod-version must match format digit.digit.digit");
} }
let streamId = await control.send(new lib.ModDownloadRequest(args.name, args.modVersion)); let streamId = await ctl.send(new lib.ModDownloadRequest(args.name, args.modVersion));
let url = new URL(control.config.get("control.controller_url")!); let url = new URL(ctl.config.get("ctl.controller_url")!);
url.pathname += `api/stream/${streamId}`; url.pathname += `api/stream/${streamId}`;
let filename = `${args.name}_${args.modVersion}.zip`; let filename = `${args.name}_${args.modVersion}.zip`;
await lib.downloadFile(url, filename, "overwrite"); await lib.downloadFile(url, filename, "overwrite");
@@ -210,10 +210,10 @@ modCommands.add(new lib.Command({
yargs.positional("name", { describe: "Name of mod to delete", type: "string" }); yargs.positional("name", { describe: "Name of mod to delete", type: "string" });
yargs.positional("mod-version", { describe: "Version of mod to delete", type: "string" }); yargs.positional("mod-version", { describe: "Version of mod to delete", type: "string" });
}], }],
handler: async function(args: { name: string, modVersion: string }, control: Control) { handler: async function(args: { name: string, modVersion: string }, ctl: Ctl) {
if (!lib.isSourceVersion(args.modVersion)) { if (!lib.isSourceVersion(args.modVersion)) {
throw new lib.CommandError("mod-version must match format digit.digit.digit"); throw new lib.CommandError("mod-version must match format digit.digit.digit");
} }
await control.send(new lib.ModDeleteRequest(args.name, args.modVersion)); await ctl.send(new lib.ModDeleteRequest(args.name, args.modVersion));
}, },
})); }));
+21 -21
View File
@@ -2,7 +2,7 @@ import asTableModule from "as-table";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " }); const asTable = asTableModule.configure({ delimiter: " | " });
@@ -12,12 +12,12 @@ modPackCommands.add(new lib.Command({
definition: ["show <mod-pack>", "Show details of mod pack", (yargs) => { definition: ["show <mod-pack>", "Show details of mod pack", (yargs) => {
yargs.positional("mod-pack", { describe: "Mod pack to show", type: "string" }); yargs.positional("mod-pack", { describe: "Mod pack to show", type: "string" });
}], }],
handler: async function(args: { modPack: string }, control: Control) { handler: async function(args: { modPack: string }, ctl: Ctl) {
let mods = new Map( let mods = new Map(
(await control.send(new lib.ModListRequest())).map(m => [m.id, m]) (await ctl.send(new lib.ModListRequest())).map(m => [m.id, m])
); );
let modPack = await control.send( let modPack = await ctl.send(
new lib.ModPackGetRequest(await lib.resolveModPack(control, args.modPack)) new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack))
); );
for (let [field, value] of Object.entries(modPack)) { for (let [field, value] of Object.entries(modPack)) {
@@ -57,8 +57,8 @@ modPackCommands.add(new lib.Command({
modPackCommands.add(new lib.Command({ modPackCommands.add(new lib.Command({
definition: [["list", "l"], "List mod packs in the cluster"], definition: [["list", "l"], "List mod packs in the cluster"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
let modPacks = await control.send(new lib.ModPackListRequest()); let modPacks = await ctl.send(new lib.ModPackListRequest());
let fields = ["id", "name", "factorioVersion"]; let fields = ["id", "name", "factorioVersion"];
for (let entry of modPacks) { for (let entry of modPacks) {
for (let field of Object.keys(entry)) { for (let field of Object.keys(entry)) {
@@ -179,7 +179,7 @@ modPackCommands.add(new lib.Command({
stringSetting?: string[], stringSetting?: string[],
colorSetting?: string[], colorSetting?: string[],
}, },
control: Control, ctl: Ctl,
) { ) {
const modPack = new lib.ModPack(); const modPack = new lib.ModPack();
modPack.name = args.name; modPack.name = args.name;
@@ -193,7 +193,7 @@ modPackCommands.add(new lib.Command({
setModPackMods(modPack, args.mods); setModPackMods(modPack, args.mods);
setModPackModsEnabled(modPack, args.disabledMods, false); setModPackModsEnabled(modPack, args.disabledMods, false);
setModPackSettings(modPack, args); setModPackSettings(modPack, args);
await control.send(new lib.ModPackCreateRequest(modPack)); await ctl.send(new lib.ModPackCreateRequest(modPack));
print(`Created mod pack ${modPack.name} (${modPack.id})`); print(`Created mod pack ${modPack.name} (${modPack.id})`);
}, },
})); }));
@@ -202,9 +202,9 @@ modPackCommands.add(new lib.Command({
definition: ["import <string>", "Import mod pack string", (yargs) => { definition: ["import <string>", "Import mod pack string", (yargs) => {
yargs.positional("string", { describe: "Mod pack string to import", type: "string" }); yargs.positional("string", { describe: "Mod pack string to import", type: "string" });
}], }],
handler: async function(args: { string: string }, control: Control) { handler: async function(args: { string: string }, ctl: Ctl) {
const modPack = lib.ModPack.fromModPackString(args.string); const modPack = lib.ModPack.fromModPackString(args.string);
await control.send(new lib.ModPackCreateRequest(modPack)); await ctl.send(new lib.ModPackCreateRequest(modPack));
print(`Created mod pack ${modPack.name} (${modPack.id})`); print(`Created mod pack ${modPack.name} (${modPack.id})`);
}, },
})); }));
@@ -213,9 +213,9 @@ modPackCommands.add(new lib.Command({
definition: ["export <mod-pack>", "Export mod pack string", (yargs) => { definition: ["export <mod-pack>", "Export mod pack string", (yargs) => {
yargs.positional("string", { describe: "Mod pack to export", type: "string" }); yargs.positional("string", { describe: "Mod pack to export", type: "string" });
}], }],
handler: async function(args: { modPack: string }, control: Control) { handler: async function(args: { modPack: string }, ctl: Ctl) {
const modPack = await control.send( const modPack = await ctl.send(
new lib.ModPackGetRequest(await lib.resolveModPack(control, args.modPack)) new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack))
); );
print(modPack.toModPackString()); print(modPack.toModPackString());
}, },
@@ -257,10 +257,10 @@ modPackCommands.add(new lib.Command({
colorSetting?: string[], colorSetting?: string[],
removeSetting?: string[], removeSetting?: string[],
}, },
control: Control, ctl: Ctl,
) { ) {
const modPack = await control.send( const modPack = await ctl.send(
new lib.ModPackGetRequest(await lib.resolveModPack(control, args.modPack)) new lib.ModPackGetRequest(await lib.resolveModPack(ctl, args.modPack))
); );
if (args.name) { modPack.name = args.name; } if (args.name) { modPack.name = args.name; }
@@ -300,7 +300,7 @@ modPackCommands.add(new lib.Command({
} }
} }
} }
await control.send(new lib.ModPackUpdateRequest(modPack)); await ctl.send(new lib.ModPackUpdateRequest(modPack));
}, },
})); }));
@@ -308,8 +308,8 @@ modPackCommands.add(new lib.Command({
definition: ["delete <mod-pack>", "Delete mod pack", (yargs) => { definition: ["delete <mod-pack>", "Delete mod pack", (yargs) => {
yargs.positional("mod-pack", { describe: "Mod pack to delete", type: "string" }); yargs.positional("mod-pack", { describe: "Mod pack to delete", type: "string" });
}], }],
handler: async function(args: { modPack: string }, control: Control) { handler: async function(args: { modPack: string }, ctl: Ctl) {
const id = await lib.resolveModPack(control, args.modPack); const id = await lib.resolveModPack(ctl, args.modPack);
await control.send(new lib.ModPackDeleteRequest(id)); await ctl.send(new lib.ModPackDeleteRequest(id));
}, },
})); }));
+3 -3
View File
@@ -1,7 +1,7 @@
import asTableModule from "as-table"; import asTableModule from "as-table";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " }); const asTable = asTableModule.configure({ delimiter: " | " });
@@ -9,8 +9,8 @@ const asTable = asTableModule.configure({ delimiter: " | " });
export const permissionCommands = new lib.CommandTree({ name: "permission", description: "Permission inspection" }); export const permissionCommands = new lib.CommandTree({ name: "permission", description: "Permission inspection" });
permissionCommands.add(new lib.Command({ permissionCommands.add(new lib.Command({
definition: [["list", "l"], "List permissions in the cluster"], definition: [["list", "l"], "List permissions in the cluster"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
let permissions = await control.send(new lib.PermissionListRequest()); let permissions = await ctl.send(new lib.PermissionListRequest());
print(asTable(permissions)); print(asTable(permissions));
}, },
})); }));
+12 -12
View File
@@ -2,7 +2,7 @@ import asTableModule from "as-table";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib"; import { logger } from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " }); const asTable = asTableModule.configure({ delimiter: " | " });
@@ -10,8 +10,8 @@ const asTable = asTableModule.configure({ delimiter: " | " });
export const roleCommands = new lib.CommandTree({ name: "role", description: "Role management" }); export const roleCommands = new lib.CommandTree({ name: "role", description: "Role management" });
roleCommands.add(new lib.Command({ roleCommands.add(new lib.Command({
definition: [["list", "l"], "List roles in the cluster"], definition: [["list", "l"], "List roles in the cluster"],
handler: async function(args: object, control: Control) { handler: async function(args: object, ctl: Ctl) {
let roles = await control.send(new lib.RoleListRequest()); let roles = await ctl.send(new lib.RoleListRequest());
print(asTable(roles)); print(asTable(roles));
}, },
})); }));
@@ -24,8 +24,8 @@ roleCommands.add(new lib.Command({
"permissions": { describe: "Permissions role grants", nargs: 1, array: true, type: "string", default: [] }, "permissions": { describe: "Permissions role grants", nargs: 1, array: true, type: "string", default: [] },
}); });
}], }],
handler: async function(args: { name: string, description: string, permissions: string[] }, control: Control) { handler: async function(args: { name: string, description: string, permissions: string[] }, ctl: Ctl) {
let id = await control.send(new lib.RoleCreateRequest( let id = await ctl.send(new lib.RoleCreateRequest(
args.name, args.name,
args.description, args.description,
args.permissions, args.permissions,
@@ -58,9 +58,9 @@ roleCommands.add(new lib.Command({
removePerms?: string[], removePerms?: string[],
grantDefault?: boolean, grantDefault?: boolean,
}, },
control: Control ctl: Ctl
) { ) {
let role = await lib.retrieveRole(control, args.role); let role = await lib.retrieveRole(ctl, args.role);
if (args.name !== undefined) { if (args.name !== undefined) {
role.name = args.name; role.name = args.name;
@@ -81,10 +81,10 @@ roleCommands.add(new lib.Command({
if (args.setPerms !== undefined) { if (args.setPerms !== undefined) {
role.permissions = new Set(args.setPerms); role.permissions = new Set(args.setPerms);
} }
await control.send(new lib.RoleUpdateRequest(role.id, role.name, role.description, [...role.permissions])); await ctl.send(new lib.RoleUpdateRequest(role.id, role.name, role.description, [...role.permissions]));
if (args.grantDefault) { if (args.grantDefault) {
await control.send(new lib.RoleGrantDefaultPermissionsRequest(role.id)); await ctl.send(new lib.RoleGrantDefaultPermissionsRequest(role.id));
} }
}, },
})); }));
@@ -93,8 +93,8 @@ roleCommands.add(new lib.Command({
definition: ["delete <role>", "Delete role", (yargs) => { definition: ["delete <role>", "Delete role", (yargs) => {
yargs.positional("role", { describe: "Role to delete", type: "string" }); yargs.positional("role", { describe: "Role to delete", type: "string" });
}], }],
handler: async function(args: { role: string }, control: Control) { handler: async function(args: { role: string }, ctl: Ctl) {
let role = await lib.retrieveRole(control, args.role); let role = await lib.retrieveRole(ctl, args.role);
await control.send(new lib.RoleDeleteRequest(role.id)); await ctl.send(new lib.RoleDeleteRequest(role.id));
}, },
})); }));
+29 -29
View File
@@ -3,7 +3,7 @@ import asTableModule from "as-table";
import path from "path"; import path from "path";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
import type { Control } from "../ctl.js"; import type { Ctl } from "../ctl.js";
import { print } from "./command_ops.js"; import { print } from "./command_ops.js";
const asTable = asTableModule.configure({ delimiter: " | " }); const asTable = asTableModule.configure({ delimiter: " | " });
@@ -16,8 +16,8 @@ userCommands.add(new lib.Command({
"instance-stats": { describe: "include per-instance stats", nargs: 0, type: "boolean", default: false }, "instance-stats": { describe: "include per-instance stats", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: { name: string, instanceStats: boolean }, control: Control) { handler: async function(args: { name: string, instanceStats: boolean }, ctl: Ctl) {
let user = await control.send(new lib.UserGetRequest(args.name)); let user = await ctl.send(new lib.UserGetRequest(args.name));
Object.assign(user, user.playerStats); Object.assign(user, user.playerStats);
// @ts-expect-error Terrible hack // @ts-expect-error Terrible hack
delete user.playerStats; delete user.playerStats;
@@ -27,7 +27,7 @@ userCommands.add(new lib.Command({
print(asTable(Object.entries(user).map(([property, value]) => ({ property, value })))); print(asTable(Object.entries(user).map(([property, value]) => ({ property, value }))));
if (args.instanceStats) { if (args.instanceStats) {
let instances = await control.send(new lib.InstanceDetailsListRequest()); let instances = await ctl.send(new lib.InstanceDetailsListRequest());
function instanceName(id: number) { function instanceName(id: number) {
let instance = instances.find(i => i.id === id); let instance = instances.find(i => i.id === id);
if (instance) { if (instance) {
@@ -51,8 +51,8 @@ userCommands.add(new lib.Command({
"attributes": { describe: "include admin/whitelisted/banned", nargs: 0, type: "boolean", default: false }, "attributes": { describe: "include admin/whitelisted/banned", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: { stats: boolean, attributes: boolean }, control: Control) { handler: async function(args: { stats: boolean, attributes: boolean }, ctl: Ctl) {
let users = await control.send(new lib.UserListRequest()); let users = await ctl.send(new lib.UserListRequest());
for (let user of users) { for (let user of users) {
if (args.stats) { if (args.stats) {
Object.assign(user, user.playerStats); Object.assign(user, user.playerStats);
@@ -82,8 +82,8 @@ userCommands.add(new lib.Command({
definition: ["create <name>", "Create a user", (yargs) => { definition: ["create <name>", "Create a user", (yargs) => {
yargs.positional("name", { describe: "Name of user to create", type: "string" }); yargs.positional("name", { describe: "Name of user to create", type: "string" });
}], }],
handler: async function(args: { name: string }, control: Control) { handler: async function(args: { name: string }, ctl: Ctl) {
await control.send(new lib.UserCreateRequest(args.name)); await ctl.send(new lib.UserCreateRequest(args.name));
}, },
})); }));
@@ -91,8 +91,8 @@ userCommands.add(new lib.Command({
definition: ["revoke-token <name>", "Revoke token for user", (yargs) => { definition: ["revoke-token <name>", "Revoke token for user", (yargs) => {
yargs.positional("name", { describe: "Name of user to revoke token for", type: "string" }); yargs.positional("name", { describe: "Name of user to revoke token for", type: "string" });
}], }],
handler: async function(args: { name: string }, control: Control) { handler: async function(args: { name: string }, ctl: Ctl) {
await control.send(new lib.UserRevokeTokenRequest(args.name)); await ctl.send(new lib.UserRevokeTokenRequest(args.name));
}, },
})); }));
@@ -104,8 +104,8 @@ userCommands.add(new lib.Command({
"create": { describe: "Create user if it does not exist", nargs: 0, type: "boolean", default: false }, "create": { describe: "Create user if it does not exist", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: { user: string, revoke: boolean, create: boolean }, control: Control) { handler: async function(args: { user: string, revoke: boolean, create: boolean }, ctl: Ctl) {
await control.send(new lib.UserSetAdminRequest(args.user, args.create, !args.revoke)); await ctl.send(new lib.UserSetAdminRequest(args.user, args.create, !args.revoke));
}, },
})); }));
@@ -117,8 +117,8 @@ userCommands.add(new lib.Command({
"create": { describe: "Create user if it does not exist", nargs: 0, type: "boolean", default: false }, "create": { describe: "Create user if it does not exist", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: { user: string, remove: boolean, create: boolean }, control: Control) { handler: async function(args: { user: string, remove: boolean, create: boolean }, ctl: Ctl) {
await control.send(new lib.UserSetWhitelistedRequest(args.user, args.create, !args.remove)); await ctl.send(new lib.UserSetWhitelistedRequest(args.user, args.create, !args.remove));
}, },
})); }));
@@ -138,9 +138,9 @@ userCommands.add(new lib.Command({
reason: string, reason: string,
create: boolean create: boolean
}, },
control: Control ctl: Ctl
) { ) {
await control.send(new lib.UserSetBannedRequest(args.user, args.create, !args.pardon, args.reason)); await ctl.send(new lib.UserSetBannedRequest(args.user, args.create, !args.pardon, args.reason));
}, },
})); }));
@@ -149,8 +149,8 @@ userCommands.add(new lib.Command({
yargs.positional("user", { describe: "Name of user to change roles for", type: "string" }); yargs.positional("user", { describe: "Name of user to change roles for", type: "string" });
yargs.positional("roles", { describe: "roles to assign", type: "string" }); yargs.positional("roles", { describe: "roles to assign", type: "string" });
}], }],
handler: async function(args: { user: string, roles: string[] }, control: Control) { handler: async function(args: { user: string, roles: string[] }, ctl: Ctl) {
let roles = await control.send(new lib.RoleListRequest()); let roles = await ctl.send(new lib.RoleListRequest());
let resolvedRoles = []; let resolvedRoles = [];
for (let roleName of args.roles) { for (let roleName of args.roles) {
@@ -174,7 +174,7 @@ userCommands.add(new lib.Command({
} }
} }
await control.send(new lib.UserUpdateRolesRequest(args.user, resolvedRoles)); await ctl.send(new lib.UserUpdateRolesRequest(args.user, resolvedRoles));
}, },
})); }));
@@ -182,8 +182,8 @@ userCommands.add(new lib.Command({
definition: ["delete <user>", "Delete user", (yargs) => { definition: ["delete <user>", "Delete user", (yargs) => {
yargs.positional("user", { describe: "Name of user to delete", type: "string" }); yargs.positional("user", { describe: "Name of user to delete", type: "string" });
}], }],
handler: async function(args: { user: string }, control: Control) { handler: async function(args: { user: string }, ctl: Ctl) {
await control.send(new lib.UserDeleteRequest(args.user)); await ctl.send(new lib.UserDeleteRequest(args.user));
}, },
})); }));
@@ -194,7 +194,7 @@ async function handleImportOrRestore(args: {
admins: boolean, admins: boolean,
whitelist: boolean, whitelist: boolean,
noBackup?: boolean, noBackup?: boolean,
}, control: Control, restore: boolean) { }, ctl: Ctl, restore: boolean) {
let importType: ConstructorParameters<typeof lib.UserBulkImportRequest>[0]; let importType: ConstructorParameters<typeof lib.UserBulkImportRequest>[0];
const data = JSON.parse((await fs.readFile(args.filepath)).toString()); const data = JSON.parse((await fs.readFile(args.filepath)).toString());
const optionCount = [args.users, args.bans, args.admins, args.whitelist] const optionCount = [args.users, args.bans, args.admins, args.whitelist]
@@ -218,7 +218,7 @@ async function handleImportOrRestore(args: {
throw new lib.CommandError("Unknown json file, please specify an option"); throw new lib.CommandError("Unknown json file, please specify an option");
} }
const backup = await control.send( const backup = await ctl.send(
new lib.UserBulkImportRequest(importType, importType === "users" ? data.users : data, restore) new lib.UserBulkImportRequest(importType, importType === "users" ? data.users : data, restore)
); );
@@ -239,8 +239,8 @@ userCommands.add(new lib.Command({
"whitelist": { describe: "Import whitelist json", nargs: 0, type: "boolean", default: false }, "whitelist": { describe: "Import whitelist json", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: any, control: any) { handler: async function(args: any, ctl: any) {
await handleImportOrRestore(args, control, false); await handleImportOrRestore(args, ctl, false);
}, },
})); }));
@@ -255,8 +255,8 @@ userCommands.add(new lib.Command({
"no-backup": { describe: "Don't save a backup to the cwd", nargs: 0, type: "boolean", default: false }, "no-backup": { describe: "Don't save a backup to the cwd", nargs: 0, type: "boolean", default: false },
}); });
}], }],
handler: async function(args: any, control: any) { handler: async function(args: any, ctl: any) {
await handleImportOrRestore(args, control, true); await handleImportOrRestore(args, ctl, true);
}, },
})); }));
@@ -276,7 +276,7 @@ userCommands.add(new lib.Command({
bans: boolean, bans: boolean,
admins: boolean, admins: boolean,
whitelist: boolean, whitelist: boolean,
}, control: Control) { }, ctl: Ctl) {
let exportType = "users" as ConstructorParameters<typeof lib.UserBulkExportRequest>[0]; let exportType = "users" as ConstructorParameters<typeof lib.UserBulkExportRequest>[0];
const optionCount = [args.bans, args.admins, args.whitelist] const optionCount = [args.bans, args.admins, args.whitelist]
.reduce((acc, bool) => (bool ? acc + 1 : acc), 0); .reduce((acc, bool) => (bool ? acc + 1 : acc), 0);
@@ -296,7 +296,7 @@ userCommands.add(new lib.Command({
exportType = "whitelist"; exportType = "whitelist";
} }
await fs.writeFile(args.filepath, JSON.stringify(await control.send( await fs.writeFile(args.filepath, JSON.stringify(await ctl.send(
new lib.UserBulkExportRequest(exportType) new lib.UserBulkExportRequest(exportType)
), undefined, "\t")); ), undefined, "\t"));
print(`Exported ${exportType} to ${args.filepath}`); print(`Exported ${exportType} to ${args.filepath}`);
+5 -5
View File
@@ -11,7 +11,7 @@ import * as libErrors from "./errors.js";
import type { Link } from "./link/index.js"; import type { Link } from "./link/index.js";
import type { Argv } from "yargs"; import type { Argv } from "yargs";
export type CommandHandler = (args: any, control: any) => Promise<void>; export type CommandHandler = (args: any, ctl: any) => Promise<void>;
export type CommandDefinition = [string | string[], string?, ((yargs: Argv) => void)?]; export type CommandDefinition = [string | string[], string?, ((yargs: Argv) => void)?];
/** /**
@@ -34,7 +34,7 @@ export class Command {
* @param cmd.handler - * @param cmd.handler -
* Async function invoked when the command is executed. Is given * Async function invoked when the command is executed. Is given
* the parsed args and a reference to the {@link * the parsed args and a reference to the {@link
* module:ctl/ctl.Control} instance. * module:ctl/ctl.Ctl} instance.
*/ */
constructor({ definition, handler }: { definition: CommandDefinition, handler: CommandHandler }) { constructor({ definition, handler }: { definition: CommandDefinition, handler: CommandHandler }) {
if (definition[0] instanceof Array) { if (definition[0] instanceof Array) {
@@ -52,8 +52,8 @@ export class Command {
yargs.command(...this._definition); yargs.command(...this._definition);
} }
async run(args: Record<string, unknown>, control: Link) { async run(args: Record<string, unknown>, ctl: Link) {
await this._handler(args, control); await this._handler(args, ctl);
} }
} }
@@ -62,7 +62,7 @@ export class Command {
* *
* Container which can contain {@link module:lib.Command}s and other * Container which can contain {@link module:lib.Command}s and other
* CommandTrees. This is used by clusterioctl to hold the full tree of * CommandTrees. This is used by clusterioctl to hold the full tree of
* available commands, you may extend this tree by using a control plugin, * available commands, you may extend this tree by using a ctl plugin,
* see {@link module:lib.BaseControlPlugin#addCommands} * see {@link module:lib.BaseControlPlugin#addCommands}
*/ */
export class CommandTree { export class CommandTree {
+12 -12
View File
@@ -691,32 +691,32 @@ export class InstanceConfig extends classes.Config<InstanceConfigFields> {
}; };
} }
export interface ControlConfigFields { export interface CtlConfigFields {
"control.controller_url": string | null; "ctl.controller_url": string | null;
"control.controller_token": string | null; "ctl.controller_token": string | null;
"control.max_reconnect_delay": number; "ctl.max_reconnect_delay": number;
} }
/** /**
* Control config class * Ctl config class
* @extends classes.Config * @extends classes.Config
*/ */
export class ControlConfig extends classes.Config<ControlConfigFields> { export class CtlConfig extends classes.Config<CtlConfigFields> {
declare static fromJSON: configFromJSON<ControlConfig>; declare static fromJSON: configFromJSON<CtlConfig>;
declare static fromFile: configFromFile<ControlConfig>; declare static fromFile: configFromFile<CtlConfig>;
static fieldDefinitions: classes.ConfigDefs<ControlConfigFields> = { static fieldDefinitions: classes.ConfigDefs<CtlConfigFields> = {
"control.controller_url": { "ctl.controller_url": {
description: "URL to connect to the controller at", description: "URL to connect to the controller at",
type: "string", type: "string",
optional: true, optional: true,
}, },
"control.controller_token": { "ctl.controller_token": {
access: ["control"], access: ["control"],
description: "Token to authenticate to controller with.", description: "Token to authenticate to controller with.",
type: "string", type: "string",
optional: true, optional: true,
}, },
"control.max_reconnect_delay": { "ctl.max_reconnect_delay": {
title: "Max Reconnect Delay", title: "Max Reconnect Delay",
description: "Maximum delay to wait before attempting to reconnect WebSocket", description: "Maximum delay to wait before attempting to reconnect WebSocket",
type: "number", type: "number",
+2 -2
View File
@@ -31,7 +31,7 @@ export type PluginDeclaration = {
ctlEntrypoint?: string; ctlEntrypoint?: string;
webEntrypoint?: string; webEntrypoint?: string;
controlConfigFields?: Record<string, FieldDefinition>; ctlConfigFields?: Record<string, FieldDefinition>;
features?: (typeof PluginFeatureFlags)[number][]; features?: (typeof PluginFeatureFlags)[number][];
@@ -53,7 +53,7 @@ export function pluginNeedsWebBuild(info: PluginDeclaration) {
|| info.controllerConfigFields || info.controllerConfigFields
|| info.hostConfigFields || info.hostConfigFields
|| info.instanceConfigFields || info.instanceConfigFields
|| info.controlConfigFields || info.ctlConfigFields
); );
} }
@@ -16,7 +16,7 @@ import { DraggingContext } from "../model/is_dragging";
import webUiPackage from "../../package.json"; import webUiPackage from "../../package.json";
import logo from "../images/logo.png"; import logo from "../images/logo.png";
import { ControlConfig } from "@clusterio/lib"; import { CtlConfig } from "@clusterio/lib";
type MenuItem = Required<MenuProps>["items"][number]; type MenuItem = Required<MenuProps>["items"][number];
@@ -77,11 +77,11 @@ export default function SiteLayout() {
if (key === "user") { if (key === "user") {
navigate(`/users/${account.name}/view`); navigate(`/users/${account.name}/view`);
} else if (key === "ctlConfig") { } else if (key === "ctlConfig") {
const config = new ControlConfig("control", { const config = new CtlConfig("control", {
"control.controller_token": control.connector.token, "ctl.controller_token": control.connector.token,
"control.controller_url": (new URL(webRoot, document.location.href)).href, "ctl.controller_url": (new URL(webRoot, document.location.href)).href,
}); });
saveJson("config-control.json", config.toJSON()); saveJson("config-ctl.json", config.toJSON());
} else if (key === "about") { } else if (key === "about") {
setAboutOpen(true); setAboutOpen(true);
} else if (key === "logOut") { } else if (key === "logOut") {
@@ -9,8 +9,8 @@ globalChatCommands.add(new Command({
definition: ["shout <message>", "Send message to all instances", (yargs) => { definition: ["shout <message>", "Send message to all instances", (yargs) => {
yargs.positional("message", { describe: "message to send", type: "string" }); yargs.positional("message", { describe: "message to send", type: "string" });
}], }],
handler: async function(args, control) { handler: async function(args, ctl) {
await control.sendTo("allInstances", new ChatEvent("Console", args.message)); await ctl.sendTo("allInstances", new ChatEvent("Console", args.message));
}, },
})); }));
+1 -1
View File
@@ -7,7 +7,7 @@ export const plugin: lib.PluginDeclaration = {
title: "Global Chat", title: "Global Chat",
description: "Forwards chat between instances.", description: "Forwards chat between instances.",
instanceEntrypoint: "dist/node/instance.js", instanceEntrypoint: "dist/node/instance.js",
ctlEntrypoint: "dist/node/control.js", ctlEntrypoint: "dist/node/ctl.js",
features: [ features: [
"ScriptCommands", "ScriptCommands",
@@ -8,7 +8,7 @@ testPluginCommands.add(new Command({
definition: ["echo <message>", "Print the message given to it", (yargs) => { definition: ["echo <message>", "Print the message given to it", (yargs) => {
yargs.positional("message", { describe: "message to print", type: "string" }); yargs.positional("message", { describe: "message to print", type: "string" });
}], }],
handler: async function(args, control) { handler: async function(args, ctl) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(args.message); console.log(args.message);
}, },
+1 -1
View File
@@ -11,7 +11,7 @@ export const plugin = {
controllerEntrypoint: "controller.js", controllerEntrypoint: "controller.js",
hostEntrypoint: "host.js", hostEntrypoint: "host.js",
instanceEntrypoint: "instance.js", instanceEntrypoint: "instance.js",
ctlEntrypoint: "control.js", ctlEntrypoint: "ctl.js",
messages: [ messages: [
ControllerEcho, ControllerEcho,
+5 -5
View File
@@ -200,7 +200,7 @@ export let factorioDir = getFactorioDir(baseHostConfig);
let pluginListPath = path.join("temp", "test", "plugin-list.json"); let pluginListPath = path.join("temp", "test", "plugin-list.json");
export let controllerConfigPath = path.join("temp", "test", "config-controller.json"); export let controllerConfigPath = path.join("temp", "test", "config-controller.json");
export let hostConfigPath = path.join("temp", "test", "config-host.json"); export let hostConfigPath = path.join("temp", "test", "config-host.json");
export let controlConfigPath = path.join("temp", "test", "config-control.json"); export let ctlConfigPath = path.join("temp", "test", "config-ctl.json");
function childOptions(options) { function childOptions(options) {
return { return {
@@ -241,7 +241,7 @@ export async function execCtl(command) {
return; return;
} }
control.config = initArgs.controlConfig; control.config = initArgs.ctlConfig;
const targetCommand = selectTargetCommand(initArgs.args, initArgs.rootCommands); const targetCommand = selectTargetCommand(initArgs.args, initArgs.rootCommands);
await targetCommand.run(initArgs.args, control); await targetCommand.run(initArgs.args, control);
} finally { } finally {
@@ -340,7 +340,7 @@ before(async function() {
await fs.rm(pluginListPath, { force: true }); await fs.rm(pluginListPath, { force: true });
await fs.rm(controllerConfigPath, { force: true }); await fs.rm(controllerConfigPath, { force: true });
await fs.rm(hostConfigPath, { force: true }); await fs.rm(hostConfigPath, { force: true });
await fs.rm(controlConfigPath, { force: true }); await fs.rm(ctlConfigPath, { force: true });
await fs.mkdir(path.join("temp", "test"), { recursive: true }); await fs.mkdir(path.join("temp", "test"), { recursive: true });
@@ -394,8 +394,8 @@ before(async function() {
control = new TestControl(controlConnector); control = new TestControl(controlConnector);
await controlConnector.connect(); await controlConnector.connect();
const initArgs = await initializeCtl(`--plugin-list ${pluginListPath} control-config list`, undefined, true); const initArgs = await initializeCtl(`--plugin-list ${pluginListPath} config list`, undefined, true);
control.config = initArgs.controlConfig; control.config = initArgs.ctlConfig;
control.hooks = initArgs.ctlHooks; control.hooks = initArgs.ctlHooks;
const testPack = lib.ModPack.fromJSON({}); const testPack = lib.ModPack.fromJSON({});
+1 -1
View File
@@ -42,7 +42,7 @@ describe("lib/config/definitions/migrations", function() {
assert.equal(configFalse.get("factorio.sync_banlist"), "disabled", "sync_adminlist contains wrong value"); assert.equal(configFalse.get("factorio.sync_banlist"), "disabled", "sync_adminlist contains wrong value");
}); });
}); });
describe("Control Config", function() { describe("Ctl Config", function() {
}); });
}); });
+2 -2
View File
@@ -1,7 +1,7 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as lib from "@clusterio/lib"; import * as lib from "@clusterio/lib";
const validators = lib.Config.validators; const validators = lib.Config.validators;
import { ControllerConfig, HostConfig, InstanceConfig, ControlConfig } from "@clusterio/lib"; import { ControllerConfig, HostConfig, InstanceConfig, CtlConfig } from "@clusterio/lib";
describe("lib/config/validators", function() { describe("lib/config/validators", function() {
describe("all", function() { describe("all", function() {
@@ -366,7 +366,7 @@ describe("lib/config/definitions/validators", function() {
}); });
}); });
describe("Control Config", function() { describe("Ctl Config", function() {
}); });
}); });
+1 -1
View File
@@ -18,7 +18,7 @@ describe("lib/plugin", function() {
name: "foo", title: "Foo", controllerEntrypoint: "controller.js", name: "foo", title: "Foo", controllerEntrypoint: "controller.js",
}), true); }), true);
for (const field of [ for (const field of [
"controllerConfigFields", "hostConfigFields", "instanceConfigFields", "controlConfigFields", "controllerConfigFields", "hostConfigFields", "instanceConfigFields", "ctlConfigFields",
]) { ]) {
assert.equal(lib.pluginNeedsWebBuild({ name: "foo", title: "Foo", [field]: {} }), true, field); assert.equal(lib.pluginNeedsWebBuild({ name: "foo", title: "Foo", [field]: {} }), true, field);
} }