Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion packages/salesforcedx-vscode-apex/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ import {
import { nls } from './messages';
import { getTelemetryService, setTelemetryService } from './telemetry/telemetry';

/** Time to await graceful LSP shutdown before force-kill. LS uses this to close its internal DB. */
const DEACTIVATE_STOP_TIMEOUT_MS = 3000;

export const activate = async (context: vscode.ExtensionContext) => {
const vscodeCoreExtension = await getVscodeCoreExtension();
const workspaceContext = vscodeCoreExtension.exports.WorkspaceContext.getInstance();
Expand Down Expand Up @@ -97,7 +100,23 @@ const registerCommands = (context: vscode.ExtensionContext): vscode.Disposable =
};

export const deactivate = async () => {
await languageClientManager.getClientInstance()?.stop();
const client = languageClientManager.getClientInstance();
if (client) {
let timedOut = false;
const stopPromise = client.stop();
const timeoutPromise = new Promise<void>(resolve =>
setTimeout(() => {
timedOut = true;
resolve();
}, DEACTIVATE_STOP_TIMEOUT_MS)
);
await Promise.race([stopPromise, timeoutPromise]);
if (timedOut) {
languageClientManager.killChildApexProcesses();
}
} else {
languageClientManager.killChildApexProcesses();
}
getTelemetryService().sendExtensionDeactivationEvent();
};

Expand Down
3 changes: 2 additions & 1 deletion packages/salesforcedx-vscode-apex/src/languageServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ import {
} from './settings';
import { getTelemetryService } from './telemetry/telemetry';

const JDWP_DEBUG_PORT = 2739;
/** Use 0 for dynamic JDWP port to avoid "address in use" when previous LS orphaned (e.g. Extension Host not shut down cleanly). */
const JDWP_DEBUG_PORT = 0;
const APEX_LANGUAGE_SERVER_MAIN = 'apex.jorje.lsp.ApexLanguageServerLauncher';
const SUSPEND_LANGUAGE_SERVER_STARTUP = process.env.SUSPEND_LANGUAGE_SERVER_STARTUP === 'true';
const LANGUAGE_SERVER_LOG_LEVEL = process.env.LANGUAGE_SERVER_LOG_LEVEL ?? 'ERROR';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,21 +381,9 @@ export class LanguageClientManager {
? 'powershell.exe -command "Get-CimInstance -ClassName Win32_Process | ForEach-Object { [PSCustomObject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; CommandLine = $_.CommandLine } } | Format-Table -HideTableHeaders"'
: 'ps -e -o pid,ppid,command';

const stdout = execSync(cmd).toString();
return stdout
.trim()
.split(/\r?\n/g)
.map((line: string) => {
const [pidStr, ppidStr, ...commandParts] = line.trim().split(/\s+/);
const pid = parseInt(pidStr, 10);
const ppid = parseInt(ppidStr, 10);
const command = commandParts.join(' ');
return { pid, ppid, command, orphaned: false };
})
.filter(
(processInfo: ProcessDetail) => !['ps', 'grep', 'Get-CimInstance'].some(c => processInfo.command.includes(c))
)
.filter((processInfo: ProcessDetail) => processInfo.command.includes('apex-jorje-lsp.jar'))
const entries = this.parseApexLspPsOutput(execSync(cmd).toString());
return entries
.map(p => ({ ...p, orphaned: false }))
.map(processInfo => {
const checkOrphanedCmd = isWindows
? `powershell.exe -command "Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${processInfo.ppid}'"`
Expand All @@ -422,6 +410,76 @@ export class LanguageClientManager {
process.kill(pid, 'SIGKILL');
}

/**
* Parse ps/PowerShell stdout into Apex LS process entries.
* Expects "pid ppid command" format (Unix ps -e -o pid,ppid,command).
* Also handles Win32_Process output with ProcessId, ParentProcessId, CommandLine.
*/
private parseApexLspPsOutput(stdout: string): { pid: number; ppid: number; command: string }[] {
const skipCommands = ['ps', 'grep', 'Get-CimInstance'];
const apexJar = 'apex-jorje-lsp.jar';
return stdout
.trim()
.split(/\r?\n/g)
.map(line => {
const parts = line.trim().split(/\s+/);
if (parts.length < 3) return null;
const pid = parseInt(parts[0], 10);
const ppid = parseInt(parts[1], 10);
const command = parts.slice(2).join(' ');
if (Number.isNaN(pid) || Number.isNaN(ppid)) return null;
return { pid, ppid, command };
})
.filter((p): p is NonNullable<typeof p> => p !== null)
.filter(p => !skipCommands.some(c => p.command.includes(c)) && p.command.includes(apexJar));
}

/**
* Find and SIGKILL Apex LS processes that are direct children of the current process.
* Used when LSP shutdown times out so the extension host can exit (child's stdio pipes close).
*/
public killChildApexProcesses(): void {
const isWindows = process.platform === 'win32';
if (!this.canRunCheck(isWindows)) {
return;
}
const parentPid = process.pid;
try {
if (isWindows) {
const cmd = `powershell.exe -command "Get-CimInstance -ClassName Win32_Process | Where-Object { $_.ParentProcessId -eq ${parentPid} } | ForEach-Object { [PSCustomObject]@{ ProcessId = $_.ProcessId; CommandLine = $_.CommandLine } } | Format-Table -HideTableHeaders"`;
const stdout = execSync(cmd).toString();
const lines = stdout.trim().split(/\r?\n/g);
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 2) continue;
const pid = parseInt(parts[0], 10);
const command = parts.slice(1).join(' ');
if (Number.isNaN(pid)) continue;
if (command.includes('apex-jorje-lsp.jar')) {
try {
this.terminateProcess(pid);
} catch {
// Process may already be gone
}
}
}
} else {
const stdout = execSync('ps -e -o pid,ppid,command').toString();
for (const p of this.parseApexLspPsOutput(stdout)) {
if (p.ppid === parentPid) {
try {
this.terminateProcess(p.pid);
} catch {
// Process may already be gone
}
}
}
}
} catch {
// Ignore ps/exec errors
}
}

public canRunCheck(isWindows: boolean): boolean {
if (isWindows) {
try {
Expand Down
Loading