diff --git a/packages/controller/src/Controller.ts b/packages/controller/src/Controller.ts index 7c366a73..de0305e4 100644 --- a/packages/controller/src/Controller.ts +++ b/packages/controller/src/Controller.ts @@ -96,6 +96,7 @@ export default class Controller { devMiddleware: any | null = null; + startedAtMs = Date.now(); autosaveInterval?: ReturnType; systemMetricsInterval?: ReturnType; @@ -397,6 +398,7 @@ export default class Controller { this.onSystemMetricsIntervalChanged(); logger.info("Started controller"); + this.startedAtMs = Date.now(); this._state = "running"; } @@ -553,7 +555,7 @@ export default class Controller { requests.push(hostConnection.send(new lib.SystemInfoRequest())); } const restartRequired = await this.checkRestartRequired(); - requests.push(lib.gatherSystemInfo("controller", this.canRestart, restartRequired)); + requests.push(lib.gatherSystemInfo("controller", this.canRestart, restartRequired, this.startedAtMs)); const newMetrics = await Promise.all(requests); for (const metric of newMetrics) { this.systems.set(metric); @@ -663,6 +665,12 @@ export default class Controller { if (!json.restartRequired) { // Added in 2.0.0.alpha.21 json.restartRequired = false; } + if (!json.systemStartedAtMs) { // Added in 2.0.0.alpha.23 + json.systemStartedAtMs = Date.now(); + } + if (!json.processStartedAtMs) { // Added in 2.0.0.alpha.23 + json.processStartedAtMs = Date.now(); + } return json; }); } diff --git a/packages/controller/src/HostConnection.ts b/packages/controller/src/HostConnection.ts index ac23de34..c50c5f3d 100644 --- a/packages/controller/src/HostConnection.ts +++ b/packages/controller/src/HostConnection.ts @@ -207,6 +207,11 @@ export default class HostConnection extends BaseConnection { let prev = instance.status; instance.status = request.status; + // If the instance has transitioned to running then updated the started at time + if (request.status === "running" && prev === "starting") { + instance.startedAtMs = Date.now(); + } + instance.gamePort = request.gamePort; instance.factorioVersion = request.factorioVersion; this._controller.instances.set(instance); @@ -246,6 +251,9 @@ export default class HostConnection extends BaseConnection { controllerInstance.status = instanceData.status; controllerInstance.gamePort = instanceData.gamePort; controllerInstance.factorioVersion = instanceData.factorioVersion; + if (instanceData.status === "running" && prev === "starting") { + controllerInstance.startedAtMs = Date.now(); + } instanceUpdates.push(controllerInstance); logger.verbose(`Instance ${instanceConfig.get("instance.name")} State: ${instanceData.status}`); await lib.invokeHook( @@ -261,6 +269,7 @@ export default class HostConnection extends BaseConnection { instanceData.status, instanceData.gamePort, instanceData.factorioVersion, + 0, Date.now(), ); instanceUpdates.push(newInstance); diff --git a/packages/controller/src/InstanceInfo.ts b/packages/controller/src/InstanceInfo.ts index 05d63596..836ad472 100644 --- a/packages/controller/src/InstanceInfo.ts +++ b/packages/controller/src/InstanceInfo.ts @@ -12,6 +12,7 @@ export default class InstanceInfo { public status: lib.InstanceStatus, public gamePort?: number, public factorioVersion?: lib.TargetVersion, + public startedAtMs = 0, public updatedAtMs = 0, ) { this.config = config; @@ -22,6 +23,7 @@ export default class InstanceInfo { "config": lib.InstanceConfig.jsonSchema, "status": lib.InstanceStatus, "gamePort": Type.Optional(Type.Number()), + "startedAtMs": Type.Optional(Type.Number()), "updatedAtMs": Type.Optional(Type.Number()), "factorioVersion": Type.Optional(lib.TargetVersionSchema), }); @@ -32,6 +34,7 @@ export default class InstanceInfo { json.status, json.gamePort, json.factorioVersion, + json.startedAtMs, json.updatedAtMs, ); } @@ -44,6 +47,7 @@ export default class InstanceInfo { this.gamePort, this.status, this.factorioVersion, + this.startedAtMs, this.updatedAtMs, this.config.get("instance.exclude_from_start_all"), ); diff --git a/packages/host/host.ts b/packages/host/host.ts index c3f539a5..19127713 100755 --- a/packages/host/host.ts +++ b/packages/host/host.ts @@ -291,6 +291,7 @@ async function startHost() { }); await hostConnector.connect(); + host.startedAtMs = Date.now(); logger.info("Started host"); } diff --git a/packages/host/src/Host.ts b/packages/host/src/Host.ts index f3061f29..b3bc909b 100644 --- a/packages/host/src/Host.ts +++ b/packages/host/src/Host.ts @@ -278,6 +278,8 @@ export default class Host extends lib.Link { _disconnecting = false; _shuttingDown = false; + startedAtMs = Date.now(); + static instanceConfigWarning = { "_warning": "Changes to this file will be overwritten by the controller's copy.", }; @@ -807,7 +809,7 @@ export default class Host extends lib.Link { async handleSystemInfoRequest() { const restartRequired = await this.checkRestartRequired(); - return lib.gatherSystemInfo(this.config.get("host.id"), this.canRestart, restartRequired); + return lib.gatherSystemInfo(this.config.get("host.id"), this.canRestart, restartRequired, this.startedAtMs); } async checkRestartRequired() { diff --git a/packages/lib/src/data/messages_controller.ts b/packages/lib/src/data/messages_controller.ts index aa4232a5..53c48e74 100644 --- a/packages/lib/src/data/messages_controller.ts +++ b/packages/lib/src/data/messages_controller.ts @@ -260,6 +260,8 @@ export class SystemInfo { public diskAvailable: number, public canRestart: boolean, public restartRequired: boolean, + public systemStartedAtMs: number, + public processStartedAtMs: number, /** Millisecond Unix timestamp this entry was last updated at */ public updatedAtMs: number, public isDeleted: boolean, @@ -279,6 +281,8 @@ export class SystemInfo { "diskAvailable": Type.Number(), "canRestart": Type.Boolean(), "restartRequired": Type.Boolean(), + "systemStartedAtMs": Type.Number(), + "processStartedAtMs": Type.Number(), "updatedAtMs": Type.Number(), "isDeleted": Type.Boolean(), }); @@ -298,6 +302,8 @@ export class SystemInfo { json.diskAvailable, json.canRestart, json.restartRequired, + json.systemStartedAtMs, + json.processStartedAtMs, json.updatedAtMs, json.isDeleted, ); diff --git a/packages/lib/src/data/messages_instance.ts b/packages/lib/src/data/messages_instance.ts index a0a251d2..91d8c0b4 100644 --- a/packages/lib/src/data/messages_instance.ts +++ b/packages/lib/src/data/messages_instance.ts @@ -44,6 +44,7 @@ export class InstanceDetails { public gamePort: number | undefined, public status: InstanceStatus, public factorioVersion: TargetVersion | undefined, + public startedAtMs = 0, /** Millisecond Unix timestamp this entry was last updated at */ public updatedAtMs = 0, public excludeFromStartAll = false, @@ -59,6 +60,7 @@ export class InstanceDetails { "creating_save", "exporting_data", "deleted", ]), "factorioVersion": Type.Optional(TargetVersionSchema), + "startedAtMs": Type.Optional(Type.Number()), "updatedAtMs": Type.Optional(Type.Number()), "excludeFromStartAll": Type.Optional(Type.Boolean()), }); @@ -71,6 +73,7 @@ export class InstanceDetails { json.gamePort, json.status, json.factorioVersion, + json.startedAtMs, json.updatedAtMs, json.excludeFromStartAll, ); diff --git a/packages/lib/src/system_collectors.ts b/packages/lib/src/system_collectors.ts index 6822e474..436c57de 100644 --- a/packages/lib/src/system_collectors.ts +++ b/packages/lib/src/system_collectors.ts @@ -134,7 +134,12 @@ function minZip(a: T[], b: T[]): [T, T][] { let previousTotalCpuMs: number[] = []; let previousIdleCpuMs: number[] = []; -export async function gatherSystemInfo(id: SystemInfo["id"], canRestart: boolean, restartRequired: boolean) { +export async function gatherSystemInfo( + id: SystemInfo["id"], + canRestart: boolean, + restartRequired: boolean, + startedAtMs: number +) { 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); @@ -152,6 +157,7 @@ export async function gatherSystemInfo(id: SystemInfo["id"], canRestart: boolean diskAvailable = stats.bavail * stats.bsize; } + const now = Date.now(); return new SystemInfo( id, os.hostname(), @@ -166,7 +172,9 @@ export async function gatherSystemInfo(id: SystemInfo["id"], canRestart: boolean diskAvailable, canRestart, restartRequired, - Date.now(), + now - (os.uptime() * 1000), + startedAtMs, + now, false, ); } diff --git a/packages/web_ui/src/components/ControllerPage.tsx b/packages/web_ui/src/components/ControllerPage.tsx index 4a65b415..1c74cbc9 100644 --- a/packages/web_ui/src/components/ControllerPage.tsx +++ b/packages/web_ui/src/components/ControllerPage.tsx @@ -8,7 +8,7 @@ import PluginExtra from "./PluginExtra"; import LogConsole, { SelectMaxLogLevel } from "./LogConsole"; import { MetricCpuRatio, MetricCpuUsed, MetricMemoryRatio, MetricMemoryUsed, - MetricDiskUsed, MetricDiskRatio, + MetricDiskUsed, MetricDiskRatio, MetricRelativeDate, } from "./system_metrics"; import { useAccount } from "../model/account"; import { useSystems } from "../model/system"; @@ -101,6 +101,12 @@ export default function ControllerPage() { {system?.node} {system?.kernel} {system?.machine} + + + + + + {system?.hostname} {system?.cpuModel} diff --git a/packages/web_ui/src/components/HostViewPage.tsx b/packages/web_ui/src/components/HostViewPage.tsx index f7eddcf8..f6f4d9dd 100644 --- a/packages/web_ui/src/components/HostViewPage.tsx +++ b/packages/web_ui/src/components/HostViewPage.tsx @@ -17,7 +17,7 @@ import PageLayout from "./PageLayout"; import PluginExtra from "./PluginExtra"; import { MetricCpuRatio, MetricCpuUsed, MetricMemoryRatio, MetricMemoryUsed, - MetricDiskUsed, MetricDiskRatio, + MetricDiskUsed, MetricDiskRatio, MetricRelativeDate, } from "./system_metrics"; import { formatTimestamp } from "../util/time_format"; import { useSystems } from "../model/system"; @@ -147,8 +147,14 @@ export default function HostViewPage() { {system?.node} {system?.kernel} {system?.machine} - {system?.hostname} - {host.remoteAddress} + + + + + + + {system?.hostname} + {host.remoteAddress} {system?.cpuModel} diff --git a/packages/web_ui/src/components/InstanceViewPage.tsx b/packages/web_ui/src/components/InstanceViewPage.tsx index 69b5055c..8fad2747 100644 --- a/packages/web_ui/src/components/InstanceViewPage.tsx +++ b/packages/web_ui/src/components/InstanceViewPage.tsx @@ -25,6 +25,7 @@ import { useHost } from "../model/host"; import InstanceStatusTag from "./InstanceStatusTag"; import Link from "./Link"; import { instancePublicAddress } from "../util/instance"; +import { MetricRelativeDate } from "./system_metrics"; type MenuItem = Required["items"][number]; const { Title } = Typography; @@ -41,6 +42,7 @@ function InstanceDescription(props: InstanceDescriptionProps) { return {!assigned @@ -64,7 +66,12 @@ function InstanceDescription(props: InstanceDescriptionProps) { {instance.factorioVersion ?? "unknown"} - + + + + + + ; } diff --git a/packages/web_ui/src/components/system_metrics.tsx b/packages/web_ui/src/components/system_metrics.tsx index 34e503da..9c051d12 100644 --- a/packages/web_ui/src/components/system_metrics.tsx +++ b/packages/web_ui/src/components/system_metrics.tsx @@ -63,3 +63,52 @@ export function RestartRequired(props: { system?: lib.SystemInfo }) { ; } + +/** + * Returns a human-readable duration between two dates. + * + * The output includes up to two most significant time units and omits + * leading zero units. Supported units are weeks, days, hours, minutes, + * and seconds. + * + * Examples: "1w 2d", "2d 3h", "1h 2m", "45s" + * + * @param date1 - The starting date. + * @param date2 - The ending date. + * @returns A duration string (e.g. "2d 3h"). + */ +function humanAbsTimeDiff(date1: number, date2 = 0) { + let diffMs = Math.abs(date2 - date1); + const totalSeconds = Math.floor(diffMs / 1000); + + const weeks = Math.floor(totalSeconds / 604800); // 7 * 24 * 60 * 60 + const days = Math.floor((totalSeconds % 604800) / 86400); + const hours = Math.floor((totalSeconds % 86400) / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + + if (weeks > 0) { + return days > 0 ? `${weeks}w ${days}d` : `${weeks}w`; + } + + if (days > 0) { + return hours > 0 ? `${days}d ${hours}h` : `${days}d`; + } + + if (hours > 0) { + return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`; + } + + if (minutes > 0) { + return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`; + } + + return `${seconds}s`; +} + +export function MetricRelativeDate(props: { timeMs?: number }) { + if (!props.timeMs || props.timeMs === 0) { + return "N/A"; + } + return `${new Date(props.timeMs).toLocaleString()} (${humanAbsTimeDiff(props.timeMs, Date.now())})`; +}