Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix orphaned python processes on exit #2745

Merged
merged 11 commits into from
Apr 5, 2024
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
6 changes: 6 additions & 0 deletions backend/src/server_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,12 @@ async def setup_sse(request: Request):
break


@app.post("/shutdown")
async def shutdown(request: Request):
await close_server(request.app)
return json(success_response())


async def import_packages(
config: ServerConfig,
update_progress_cb: UpdateProgressFn,
Expand Down
16 changes: 11 additions & 5 deletions backend/src/server_process_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,25 @@ def __init__(self, flags: list[str]):
self._stop_event = threading.Event()

# Create a separate thread to read and print the output of the subprocess
threading.Thread(
self._reader_thread = threading.Thread(
target=self._read_output,
daemon=True,
name="output reader",
).start()
)
self._reader_thread.daemon = True
self._reader_thread.start()

def close(self):
logger.info("Closing worker process...")
self._stop_event.set()
self._process.terminate()
self._process.kill()
if self._process is not None:
self._process.terminate()
self._process.kill()
self._process = None
self._reader_thread = None

def _read_output(self):
if self._process.stdout is None:
if self._process is None or self._process.stdout is None:
return
for line in self._process.stdout:
if self._stop_event.is_set():
Expand Down
4 changes: 4 additions & 0 deletions src/common/Backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ export class Backend {
package: pkg.id,
});
}

shutdown(): Promise<void> {
return this.fetchJson('/shutdown', 'POST');
}
}

const backendCache = new Map<string, Backend>();
Expand Down
19 changes: 11 additions & 8 deletions src/main/backend/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ export class OwnedBackendProcess implements BaseBackendProcess {
this.errorListeners.push(listener);
}

clearErrorListeners() {
this.errorListeners = [];
}

private setNewProcess(process: ChildProcessWithoutNullStreams): void {
this.process = process;

Expand All @@ -136,9 +140,9 @@ export class OwnedBackendProcess implements BaseBackendProcess {
/**
* Kills the current backend process.
*
* @throws If the backend process could n
* @throws If the backend process couldn't exit
*/
kill() {
async kill() {
log.info('Attempting to kill backend...');

if (!this.process) {
Expand All @@ -153,11 +157,10 @@ export class OwnedBackendProcess implements BaseBackendProcess {
return;
}

await getBackend(this.url).shutdown();
if (this.process.kill()) {
this.process = undefined;
log.info('Successfully killed backend.');
} else {
throw new Error('Unable to the backend process. Kill returned false.');
}
}

Expand All @@ -166,16 +169,16 @@ export class OwnedBackendProcess implements BaseBackendProcess {
*
* This function is guaranteed to throw no errors, it will only log errors if any occur.
*/
tryKill() {
async tryKill() {
try {
this.kill();
await this.kill();
} catch (error) {
log.error('Error killing backend.', error);
}
}

restart() {
this.tryKill();
async restart() {
await this.tryKill();

const backend = OwnedBackendProcess.spawnProcess(this.port, this.python, this.env);
this.setNewProcess(backend);
Expand Down
19 changes: 13 additions & 6 deletions src/main/gui/main-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,12 +257,15 @@ const registerEventHandlerPostSetup = (
app.exit(1);
});

app.on('before-quit', () => backend.tryKill());
app.on('before-quit', () => {
backend.clearErrorListeners();
backend.tryKill().catch(log.error);
});
}

ipcMain.handle('restart-backend', () => {
ipcMain.handle('restart-backend', async () => {
if (backend.owned) {
backend.restart();
await backend.restart();
} else {
log.warn('Tried to restart non-owned backend');
}
Expand All @@ -281,10 +284,14 @@ const registerEventHandlerPostSetup = (

const restartChainner = (): void => {
if (backend.owned) {
backend.tryKill();
backend
.tryKill()
.finally(() => {
app.relaunch();
app.exit();
})
.catch(log.error);
}
app.relaunch();
app.exit();
};

ipcMain.on('reboot-after-save', () => {
Expand Down
Loading