bitburner-scripts/src/ezgame/startall.ts

61 lines
2.1 KiB
TypeScript

import { NS } from "@ns";
import { scan } from "../ezgame/scan";
interface StartOptions {
threads?: number; // explicit thread count
ramPercentage?: number; // prcentage of max ram (0.0 to 1.0)
args?: string[]; // optional arguments to pass to the script
}
export const startall = (ns: NS, scriptName: string, options: StartOptions = {}) => {
const { threads: threadCount, ramPercentage, args = [] } = options;
const rootedHosts = scan(ns, { rootAccess: true });
let totalThreadsStarted = 0;
let hostsStartedOn = 0;
// get the ram required to run one thread of the script
// assume that the script is already on all the hosts that we want to run it in
// should be ran after propagation
const ramPerThread = ns.getScriptRam(scriptName, "home");
// iterate through all the rooted hosts and start the script
rootedHosts.forEach((host) => {
if (host === "home") return;
// calculate how many threads we can run based on the options provided
const availableRam = ns.getServerMaxRam(host) - ns.getServerUsedRam(host);
let threadsToUse: number;
if (threadCount) {
// priority 1 explicit thread count
threadsToUse = threadCount;
} else if (ramPercentage !== undefined) {
// priority 2 percentage of total ram
const targetRam = ns.getServerMaxRam(host) * ramPercentage;
threadsToUse = Math.floor(targetRam / ramPerThread);
} else {
// default use all available ram
threadsToUse = Math.floor(availableRam / ramPerThread);
}
if (threadsToUse > 0) {
ns.exec(scriptName, host, threadsToUse, ...args);
ns.tprint(`Started ${scriptName} on ${host} with ${threadsToUse} threads`);
totalThreadsStarted += threadsToUse;
hostsStartedOn++;
} else {
ns.tprint(`Not enough RAM to run ${scriptName} on ${host}`);
}
});
ns.tprint(`Total threads started: ${totalThreadsStarted}`);
ns.tprint(`Hosts affected: ${hostsStartedOn}`);
};
export const main = (ns: NS) => {
// get the arguments from the command line
const args = ns.args as string[];
startall(ns, "super.js", { args: args });
};