Merge pull request #758 from Cooldude2606/feature/pending-restart

Add indicators for host version mismatch and required restart
This commit is contained in:
Daniel authored and GitHub committed 2025-05-11 14:14:39 +02:00
commit 0adb45bba4
14 files changed
+248 -79

No files matched your search

+2
View File
@@ -361,6 +361,8 @@ async function initialize(): Promise<InitializeParameters> {
}
}
controllerConfig.set("controller.version", version); // Allows tracking last loaded version
if (!controllerConfig.get("controller.auth_secret")) {
logger.info("Generating new controller authentication secret");
let asyncRandomBytes = util.promisify(crypto.randomBytes);
+13 -1
View File
@@ -528,7 +528,19 @@ export default class Controller {
}
requests.push(hostConnection.send(new lib.SystemInfoRequest()));
}
requests.push(lib.gatherSystemInfo("controller", this.canRestart));
if (!this.config.restartRequired) {
// If a restart isn't already required, then test if a new version is installed
try {
const runningVersion = this.config.get("controller.version");
const packageJson = await fs.readJSON(path.join(__dirname, "..", "package.json"));
if (runningVersion !== packageJson.version) {
this.config.restartRequired = true;
}
} catch (err: any) {
logger.warn(`Failed to read package json:\n${err.stack ?? err.message}`);
}
}
requests.push(lib.gatherSystemInfo("controller", this.canRestart, this.config.restartRequired));
const newMetrics = await Promise.all(requests);
for (const metric of newMetrics) {
this.systems.set(metric);
+2 -1
View File
@@ -183,13 +183,14 @@ async function startHost() {
}
}
hostConfig.set("host.version", version); // Allows tracking last loaded version
if (command === "config") {
await lib.handleConfigCommand(args, hostConfig, args.config);
return;
}
// If we get here the command was run
await fs.ensureDir(hostConfig.get("host.instances_directory"));
await fs.ensureDir(hostConfig.get("host.mods_directory"));
await fs.ensureDir("modules");
+13 -1
View File
@@ -808,7 +808,19 @@ export default class Host extends lib.Link {
}
async handleSystemInfoRequest() {
return lib.gatherSystemInfo(this.config.get("host.id"), this.canRestart);
if (!this.config.restartRequired) {
// If a restart isn't already required, then test if a new version is installed
try {
const runningVersion = this.config.get("host.version");
const packageJson = await fs.readJSON(path.join(__dirname, "..", "package.json"));
if (runningVersion !== packageJson.version) {
this.config.restartRequired = true;
}
} catch (err: any) {
logger.warn(`Failed to read package json:\n${err.stack ?? err.message}`);
}
}
return lib.gatherSystemInfo(this.config.get("host.id"), this.canRestart, this.config.restartRequired);
}
async handleHostMetricsRequest() {
+27 -17
View File
@@ -203,6 +203,8 @@ export class Config<
/** Set to true when a field in the config is changed. */
dirty = false;
/** Set to true when a 'restart required' field in the config is changed. */
restartRequired = false;
/**
* Create a new instance of the given config
@@ -272,6 +274,27 @@ export class Config<
return true;
}
/**
* Set the value of a field, while also settings the required flags and events.
* This method does not perform any validation on the value being set
*
* @param name - Name of the field to set
* @param value - The new value of the field
* @param notify - False to skip setting dirty flags and emitting events
*/
_set(name: keyof Fields & string, value: FieldValue, notify: boolean = true) {
const prev = this.fields[name];
this.fields[name] = value as any;
if (notify && !isDeepStrictEqual(value, prev)) {
const def = this.constructor.fieldDefinitions[name];
if (def.restartRequired) {
this.restartRequired = true;
}
this.dirty = true;
this.emit("fieldChanged", name, value, prev);
}
}
static jsonSchema = ConfigSchema;
static validate = libSchema.compile(this.jsonSchema as any);
@@ -391,12 +414,7 @@ export class Config<
continue;
}
let prev = this.fields[name];
this.fields[name] = value as any;
if (notify && !isDeepStrictEqual(value, prev)) {
this.dirty = true;
this.emit("fieldChanged", name, value, prev);
}
this._set(name, value, notify);
}
}
@@ -511,12 +529,7 @@ export class Config<
throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`);
}
let prev = this.fields[name];
this.fields[name] = value as Fields[Field];
if (!isDeepStrictEqual(value, prev)) {
this.dirty = true;
this.emit("fieldChanged", name, value, prev);
}
this._set(name, value);
}
/**
@@ -559,10 +572,7 @@ export class Config<
} else {
delete updated[prop];
}
this.fields[name] = updated as Fields[Field];
if (!isDeepStrictEqual(updated, prev)) {
this.dirty = true;
this.emit("fieldChanged", name, updated, prev);
}
this._set(name, updated);
}
}
+14
View File
@@ -4,6 +4,7 @@ import type { PluginNodeEnvInfo, PluginWebpackEnvInfo } from "../plugin";
import { Static } from "@sinclair/typebox";
export interface ControllerConfigFields {
"controller.version": string;
"controller.name": string;
"controller.mods_directory": string;
"controller.database_directory": string;
@@ -46,6 +47,12 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
}
static fieldDefinitions: classes.ConfigDefs<ControllerConfigFields> = {
"controller.version": {
type: "string",
initialValue: "", // Set on start
readonly: ["controller"],
hidden: true,
},
"controller.name": {
title: "Name",
description: "Name of the cluster.",
@@ -215,6 +222,7 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
}
export interface HostConfigFields {
"host.version": string;
"host.name": string;
"host.id": number;
"host.factorio_directory": string;
@@ -237,6 +245,12 @@ export interface HostConfigFields {
export class HostConfig extends classes.Config<HostConfigFields> {
declare static fromJSON: (json: classes.ConfigSchema, location: classes.ConfigLocation) => HostConfig;
static fieldDefinitions: classes.ConfigDefs<HostConfigFields> = {
"host.version": {
type: "string",
initialValue: "", // Set on start
readonly: ["host"],
hidden: true,
},
"host.name": {
description: "Name of the host",
type: "string",
@@ -250,6 +250,7 @@ export class SystemInfo {
public diskCapacity: number,
public diskAvailable: number,
public canRestart: boolean,
public restartRequired: boolean,
/** Millisecond Unix timestamp this entry was last updated at */
public updatedAtMs: number,
public isDeleted: boolean,
@@ -268,6 +269,7 @@ export class SystemInfo {
"diskCapacity": Type.Number(),
"diskAvailable": Type.Number(),
"canRestart": Type.Boolean(),
"restartRequired": Type.Boolean(),
"updatedAtMs": Type.Number(),
"isDeleted": Type.Boolean(),
});
@@ -286,6 +288,7 @@ export class SystemInfo {
json.diskCapacity,
json.diskAvailable,
json.canRestart,
json.restartRequired,
json.updatedAtMs,
json.isDeleted,
);
+2 -1
View File
@@ -134,7 +134,7 @@ function minZip<T>(a: T[], b: T[]): [T, T][] {
let previousTotalCpuMs: number[] = [];
let previousIdleCpuMs: number[] = [];
export async function gatherSystemInfo(id: SystemInfo["id"], canRestart: boolean) {
export async function gatherSystemInfo(id: SystemInfo["id"], canRestart: boolean, restartRequired: boolean) {
const cpus = os.cpus();
const currentTotalCpuMs = cpus.map(({ times }) => times.user + times.idle + times.irq + times.nice + times.sys);
const currentIdleCpuMs = cpus.map(({ times }) => times.idle);
@@ -165,6 +165,7 @@ export async function gatherSystemInfo(id: SystemInfo["id"], canRestart: boolean
diskCapacity,
diskAvailable,
canRestart,
restartRequired,
Date.now(),
false,
);
@@ -1,5 +1,6 @@
import React, {useContext, useState} from "react";
import { Button, Descriptions, Flex, Popconfirm, Space, Typography } from "antd";
import { Button, Descriptions, Flex, Popconfirm, Space, Tooltip, Typography } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import * as lib from "@clusterio/lib";
@@ -54,16 +55,20 @@ export default function ControllerPage() {
}
{
account.hasPermission("core.controller.restart")
&& <Button
disabled={system?.canRestart === false}
onClick={() => {
control.send(
new lib.ControllerRestartRequest()
).catch(notifyErrorHandler("Error restarting controller"));
}}
>
Restart
</Button>
&& <Tooltip title={system?.restartRequired ? "Restart Required" : null}>
<Button
disabled={system?.canRestart === false}
onClick={() => {
control.send(
new lib.ControllerRestartRequest()
).catch(notifyErrorHandler("Error restarting controller"));
}}
>
Restart
{!system?.restartRequired ? undefined
: <ExclamationCircleOutlined style={{ color: "yellow" }}/>}
</Button>
</Tooltip>
}
</Space>}
/>
+17 -12
View File
@@ -1,5 +1,6 @@
import React, { useContext, useState } from "react";
import { Descriptions, Spin, Tag, Typography, Button, Space, Modal, Popconfirm, Flex } from "antd";
import { Descriptions, Spin, Tag, Typography, Button, Space, Modal, Popconfirm, Flex, Tooltip } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { useParams } from "react-router-dom";
import * as lib from "@clusterio/lib";
@@ -89,17 +90,21 @@ export default function HostViewPage() {
}
{
account.hasPermission("core.host.restart")
&& <Button
disabled={system?.canRestart === false}
onClick={() => {
control.sendTo(
{ hostId },
new lib.HostRestartRequest()
).catch(notifyErrorHandler("Error restarting host"));
}}
>
Restart
</Button>
&& <Tooltip title={system?.restartRequired ? "Restart Required" : null}>
<Button
disabled={system?.canRestart === false}
onClick={() => {
control.sendTo(
{ hostId },
new lib.HostRestartRequest()
).catch(notifyErrorHandler("Error restarting host"));
}}
>
Restart
{!system?.restartRequired ? undefined
: <ExclamationCircleOutlined style={{ color: "yellow" }} />}
</Button>
</Tooltip>
}
</Space>;
+18 -7
View File
@@ -1,10 +1,11 @@
import React, { useContext, useRef, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Flex, Form, InputNumber, Modal, Progress, Switch, Table, Tag, Typography } from "antd";
import CopyOutlined from "@ant-design/icons/lib/icons/CopyOutlined";
import { Button, Flex, Form, InputNumber, Modal, Progress, Space, Switch, Table, Tag, Tooltip, Typography } from "antd";
import { ExclamationCircleOutlined, CopyOutlined } from "@ant-design/icons";
import * as lib from "@clusterio/lib";
import webUiPackage from "../../package.json";
import { useAccount } from "../model/account";
import ControlContext from "./ControlContext";
import PageHeader from "./PageHeader";
@@ -13,6 +14,7 @@ import PluginExtra from "./PluginExtra";
import {
MetricCpuRatio, MetricCpuUsed, MetricMemoryRatio, MetricMemoryUsed,
MetricDiskUsed, MetricDiskRatio,
RestartRequired,
} from "./system_metrics";
import { useHosts } from "../model/host";
import { useSystems } from "../model/system";
@@ -268,6 +270,12 @@ export default function HostsPage() {
{
title: "Version",
dataIndex: "version",
render: (_, host) => <Space>
{host.version}
{webUiPackage.version === host.version ? undefined : <Tooltip title="Version Mismatch">
<ExclamationCircleOutlined style={{ color: "yellow" }}/>
</Tooltip>}
</Space>,
sorter: (a, b) => strcmp(a.version, b.version),
},
{
@@ -278,11 +286,14 @@ export default function HostsPage() {
{
title: "Connected",
key: "connected",
render: (_, host) => <Tag
color={host.connected ? "#389e0d" : "#cf1322"}
>
{host.connected ? "Connected" : "Disconnected"}
</Tag>,
render: (_, host) => <>
<Tag
color={host.connected ? "#389e0d" : "#cf1322"}
>
{host.connected ? "Connected" : "Disconnected"}
</Tag>
<RestartRequired system={systems.get(host.id)}/>
</>,
sorter: (a, b) => Number(a.connected) - Number(b.connected),
},
]}
@@ -1,7 +1,8 @@
import React from "react";
import * as lib from "@clusterio/lib";
import { Progress } from "antd";
import { Progress, Tooltip } from "antd";
import { ReloadOutlined } from "@ant-design/icons";
export function MetricCpuRatio(props: { system?: lib.SystemInfo }) {
if (!props.system) {
@@ -53,3 +54,12 @@ export function MetricDiskUsed(props: { system?: lib.SystemInfo }) {
const capacity = lib.formatBytes(props.system.diskCapacity);
return `${used} / ${capacity}`;
}
export function RestartRequired(props: { system?: lib.SystemInfo }) {
if (!props.system || !props.system.restartRequired) {
return "";
}
return <Tooltip title="Restart Required">
<ReloadOutlined style={{ color: "yellow" }}/>
</Tooltip>;
}
+109 -27
View File
@@ -33,6 +33,7 @@ describe("lib/config/classes", function() {
"test.func": { type: "number", initialValue: () => 42 },
"test.bool": { type: "boolean", initialValue: false, optional: true },
"test.json": { type: "object", initialValue: {}, optional: true },
"test.rest": { type: "object", initialValue: {}, optional: true, restartRequired: true },
"test.priv": { access: ["local"], type: "string", optional: true },
"test.cred": { credential: ["local"] },
"test.rdo": { readonly: ["local"] },
@@ -88,6 +89,7 @@ describe("lib/config/classes", function() {
"test.func": 42,
"test.bool": false,
"test.json": {},
"test.rest": {},
"test.priv": null,
"test.cred": null,
"test.rdo": null,
@@ -106,6 +108,7 @@ describe("lib/config/classes", function() {
"test.func": 42,
"test.bool": false,
"test.json": {},
"test.rest": {},
"test.rdo": null,
});
});
@@ -167,6 +170,7 @@ describe("lib/config/classes", function() {
"test.func": 50,
"test.bool": false,
"test.json": {},
"test.rest": {},
"test.priv": null,
"test.cred": null,
"test.rdo": null,
@@ -202,6 +206,7 @@ describe("lib/config/classes", function() {
"test.enum": "b",
"test.func": 42,
"test.json": {},
"test.rest": {},
"test.priv": null,
"test.cred": null,
"test.rdo": null,
@@ -246,6 +251,74 @@ describe("lib/config/classes", function() {
new Error("Invalid config")
);
});
it("should notify fieldChanged listeners", function() {
const testInstance = new TestConfig("local");
const changes = [];
testInstance.on("fieldChanged", (name, value, prev) => changes.push([name, value, prev]));
testInstance.update({
"extra.blah": true,
"alpha.foo": "baz",
"beta.bar": { value: 30 },
}, false);
assert.deepEqual(changes, [], "fieldChanged emitted when notify was false");
testInstance.update({
"extra.blah": false,
"alpha.foo": "bam",
"beta.bar": { value: 45 },
}, true);
assert.deepEqual(changes, [
["alpha.foo", "bam", "baz"],
["beta.bar", { value: 45 }, { value: 30 }],
], "fieldChanged emitted incorrectly");
});
it("should set the dirty flag", function() {
const testInstance = new TestConfig("local");
testInstance.update({
"extra.blah": true,
"alpha.foo": "baz",
"beta.bar": { value: 30 },
}, false);
assert.deepEqual(testInstance.dirty, false, "dirty flag set when notify was false");
testInstance.update({
"extra.blah": false,
"alpha.foo": "bam",
"beta.bar": { value: 45 },
}, true);
assert.deepEqual(testInstance.dirty, true, "dirty flag not set when notify was true");
});
it("should set the requires restart flag", function() {
const testInstance = new TestConfig("local");
testInstance.update({
"test.enum": "a",
"alpha.foo": "baz",
"beta.bar": { value: 30 },
}, false);
assert.deepEqual(testInstance.restartRequired, false, "restart required set when notify was false");
testInstance.update({
"alpha.foo": "bam",
"beta.bar": { value: 45 },
}, true);
assert.deepEqual(testInstance.restartRequired, false, "restart required when no restart field changed");
testInstance.update({
"test.enum": "b",
}, true);
assert.deepEqual(testInstance.restartRequired, true, "restart required not set when notify was true");
});
});
describe(".canAccess()", function() {
@@ -467,6 +540,26 @@ describe("lib/config/classes", function() {
new lib.InvalidValue(`Error parsing value for test.json: ${errMsg}`)
);
});
it("should notify fieldChanged listeners", function() {
const changes = [];
testInstance.on("fieldChanged", (name, value, prev) => changes.push([name, value, prev]));
testInstance.set("test.test", "foo");
assert.deepEqual(changes, [
["test.test", "foo", "blah"],
], "fieldChanged emitted incorrectly");
});
it("should set the dirty flag", function() {
testInstance.set("test.test", "foo");
assert.deepEqual(testInstance.dirty, true, "dirty flag not set");
});
it("should set the requires restart flag", function() {
testInstance.set("test.test", "foo");
assert.deepEqual(testInstance.restartRequired, false, "restart required when no restart field changed");
testInstance.set("test.enum", "b");
assert.deepEqual(testInstance.restartRequired, true, "restart required not set");
});
});
describe(".setProp()", function() {
@@ -524,36 +617,25 @@ describe("lib/config/classes", function() {
testInstance.setProp("test.json", "extra", undefined);
assert.deepEqual(testInstance.get("test.json"), { test: true });
});
});
it("should notify fieldChanged listeners", function() {
const changes = [];
testInstance.on("fieldChanged", (name, value, prev) => changes.push([name, value, prev]));
describe("fieldChanged event", function() {
let testInstance;
let called;
beforeEach(function() {
testInstance = new TestConfig("local");
called = false;
testInstance.once("fieldChanged", (field, curr, prev) => {
if (field === "beta.bar") {
called = true;
}
});
testInstance.setProp("test.json", "test", true);
assert.deepEqual(changes, [
["test.json", { test: true }, {}],
], "fieldChanged emitted incorrectly");
});
it("should be called when setting a field", function() {
testInstance.set("beta.bar", { value: 1 });
assert(called, "fieldChanged was not called");
it("should set the dirty flag", function() {
testInstance.setProp("test.json", "test", true);
assert.deepEqual(testInstance.dirty, true, "dirty flag not set");
});
it("should be called when updating a config", function() {
testInstance.update({
"beta.bar": { value: 1 },
}, true);
assert(called, "fieldChanged was not called");
});
it("should be called when setting a prop", function() {
testInstance.setProp("beta.bar", "value", 2);
assert(called, "fieldChanged was not called");
it("should set the requires restart flag", function() {
testInstance.setProp("test.json", "test", true);
assert.deepEqual(testInstance.restartRequired, false, "restart required when no restart field changed");
testInstance.setProp("test.rest", "test", true);
assert.deepEqual(testInstance.restartRequired, true, "restart required not set");
});
});
});
+1
View File
@@ -21,6 +21,7 @@ describe("lib/data/SystemInfo", function() {
2048,
512,
false,
false,
0,
false
);