mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-27 16:47:13 +09:00
Implement HostInfo as a class
Replace POJO definition of HostInfo with a class that properly manages its own serialisation to JSON.
This commit is contained in:
1 parent
20330bc2c3
commit
c248363895
6 files changed
+137
-60
No files matched your search
@@ -1,5 +1,4 @@
|
|||||||
import type WsServerConnector from "./WsServerConnector";
|
import type WsServerConnector from "./WsServerConnector";
|
||||||
import type { HostInfo } from "./HostConnection";
|
|
||||||
|
|
||||||
import events from "events";
|
import events from "events";
|
||||||
|
|
||||||
@@ -188,7 +187,7 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
throw new Error(`Unknown host id (${request.hostId})`);
|
throw new Error(`Unknown host id (${request.hostId})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
host.token_valid_after = Math.floor(Date.now() / 1000);
|
host.tokenValidAfter = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
const hostConnection = this._controller.wsServer.hostConnections.get(request.hostId);
|
const hostConnection = this._controller.wsServer.hostConnections.get(request.hostId);
|
||||||
if (hostConnection) {
|
if (hostConnection) {
|
||||||
@@ -199,19 +198,7 @@ export default class ControlConnection extends BaseConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async handleHostListRequest(): Promise<lib.HostDetails[]> {
|
async handleHostListRequest(): Promise<lib.HostDetails[]> {
|
||||||
let list = [];
|
return [...this._controller.hosts.values()].map(host => host.toHostDetails());
|
||||||
for (let host of this._controller.hosts.values()) {
|
|
||||||
list.push(new lib.HostDetails(
|
|
||||||
host.agent,
|
|
||||||
host.version,
|
|
||||||
host.name,
|
|
||||||
host.id,
|
|
||||||
this._controller.wsServer.hostConnections.has(host.id),
|
|
||||||
host.public_address,
|
|
||||||
host.token_valid_after,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return list;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleHostGenerateTokenRequest(message: lib.HostGenerateTokenRequest) {
|
async handleHostGenerateTokenRequest(message: lib.HostGenerateTokenRequest) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type winston from "winston";
|
|||||||
import type { AddressInfo } from "net";
|
import type { AddressInfo } from "net";
|
||||||
import type { ControllerArgs } from "../controller";
|
import type { ControllerArgs } from "../controller";
|
||||||
import express, { type Request, type Response, type NextFunction, type Application } from "express";
|
import express, { type Request, type Response, type NextFunction, type Application } from "express";
|
||||||
|
import type { Static } from "@sinclair/typebox";
|
||||||
|
|
||||||
import compression from "compression";
|
import compression from "compression";
|
||||||
import events, { EventEmitter } from "events";
|
import events, { EventEmitter } from "events";
|
||||||
@@ -22,7 +23,8 @@ import * as routes from "./routes";
|
|||||||
import ControllerUser from "./ControllerUser";
|
import ControllerUser from "./ControllerUser";
|
||||||
import UserManager from "./UserManager";
|
import UserManager from "./UserManager";
|
||||||
import WsServer from "./WsServer";
|
import WsServer from "./WsServer";
|
||||||
import HostConnection, { type HostInfo } from "./HostConnection";
|
import HostConnection from "./HostConnection";
|
||||||
|
import HostInfo from "./HostInfo";
|
||||||
import BaseControllerPlugin from "./BaseControllerPlugin";
|
import BaseControllerPlugin from "./BaseControllerPlugin";
|
||||||
|
|
||||||
const endpointDurationSummary = new Summary(
|
const endpointDurationSummary = new Summary(
|
||||||
@@ -439,7 +441,7 @@ export default class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static async loadHosts(filePath: string): Promise<Map<number, HostInfo>> {
|
static async loadHosts(filePath: string): Promise<Map<number, HostInfo>> {
|
||||||
let serialized: [number, HostInfo][];
|
let serialized: [number, Static<typeof HostInfo.jsonSchema>][];
|
||||||
try {
|
try {
|
||||||
serialized = JSON.parse(await fs.readFile(filePath, { encoding: "utf8" }));
|
serialized = JSON.parse(await fs.readFile(filePath, { encoding: "utf8" }));
|
||||||
|
|
||||||
@@ -450,12 +452,21 @@ export default class Controller {
|
|||||||
return new Map();
|
return new Map();
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Remove after release.
|
// TODO: migrate remove after release.
|
||||||
if (serialized.length && !(serialized[0] instanceof Array)) {
|
if (serialized.length && !(serialized[0] instanceof Array)) {
|
||||||
return new Map(); // Discard old format.
|
return new Map(); // Discard old format.
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Map(serialized);
|
const hosts = new Map();
|
||||||
|
for (let [id, json] of serialized) {
|
||||||
|
const host = HostInfo.fromJSON(json);
|
||||||
|
if (host.connected) {
|
||||||
|
host.connected = false;
|
||||||
|
host.updatedAt = Date.now();
|
||||||
|
}
|
||||||
|
hosts.set(id, host);
|
||||||
|
}
|
||||||
|
return hosts;
|
||||||
}
|
}
|
||||||
|
|
||||||
static async saveHosts(filePath: string, hosts: Map<number, HostInfo>) {
|
static async saveHosts(filePath: string, hosts: Map<number, HostInfo>) {
|
||||||
@@ -608,16 +619,12 @@ export default class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
hostsUpdated(hosts: HostInfo[]) {
|
hostsUpdated(hosts: HostInfo[]) {
|
||||||
let updates = hosts.map(host => new lib.HostDetails(
|
const now = Date.now();
|
||||||
host.agent,
|
for (const host of hosts) {
|
||||||
host.version,
|
host.updatedAt = now;
|
||||||
host.name,
|
}
|
||||||
host.id,
|
this.hostsDirty = true;
|
||||||
this.wsServer.hostConnections.has(host.id),
|
let updates = hosts.map(host => host.toHostDetails());
|
||||||
host.public_address,
|
|
||||||
host.token_valid_after,
|
|
||||||
));
|
|
||||||
|
|
||||||
this.subscriptions.broadcast(new lib.HostUpdatesEvent(updates));
|
this.subscriptions.broadcast(new lib.HostUpdatesEvent(updates));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,18 +6,9 @@ const { logger } = lib;
|
|||||||
|
|
||||||
import BaseConnection from "./BaseConnection";
|
import BaseConnection from "./BaseConnection";
|
||||||
import InstanceInfo, { InstanceStatus } from "./InstanceInfo";
|
import InstanceInfo, { InstanceStatus } from "./InstanceInfo";
|
||||||
|
import HostInfo from "./HostInfo";
|
||||||
|
|
||||||
|
|
||||||
export interface HostInfo {
|
|
||||||
agent: string;
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
version: string;
|
|
||||||
plugins: Record<string, string>;
|
|
||||||
public_address: string | undefined;
|
|
||||||
token_valid_after?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents the connection to a host
|
* Represents the connection to a host
|
||||||
*
|
*
|
||||||
@@ -25,10 +16,10 @@ export interface HostInfo {
|
|||||||
* @alias module:controller/src/HostConnection
|
* @alias module:controller/src/HostConnection
|
||||||
*/
|
*/
|
||||||
export default class HostConnection extends BaseConnection {
|
export default class HostConnection extends BaseConnection {
|
||||||
private _agent: any;
|
private _agent: string;
|
||||||
private _id: any;
|
private _id: number;
|
||||||
private _name: any;
|
private _name: string;
|
||||||
private _version: any;
|
private _version: string;
|
||||||
plugins: Map<string, string>;
|
plugins: Map<string, string>;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@@ -45,18 +36,21 @@ export default class HostConnection extends BaseConnection {
|
|||||||
this.plugins = new Map(Object.entries(registerData.plugins));
|
this.plugins = new Map(Object.entries(registerData.plugins));
|
||||||
this._checkPluginVersions();
|
this._checkPluginVersions();
|
||||||
|
|
||||||
let currentHostInfo = this._controller.hosts.get(this._id);
|
const previousHostInfo = this._controller.hosts.get(this._id);
|
||||||
|
const currentHostInfo = new HostInfo(
|
||||||
this._controller.hosts.set(this._id, {
|
this._agent,
|
||||||
agent: this._agent,
|
this._id,
|
||||||
id: this._id,
|
this._name,
|
||||||
name: this._name,
|
this._version,
|
||||||
version: this._version,
|
this.plugins,
|
||||||
public_address: registerData.publicAddress,
|
true,
|
||||||
plugins: registerData.plugins,
|
registerData.publicAddress ?? "",
|
||||||
token_valid_after: currentHostInfo?.token_valid_after,
|
previousHostInfo?.tokenValidAfter,
|
||||||
});
|
Date.now(),
|
||||||
this._controller.hostsDirty = true;
|
false,
|
||||||
|
);
|
||||||
|
this._controller.hosts.set(this._id, currentHostInfo);
|
||||||
|
this._controller.hostsUpdated([currentHostInfo]);
|
||||||
|
|
||||||
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
for (let event of ["connect", "drop", "resume", "close"] as const) {
|
||||||
// eslint-disable-next-line no-loop-func
|
// eslint-disable-next-line no-loop-func
|
||||||
@@ -81,6 +75,9 @@ export default class HostConnection extends BaseConnection {
|
|||||||
lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
lib.invokeHook(this._controller.plugins, "onInstanceStatusChanged", instance, prev);
|
||||||
}
|
}
|
||||||
this._controller.instanceDetailsUpdated(instances);
|
this._controller.instanceDetailsUpdated(instances);
|
||||||
|
|
||||||
|
currentHostInfo.connected = false;
|
||||||
|
this._controller.hostsUpdated([currentHostInfo]);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.handle(lib.InstanceStatusChangedEvent, this.handleInstanceStatusChangedEvent.bind(this));
|
this.handle(lib.InstanceStatusChangedEvent, this.handleInstanceStatusChangedEvent.bind(this));
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { Type, Static } from "@sinclair/typebox";
|
||||||
|
import { HostDetails } from "@clusterio/lib";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Info about a host known to the controller.
|
||||||
|
*/
|
||||||
|
export default class HostInfo {
|
||||||
|
constructor(
|
||||||
|
/** Agent this host last connected with */
|
||||||
|
public agent: string,
|
||||||
|
/** Id of this host */
|
||||||
|
public id: number,
|
||||||
|
/** Version this host last connected with */
|
||||||
|
public name: string,
|
||||||
|
/** Version this host last connected with */
|
||||||
|
public version: string,
|
||||||
|
/** Plugins this host last connected with */
|
||||||
|
public plugins: Map<string, string>,
|
||||||
|
/** True if this host is currently connected to controller */
|
||||||
|
public connected: boolean = false,
|
||||||
|
/** Value of host.public_address configured for this host */
|
||||||
|
public publicAddress: string = "",
|
||||||
|
/** Unix timestamp in seconds host token must be issued afterto be valid */
|
||||||
|
public tokenValidAfter: number = 0,
|
||||||
|
/** Millisecond Unix timestamp this entry was last updated at */
|
||||||
|
public updatedAt: number = 0,
|
||||||
|
/** True if this host has been deleted */
|
||||||
|
public isDeleted: boolean = false,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
static jsonSchema = Type.Object({
|
||||||
|
"agent": Type.String(),
|
||||||
|
"id": Type.Number(),
|
||||||
|
"name": Type.String(),
|
||||||
|
"version": Type.String(),
|
||||||
|
"plugins": Type.Record(Type.String(), Type.String()),
|
||||||
|
"connected": Type.Boolean(),
|
||||||
|
"public_address": Type.String(),
|
||||||
|
"token_valid_after": Type.Number(),
|
||||||
|
"updated_at": Type.Number(),
|
||||||
|
"is_deleted": Type.Boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||||
|
return new this(
|
||||||
|
json.agent,
|
||||||
|
json.id,
|
||||||
|
json.name,
|
||||||
|
json.version,
|
||||||
|
new Map(Object.entries(json.plugins)),
|
||||||
|
json.connected,
|
||||||
|
json.public_address,
|
||||||
|
json.token_valid_after,
|
||||||
|
json.updated_at,
|
||||||
|
json.is_deleted,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJSON(): Static<typeof HostInfo.jsonSchema> {
|
||||||
|
return {
|
||||||
|
agent: this.agent,
|
||||||
|
id: this.id,
|
||||||
|
name: this.name,
|
||||||
|
version: this.version,
|
||||||
|
plugins: Object.fromEntries(this.plugins),
|
||||||
|
connected: this.connected,
|
||||||
|
public_address: this.publicAddress,
|
||||||
|
token_valid_after: this.tokenValidAfter,
|
||||||
|
updated_at: this.updatedAt,
|
||||||
|
is_deleted: this.isDeleted,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toHostDetails() {
|
||||||
|
return new HostDetails(
|
||||||
|
this.agent,
|
||||||
|
this.version,
|
||||||
|
this.name,
|
||||||
|
this.id,
|
||||||
|
this.connected,
|
||||||
|
this.publicAddress,
|
||||||
|
this.tokenValidAfter,
|
||||||
|
this.updatedAt,
|
||||||
|
this.isDeleted,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ import * as lib from "@clusterio/lib";
|
|||||||
const { logger } = lib;
|
const { logger } = lib;
|
||||||
|
|
||||||
import ControlConnection from "./ControlConnection";
|
import ControlConnection from "./ControlConnection";
|
||||||
import HostConnection, { HostInfo } from "./HostConnection";
|
import HostConnection from "./HostConnection";
|
||||||
import WsServerConnector from "./WsServerConnector";
|
import WsServerConnector from "./WsServerConnector";
|
||||||
|
|
||||||
import { version as packageVersion } from "../package.json";
|
import { version as packageVersion } from "../package.json";
|
||||||
@@ -243,7 +243,7 @@ ${err.stack}`
|
|||||||
}
|
}
|
||||||
|
|
||||||
let host = this.controller.hosts.get(data.id);
|
let host = this.controller.hosts.get(data.id);
|
||||||
if (!tokenPayload.iat || tokenPayload.iat < (host?.token_valid_after??0)) {
|
if (!tokenPayload.iat || tokenPayload.iat < (host?.tokenValidAfter ?? 0)) {
|
||||||
throw new Error("invalid token");
|
throw new Error("invalid token");
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
@@ -274,13 +274,11 @@ ${err.stack}`
|
|||||||
connector.on("close", () => {
|
connector.on("close", () => {
|
||||||
if (this.hostConnections.get(data.id) === connection) {
|
if (this.hostConnections.get(data.id) === connection) {
|
||||||
this.hostConnections.delete(data.id);
|
this.hostConnections.delete(data.id);
|
||||||
this.controller.hostsUpdated([this.controller.hosts.get(data.id)!]);
|
|
||||||
} else {
|
} else {
|
||||||
logger.warn("Unlisted HostConnection closed");
|
logger.warn("Unlisted HostConnection closed");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.hostConnections.set(data.id, connection);
|
this.hostConnections.set(data.id, connection);
|
||||||
this.controller.hostsUpdated([this.controller.hosts.get(data.id)!]);
|
|
||||||
let src = new lib.Address(lib.Address.host, data.id);
|
let src = new lib.Address(lib.Address.host, data.id);
|
||||||
connector.ready(socket, src, sessionToken, undefined);
|
connector.ready(socket, src, sessionToken, undefined);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -152,7 +152,7 @@ function validateHostToken(req: Request, res: Response, next: any) {
|
|||||||
if (!host) {
|
if (!host) {
|
||||||
throw new Error("invalid host");
|
throw new Error("invalid host");
|
||||||
}
|
}
|
||||||
if (!tokenPayload.iat || tokenPayload.iat < (host.token_valid_after??0)) {
|
if (!tokenPayload.iat || tokenPayload.iat < (host.tokenValidAfter ?? 0)) {
|
||||||
throw new Error("invalid token");
|
throw new Error("invalid token");
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
Reference in new issue
Block a user