Skip to content

Commit

Permalink
feat: Docker instance real path mapping variable
Browse files Browse the repository at this point in the history
  • Loading branch information
yumao233 committed Oct 8, 2024
1 parent da7948b commit 984dee2
Show file tree
Hide file tree
Showing 11 changed files with 50 additions and 42 deletions.
2 changes: 1 addition & 1 deletion daemon/src/entity/commands/docker/docker_start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default class DockerStartCommand extends InstanceCommand {
}

async exec(instance: Instance, source = "Unknown") {
if (!instance.config.cwd || !instance.config.ie || !instance.config.oe)
if (!instance.hasCwdPath() || !instance.config.ie || !instance.config.oe)
throw new StartupDockerProcessError($t("TXT_CODE_a6424dcc"));
if (!fs.existsSync(instance.absoluteCwdPath()))
throw new StartupDockerProcessError($t("TXT_CODE_instance.dirNoE"));
Expand Down
6 changes: 3 additions & 3 deletions daemon/src/entity/commands/general/general_install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ export default class GeneralInstallCommand extends InstanceCommand {
instance.setLock(true);
instance.status(Instance.STATUS_BUSY);
instance.println($t("TXT_CODE_1704ea49"), $t("TXT_CODE_cbc235ad"));
if (instance.config.cwd.length > 1) {
fs.removeSync(instance.config.cwd);
fs.mkdirsSync(instance.config.cwd);
if (instance.hasCwdPath()) {
await fs.remove(instance.absoluteCwdPath());
await fs.mkdirs(instance.absoluteCwdPath());
}
instance.println($t("TXT_CODE_1704ea49"), $t("TXT_CODE_906c5d6a"));
this.process = new QuickInstallTask(
Expand Down
6 changes: 3 additions & 3 deletions daemon/src/entity/commands/general/general_start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default class GeneralStartCommand extends InstanceCommand {
async exec(instance: Instance, source = "Unknown") {
if (
(!instance.config.startCommand && instance.config.processType === "general") ||
!instance.config.cwd ||
!instance.hasCwdPath() ||
!instance.config.ie ||
!instance.config.oe
)
Expand All @@ -85,13 +85,13 @@ export default class GeneralStartCommand extends InstanceCommand {
logger.info($t("TXT_CODE_general_start.startInstance", { source: source }));
logger.info($t("TXT_CODE_general_start.instanceUuid", { uuid: instance.instanceUuid }));
logger.info($t("TXT_CODE_general_start.startCmd", { cmdList: JSON.stringify(commandList) }));
logger.info($t("TXT_CODE_general_start.cwd", { cwd: instance.config.cwd }));
logger.info($t("TXT_CODE_general_start.cwd", { cwd: instance.absoluteCwdPath() }));
logger.info("----------------");

// create child process
// Parameter 1 directly passes the process name or path (including spaces) without double quotes
const subProcess = spawn(commandExeFile, commandParameters, {
cwd: instance.config.cwd,
cwd: instance.absoluteCwdPath(),
stdio: "pipe",
windowsHide: true,
env: process.env
Expand Down
8 changes: 4 additions & 4 deletions daemon/src/entity/commands/pty/pty_start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,14 @@ export default class PtyStartCommand extends InstanceCommand {
async exec(instance: Instance, source = "Unknown") {
if (
!instance.config.startCommand ||
!instance.config.cwd ||
!instance.hasCwdPath() ||
!instance.config.ie ||
!instance.config.oe
)
throw new StartupError($t("TXT_CODE_pty_start.cmdErr"));
if (!fs.existsSync(instance.absoluteCwdPath()))
throw new StartupError($t("TXT_CODE_pty_start.cwdNotExist"));
if (!path.isAbsolute(path.normalize(instance.config.cwd)))
if (!path.isAbsolute(path.normalize(instance.absoluteCwdPath())))
throw new StartupError($t("TXT_CODE_pty_start.mustAbsolutePath"));

// PTY mode correctness check
Expand Down Expand Up @@ -202,7 +202,7 @@ export default class PtyStartCommand extends InstanceCommand {
"-coder",
instance.config.oe,
"-dir",
instance.config.cwd,
instance.absoluteCwdPath(),
"-fifo",
pipeName,
"-cmd",
Expand All @@ -215,7 +215,7 @@ export default class PtyStartCommand extends InstanceCommand {
logger.info($t("TXT_CODE_pty_start.startCmd", { cmd: commandList.join(" ") }));
logger.info($t("TXT_CODE_pty_start.ptyPath", { path: PTY_PATH }));
logger.info($t("TXT_CODE_pty_start.ptyParams", { param: ptyParameter.join(" ") }));
logger.info($t("TXT_CODE_pty_start.ptyCwd", { cwd: instance.config.cwd }));
logger.info($t("TXT_CODE_pty_start.ptyCwd", { cwd: instance.absoluteCwdPath() }));
logger.info("----------------");

// create pty child process
Expand Down
9 changes: 8 additions & 1 deletion daemon/src/entity/instance/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { PresetCommandManager } from "./preset";
import FunctionDispatcher, { IPresetCommand } from "../commands/dispatcher";
import { IInstanceProcess } from "./interface";
import StartCommand from "../commands/start";
import { configureEntityParams } from "common";
import { configureEntityParams, toText } from "common";
import { OpenFrp } from "../commands/task/openfrp";
import logger from "../../service/log";
import { t } from "i18next";
Expand Down Expand Up @@ -356,7 +356,14 @@ export default class Instance extends EventEmitter {
return date.toLocaleDateString() + " " + date.getHours() + ":" + date.getMinutes();
}

hasCwdPath() {
return !!this.config.cwd;
}

absoluteCwdPath() {
const envInstancesBasePath = toText(process.env.MCSM_INSTANCES_BASE_PATH);
if (envInstancesBasePath)
return path.normalize(path.join(envInstancesBasePath, this.instanceUuid));
if (!this.config || !this.config.cwd) throw new Error("Instance config error, cwd is Null!");
if (path.isAbsolute(this.config.cwd)) return path.normalize(this.config.cwd);
return path.normalize(path.join(process.cwd(), this.config.cwd));
Expand Down
6 changes: 3 additions & 3 deletions daemon/src/routers/http_router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ router.get("/download/:key/:fileName", async (ctx) => {
if (!FileManager.checkFileName(paramsFileName))
throw new Error($t("TXT_CODE_http_router.fileNameNotSpec"));

const cwd = instance.config.cwd;
const cwd = instance.absoluteCwdPath();
const fileRelativePath = mission.parameter.fileName;

// Check for file cross-directory security risks
Expand Down Expand Up @@ -65,7 +65,7 @@ router.post("/upload/:key", async (ctx) => {
const instance = InstanceSubsystem.getInstance(mission.parameter.instanceUuid);
if (!instance) throw new Error("Access denied: No instance found");
const uploadDir = mission.parameter.uploadDir;
const cwd = instance.config.cwd;
const cwd = instance.absoluteCwdPath();
const tmpFiles = ctx.request.files?.file;
if (tmpFiles) {
let uploadedFile: formidable.File;
Expand Down Expand Up @@ -120,7 +120,7 @@ router.post("/upload/:key", async (ctx) => {
});

if (unzip) {
const fileManager = new FileManager(instance.config.cwd);
const fileManager = new FileManager(instance.absoluteCwdPath());
fileManager.unzip(fileSaveAbsolutePath, "", zipCode);
}
ctx.body = "OK";
Expand Down
6 changes: 4 additions & 2 deletions daemon/src/service/async_task_service/quick_install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ export class QuickInstallTask extends AsyncTask {
const url = new URL(this.targetLink);
downloadFileName = url.pathname.split("/").pop() || `application${this.extName}`;
}
this.filePath = path.normalize(path.join(this.instance.config.cwd, downloadFileName));
this.filePath = path.normalize(
path.join(this.instance.absoluteCwdPath(), downloadFileName)
);
this.writeStream = fs.createWriteStream(this.filePath);
const response = await axios<Readable>({
url: this.targetLink,
Expand Down Expand Up @@ -109,7 +111,7 @@ export class QuickInstallTask extends AsyncTask {
let startCommand = this.instance.config.startCommand;
const ENV_MAP: IJsonData = {
java: "java",
cwd: this.instance.config.cwd,
cwd: this.instance.absoluteCwdPath(),
rconIp: this.instance.config.rconIp || "localhost",
rconPort: String(this.instance.config.rconPort),
rconPassword: this.instance.config.rconPassword,
Expand Down
40 changes: 20 additions & 20 deletions daemon/src/service/docker_process_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ export class SetupDockerContainer extends AsyncTask {
commandList = [];
}

const cwd = instance.absoluteCwdPath();

// Parsing port open
// 25565:25565/tcp 8080:8080/tcp
const portMap = instance.config.docker.ports || [];
Expand Down Expand Up @@ -118,11 +116,10 @@ export class SetupDockerContainer extends AsyncTask {
const isTty = instance.config.terminalOption.pty;

const workingDir = instance.config.docker.workingDir ?? "";
const cwd = instance.absoluteCwdPath();

if (workingDir) {
instance.println(
"CONTAINER",
$t("TXT_CODE_e76e49e9") + instance.config.cwd + " --> " + workingDir + "\n"
);
instance.println("CONTAINER", $t("TXT_CODE_e76e49e9") + cwd + " --> " + workingDir + "\n");
} else {
instance.println("CONTAINER", $t("TXT_CODE_ffa884f9"));
}
Expand All @@ -147,6 +144,22 @@ export class SetupDockerContainer extends AsyncTask {
logger.info(`TYPE: Docker Container`);
logger.info("----------------");

const mounts: Docker.MountConfig =
extraBinds.map((v) => {
return {
Type: "bind",
Source: v.hostPath,
Target: v.containerPath
};
}) || [];
if (workingDir && cwd) {
mounts.push({
Type: "bind",
Source: cwd,
Target: workingDir
});
}

// Start Docker container creation and running
const docker = new DefaultDocker();
this.container = await docker.createContainer({
Expand All @@ -171,20 +184,7 @@ export class SetupDockerContainer extends AsyncTask {
CpuQuota: cpuQuota,
PortBindings: publicPortArray,
NetworkMode: instance.config.docker.networkMode,
Mounts: [
{
Type: "bind",
Source: cwd,
Target: workingDir
},
...extraBinds.map((v) => {
return {
Type: "bind" as Docker.MountType,
Source: v.hostPath,
Target: v.containerPath
};
})
]
Mounts: mounts
},
NetworkingConfig: {
EndpointsConfig: {
Expand Down
3 changes: 1 addition & 2 deletions daemon/src/service/file_router_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ export function getFileManager(instanceUuid: string) {
if (!instance)
throw new Error($t("TXT_CODE_file_router_service.instanceNotExit", { uuid: instanceUuid }));
const fileCode = instance.config?.fileCode;
const cwd = instance.config.cwd;
return new FileManager(cwd, fileCode);
return new FileManager(instance.absoluteCwdPath(), fileCode);
}

let cacheDisks: string[] = [];
Expand Down
4 changes: 2 additions & 2 deletions daemon/src/service/instance_update_action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class InstanceUpdateAction extends AsyncTask {

public async onStart() {
let updateCommand = this.instance.config.updateCommand;
updateCommand = updateCommand.replace(/\{mcsm_workspace\}/gm, this.instance.config.cwd);
updateCommand = updateCommand.replace(/\{mcsm_workspace\}/gm, this.instance.absoluteCwdPath());
logger.info(
$t("TXT_CODE_general_update.readyUpdate", { instanceUuid: this.instance.instanceUuid })
);
Expand Down Expand Up @@ -57,7 +57,7 @@ export class InstanceUpdateAction extends AsyncTask {

// start the update command
const process = spawn(commandExeFile, commandParameters, {
cwd: this.instance.config.cwd,
cwd: this.instance.absoluteCwdPath(),
stdio: "pipe",
windowsHide: true
});
Expand Down
2 changes: 1 addition & 1 deletion daemon/src/service/system_instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ class InstanceSubsystem extends EventEmitter {
this.instances.delete(instanceUuid);
StorageSubsystem.delete("InstanceConfig", instanceUuid);
InstanceControl.deleteInstanceAllTask(instanceUuid);
if (deleteFile) fs.remove(instance.config.cwd, (err) => {});
if (deleteFile) fs.remove(instance.absoluteCwdPath(), (err) => {});
return true;
}
throw new Error($t("TXT_CODE_3bfb9e04"));
Expand Down

0 comments on commit 984dee2

Please sign in to comment.