[bugfix-627] support host calls for flatpak with spawn/exec

* created wrapper calls for spawn and exec for all os support
* refactored names for isProcessRunning, getProcessId, and isSteamRunning
This commit is contained in:
silentrald
2024-11-21 00:48:31 +08:00
parent 8096b3ec76
commit 38ea360ee6
12 changed files with 214 additions and 83 deletions
+1
View File
@@ -21,4 +21,5 @@ export const HTTP_STATUS_CODES = constants;
export const PROTON_BINARY_PREFIX = "proton";
export const WINE_BINARY_PREFIX = path.join("files", "bin", "wine64");
export const IS_FLATPAK = process.env.container === "flatpak";
+151 -10
View File
@@ -1,25 +1,166 @@
import cp from "child_process";
import log from "electron-log";
import psList from "ps-list";
import { IS_FLATPAK } from "main/constants";
export async function taskRunning(task: string): Promise<boolean> {
// There are 2 erroneous lines ps | grep which is both the ps and grep calls themselves
const MIN_PROCESS_COUNT_LINUX = 2;
type LinuxOptions = {
// Add the prefix to the command
// eg. command - "./Beat Saber.exe" --no-yeet, prefix - "path/to/proton" run
// = "path/to/proton" run "./Beat Saber.exe" --no-yeet
prefix: string;
};
// Only applied if package as flatpak
type FlatpakOptions = {
// Force to use "flatpak-spawn --host" to run commands outside of the sandbox
host: boolean;
// Only copy the keys from options.env from bsmSpawn/bsmExec
env?: string[];
};
export type BsmSpawnOptions = {
args?: string[];
options?: cp.SpawnOptions;
log?: boolean;
linux?: LinuxOptions;
flatpak?: FlatpakOptions;
};
export type BsmExecOptions = {
args?: string[];
options?: cp.ExecOptions;
log?: boolean;
linux?: LinuxOptions;
flatpak?: FlatpakOptions;
};
function updateCommand(command: string, options: BsmSpawnOptions) {
if (options?.args) {
command += ` ${options.args.join(" ")}`;
}
if (process.platform === "linux") {
// "/bin/sh" does not see flatpak-spawn
// Most Debian and Arch should also support "/bin/bash"
options.options.shell = "/bin/bash";
if (options.linux?.prefix) {
command = `${options.linux.prefix} ${command}`;
}
if (options?.flatpak?.host) {
const envArgs = (options?.flatpak?.env && options?.options?.env)
&& options.flatpak.env
.filter(envName => options.options.env[envName])
.map(envName =>
`--env=${envName}="${options.options.env[envName]}"`
)
.join(" ");
command = `flatpak-spawn --host ${envArgs || ""} ${command}`;
}
}
return command;
}
export function bsmSpawn(command: string, options?: BsmSpawnOptions) {
options = options || {};
options.options = options.options || {};
command = updateCommand(command, options);
if (options?.log) {
log.info(process.platform === "win32" ? "Windows" : "Linux", "spawn command\n>", command);
}
return cp.spawn(command, options.options);
}
export function bsmExec(command: string, options?: BsmExecOptions): Promise<{
stdout: string;
stderr: string;
}> {
options = options || {};
options.options = options.options || {};
command = updateCommand(command, options);
if (options?.log) {
log.info(
process.platform === "win32" ? "Windows" : "Linux",
"exec command\n>", command
);
}
return new Promise((resolve, reject) => {
cp.exec(command, options?.options || {}, (error: Error, stdout: string, stderr: string) => {
if (error) { return reject(error); }
resolve({ stdout, stderr });
});
})
}
async function isProcessRunningLinux(name: string): Promise<boolean> {
try {
const { stdout: count } = await bsmExec(`ps awwxo args | grep -c "${name}"`, {
log: true,
flatpak: { host: IS_FLATPAK },
});
return +count.trim() > MIN_PROCESS_COUNT_LINUX;
} catch(error) {
log.error(error);
return false;
};
}
async function getProcessIdWindows(name: string): Promise<number | null> {
try {
const processes = await psList();
return processes.some(process => process.name?.includes(task) || process.cmd?.includes(task));
const process = processes.find(process => process.name?.includes(name) || process.cmd?.includes(name));
return process?.pid;
} catch (error) {
log.error(error);
return null;
}
catch(error){
}
export const isProcessRunning = process.platform === "win32"
? isProcessRunningWindows
: isProcessRunningLinux;
async function isProcessRunningWindows(name: string): Promise<boolean> {
try {
const processes = await psList();
return processes.some(process =>
process.name?.includes(name) || process.cmd?.includes(name)
);
} catch (error) {
log.error(error);
return false;
}
}
export async function getProcessPid(task: string): Promise<number> {
async function getProcessIdLinux(name: string): Promise<number | null> {
try {
const processes = await psList();
const process = processes.find(process => process.name?.includes(task) || process.cmd?.includes(task));
return process?.pid;
}
catch(error){
const { stdout } = await bsmExec(`ps awwxo pid,args | grep "${name}"`, {
log: true,
flatpak: { host: IS_FLATPAK },
});
const line = stdout.split("\n")
.slice(0, -MIN_PROCESS_COUNT_LINUX)
.map(line => line.trimStart())
.find(line => line.includes(name) && !line.includes("grep"));
return line ? +line.split(" ").at(0) : null;
} catch(error) {
log.error(error);
return null;
}
};
}
export const getProcessId = process.platform === "win32"
? getProcessIdWindows
: getProcessIdLinux;
@@ -1,10 +1,12 @@
import { LaunchOption } from "shared/models/bs-launch";
import { BSLocalVersionService } from "../bs-local-version.service";
import { ChildProcessWithoutNullStreams, SpawnOptionsWithoutStdio, spawn } from "child_process";
import { ChildProcessWithoutNullStreams, SpawnOptionsWithoutStdio } from "child_process";
import path from "path";
import log from "electron-log";
import { sToMs } from "../../../shared/helpers/time.helpers";
import { LinuxService } from "../linux.service";
import { bsmSpawn } from "main/helpers/os.helpers";
import { IS_FLATPAK } from "main/constants";
export abstract class AbstractLauncherService {
@@ -47,12 +49,24 @@ export abstract class AbstractLauncherService {
spawnOptions.windowsVerbatimArguments = true;
}
if (process.platform === "linux") {
return this.linux.spawnBsProcess(bsExePath, args, spawnOptions)
}
log.info("Windows launch BS command\n>" ,bsExePath, args?.join(" "));
return spawn(bsExePath, args, spawnOptions);
return bsmSpawn(`"${bsExePath}"`, {
args, options: spawnOptions, log: true,
linux: { prefix: this.linux.getProtonCommand() },
flatpak: {
host: IS_FLATPAK,
env: [
"SteamAppId",
"SteamOverlayGameId",
"SteamGameId",
"WINEDLLOVERRIDES",
"STEAM_COMPAT_DATA_PATH",
"STEAM_COMPAT_INSTALL_PATH",
"STEAM_COMPAT_CLIENT_INSTALL_PATH",
"STEAM_COMPAT_APP_ID",
"SteamEnv",
],
},
});
}
protected launchBs(bsExePath: string, args: string[], options?: SpawnBsProcessOptions): {process: ChildProcessWithoutNullStreams, exit: Promise<number>} {
@@ -8,7 +8,7 @@ import log from "electron-log";
import { sToMs } from "../../../shared/helpers/time.helpers";
import { lstat, pathExists, readdir, readlink, rename, symlink, unlink } from "fs-extra";
import { AbstractLauncherService } from "./abstract-launcher.service";
import { taskRunning } from "../../helpers/os.helpers";
import { isProcessRunning } from "../../helpers/os.helpers";
import { CustomError } from "../../../shared/models/exceptions/custom-error.class";
import { InstallationLocationService } from "../installation-location.service";
import { ensurePathNotAlreadyExist } from "../../helpers/fs.helpers";
@@ -154,7 +154,7 @@ export class OculusLauncherService extends AbstractLauncherService implements St
(async () => {
// Cannot start multiple instances of Beat Saber with Oculus
const bsRunning = await taskRunning(BS_EXECUTABLE).catch(() => false);
const bsRunning = await isProcessRunning(BS_EXECUTABLE).catch(() => false);
if(bsRunning){
throw CustomError.fromError(new Error("Cannot start two instance of Beat Saber for Oculus"), BSLaunchError.BS_ALREADY_RUNNING);
}
@@ -74,7 +74,7 @@ export class SteamLauncherService extends AbstractLauncherService implements Sto
}
// Open Steam if not running
if(!(await this.steam.steamRunning())){
if(!(await this.steam.isSteamRunning())){
obs.next({type: BSLaunchEvent.STEAM_LAUNCHING});
await this.steam.openSteam().then(() => {
+3 -2
View File
@@ -6,6 +6,7 @@ import { RequestService } from "./request.service";
import { pathExistsSync, readJSON } from "fs-extra";
import { allSettled } from "../../shared/helpers/promise.helpers";
import { LinuxService } from "./linux.service";
import { IS_FLATPAK } from "main/constants";
export class BSVersionLibService {
private readonly REMOTE_BS_VERSIONS_URL: string = "https://raw.githubusercontent.com/Zagrios/bs-manager/master/assets/jsons/bs-versions.json";
@@ -37,7 +38,7 @@ export class BSVersionLibService {
}
private async getLocalVersions(): Promise<BSVersion[]> {
if (this.linuxService.isFlatpak) {
if (IS_FLATPAK) {
const flatpakVersionsPath = path.join(this.linuxService.getFlatpakLocalVersionFolder(), this.VERSIONS_FILE);
if (pathExistsSync(flatpakVersionsPath)) {
return readJSON(flatpakVersionsPath);
@@ -50,7 +51,7 @@ export class BSVersionLibService {
private async updateLocalVersions(versions: BSVersion[]): Promise<void> {
const localVersionsPath = path.join(
this.linuxService.isFlatpak
IS_FLATPAK
? this.linuxService.getFlatpakLocalVersionFolder()
: this.utilsService.getAssestsJsonsPath(),
this.VERSIONS_FILE
+11 -44
View File
@@ -1,7 +1,6 @@
import fs from "fs-extra";
import log from "electron-log";
import path from "path";
import { SpawnOptionsWithoutStdio, spawn } from "child_process";
import { BS_APP_ID, PROTON_BINARY_PREFIX, WINE_BINARY_PREFIX } from "main/constants";
import { StaticConfigurationService } from "./static-configuration.service";
import { CustomError } from "shared/models/exceptions/custom-error.class";
@@ -19,8 +18,7 @@ export class LinuxService {
}
private readonly staticConfig: StaticConfigurationService;
public readonly isFlatpak = process.env.container === "flatpak";
private protonCommand = "";
private constructor() {
this.staticConfig = StaticConfigurationService.getInstance();
@@ -55,13 +53,17 @@ export class LinuxService {
BSLaunchError.PROTON_NOT_SET
);
}
const protonPath = path.join(this.staticConfig.get("proton-folder"), PROTON_BINARY_PREFIX);
const protonPath = path.join(
this.staticConfig.get("proton-folder"),
PROTON_BINARY_PREFIX
);
if (!fs.pathExistsSync(protonPath)) {
throw CustomError.fromError(
new Error("Could not locate proton binary"),
BSLaunchError.PROTON_NOT_FOUND
);
}
this.protonCommand = `"${protonPath}" run`;
// Setup Proton environment variables
Object.assign(env, {
@@ -78,22 +80,6 @@ export class LinuxService {
});
}
public spawnBsProcess(bsExePath: string, args: string[], spawnOptions: SpawnOptionsWithoutStdio) {
// Already checked in setupLaunch
const protonPath = path.join(this.staticConfig.get("proton-folder"), PROTON_BINARY_PREFIX);
// "/bin/sh" does not see flatpak-spawn
// Most Debian and Arch should also support "/bin/bash"
spawnOptions.shell = "/bin/bash";
const command = this.isFlatpak
? this.createFlatpakCommand(protonPath, bsExePath, args, spawnOptions)
: `"${protonPath}" run "${bsExePath}" ${args.join(" ")}`;
log.info("Linux launch BS command\n>", command);
return spawn(command, spawnOptions);
}
public verifyProtonPath(protonFolder: string = ""): boolean {
if (protonFolder === "") {
if (!this.staticConfig.has("proton-folder")) {
@@ -124,32 +110,13 @@ export class LinuxService {
return winePath;
}
// === Flatpak Specific === //
private createFlatpakCommand(protonPath: string, bsExePath: string, args: string[], spawnOptions: SpawnOptionsWithoutStdio): string {
// DON'T REMOVE: Good for injecting commands while debugging with flatpak
// return args.slice(1).join(" ");
// The env vars are hidden to flatpak-spawn, need to set them manually in --env arg
// Minimal copy of the env, don't need to copy them all
const envArgs = [
"SteamAppId",
"SteamOverlayGameId",
"SteamGameId",
"WINEDLLOVERRIDES",
"STEAM_COMPAT_DATA_PATH",
"STEAM_COMPAT_INSTALL_PATH",
"STEAM_COMPAT_CLIENT_INSTALL_PATH",
"STEAM_COMPAT_APP_ID",
"SteamEnv",
].map(envName => {
return `--env=${envName}="${spawnOptions.env[envName]}"`;
}).join(" ");
return `flatpak-spawn --host ${envArgs} "${protonPath}" run "${bsExePath}" ${args.join(" ")}`;
public getProtonCommand(): string {
// Set in setupLaunch
return this.protonCommand;
}
// === Flatpak Specific === //
public getFlatpakLocalVersionFolder(): string {
return path.join(
app.getPath("home"),
@@ -5,7 +5,6 @@ import { BSLocalVersionService } from "../bs-local-version.service";
import path from "path";
import md5File from "md5-file";
import { RequestService } from "../request.service";
import { spawn } from "child_process";
import { BS_EXECUTABLE } from "../../constants";
import log from "electron-log";
import { deleteFolder, pathExist, Progression, unlinkPath } from "../../helpers/fs.helpers";
@@ -17,9 +16,9 @@ import { CustomError } from "shared/models/exceptions/custom-error.class";
import { popElement } from "shared/helpers/array.helpers";
import { LinuxService } from "../linux.service";
import { tryit } from "shared/helpers/error.helpers";
import { UtilsService } from "../utils.service";
import crypto from "crypto";
import { BsmZipExtractor } from "main/models/bsm-zip-extractor.class";
import { bsmSpawn } from "main/helpers/os.helpers";
export class BsModsManagerService {
private static instance: BsModsManagerService;
@@ -28,7 +27,6 @@ export class BsModsManagerService {
private readonly bsLocalService: BSLocalVersionService;
private readonly linuxService: LinuxService;
private readonly requestService: RequestService;
private readonly utilsService: UtilsService;
private manifestMatches: Mod[];
@@ -44,7 +42,6 @@ export class BsModsManagerService {
this.bsLocalService = BSLocalVersionService.getInstance();
this.linuxService = LinuxService.getInstance();
this.requestService = RequestService.getInstance();
this.utilsService = UtilsService.getInstance();
}
private async getModFromHash(hash: string): Promise<Mod> {
@@ -144,19 +141,28 @@ export class BsModsManagerService {
return false;
}
let cmd = `"${ipaPath}" "${bsExePath}" ${args.join(" ")}`;
const cmd = `"${ipaPath}" "${bsExePath}" ${args.join(" ")}`;
let winePath: string = "";
if (process.platform === "linux") {
const { error, result: winePath } = tryit(() => this.linuxService.getWinePath());
const { error, result } = tryit(() => this.linuxService.getWinePath());
if (error) {
log.error(error);
return false;
}
cmd = `"${winePath}" ${cmd}`;
winePath = `"${result}"`;
}
return new Promise<boolean>(resolve => {
log.info("START IPA PROCESS", cmd);
const processIPA = spawn(cmd, { cwd: versionPath, detached: true, shell: true });
const processIPA = bsmSpawn(cmd, {
log: true,
options: {
cwd: versionPath,
detached: true,
shell: true
},
linux: { prefix: winePath },
});
const timeout = setTimeout(() => {
log.info("Ipa process timeout");
+2 -2
View File
@@ -4,7 +4,7 @@ import log from "electron-log";
import { lstat } from "fs-extra";
import { tryit } from "../../shared/helpers/error.helpers";
import { shell } from "electron";
import { taskRunning } from "../helpers/os.helpers";
import { isProcessRunning } from "../helpers/os.helpers";
import { sToMs } from "../../shared/helpers/time.helpers";
import { execOnOs } from "../helpers/env.helpers";
@@ -99,7 +99,7 @@ export class OculusService {
}
public oculusRunning(): Promise<boolean> {
return taskRunning("OculusClient");
return isProcessRunning("OculusClient");
}
public async startOculus(): Promise<void>{
+6 -6
View File
@@ -5,7 +5,7 @@ import { readFile } from "fs/promises";
import { pathExist } from "../helpers/fs.helpers";
import log from "electron-log";
import { app, shell } from "electron";
import { getProcessPid, taskRunning } from "../helpers/os.helpers";
import { getProcessId, isProcessRunning } from "main/helpers/os.helpers";
import { isElevated } from "query-process";
import { execOnOs } from "../helpers/env.helpers";
@@ -15,7 +15,7 @@ export class SteamService {
private static readonly PROCESS_NAME: string = process.platform === "linux"
? "steam-runtime-launcher-service"
: "steam";
: "steam.exe";
private static instance: SteamService;
@@ -37,15 +37,15 @@ export class SteamService {
return registryValue.value;
}
public async steamRunning(): Promise<boolean>{
const steamProcessRunning = await taskRunning(SteamService.PROCESS_NAME);
public async isSteamRunning(): Promise<boolean>{
const steamProcessRunning = await isProcessRunning(SteamService.PROCESS_NAME);
if(process.platform === "linux") { return steamProcessRunning; }
const activeUser = await this.getActiveUser().catch(err => log.error(err));
return steamProcessRunning && !!activeUser;
}
public async getSteamPid(): Promise<number>{
return getProcessPid(SteamService.PROCESS_NAME);
return getProcessId(SteamService.PROCESS_NAME);
}
/**
@@ -123,7 +123,7 @@ export class SteamService {
return new Promise((resolve, reject) => {
// Every 3 seconds check if steam is running
const interval = setInterval(() => {
const steamRunning = this.steamRunning().catch(() => false);
const steamRunning = this.isSteamRunning().catch(() => false);
steamRunning.then(running => {
if(!running){ return; }
clearInterval(interval);