From 2a335287eac7279c45c8534df81b5ddf7d7075f3 Mon Sep 17 00:00:00 2001 From: Romeo Dumitrescu Date: Tue, 30 Jun 2020 15:58:14 +0300 Subject: [PATCH] Fix unexpected sshd process exit by restarting it. (#33) --- src/ES.SFTP.Host/SSH/SSHService.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/ES.SFTP.Host/SSH/SSHService.cs b/src/ES.SFTP.Host/SSH/SSHService.cs index d6b1e27..8bb9662 100644 --- a/src/ES.SFTP.Host/SSH/SSHService.cs +++ b/src/ES.SFTP.Host/SSH/SSHService.cs @@ -25,6 +25,7 @@ public class SSHService : IHostedService, INotificationHandler logger, IMediator mediator) @@ -163,6 +164,21 @@ private async Task UpdateHostKeyFiles() private async Task StartOpenSSH() { _logger.LogInformation("Starting 'sshd' process"); + _serviceProcessExitAction = () => + { + _logger.LogWarning("'sshd' process has stopped. Restarting process."); + RestartService().Wait(); + }; + + void ListenForExit() + { + //Use this approach since the Exited event does not trigger on process crash + Task.Run(() => + { + _serverProcess.WaitForExit(); + _serviceProcessExitAction?.Invoke(); + }); + } _serverProcess = new Process { StartInfo = @@ -180,6 +196,7 @@ private async Task StartOpenSSH() _serverProcess.OutputDataReceived += OnSSHOutput; _serverProcess.ErrorDataReceived += OnSSHOutput; _serverProcess.Start(); + ListenForExit(); _serverProcess.BeginOutputReadLine(); _serverProcess.BeginErrorReadLine(); await _mediator.Publish(new ServerStartupEvent()); @@ -198,6 +215,7 @@ private async Task StopOpenSSH(bool force = false) if (_serverProcess != null) { _logger.LogDebug("Stopping 'sshd' process"); + _serviceProcessExitAction = null; _serverProcess.Kill(true); _serverProcess.OutputDataReceived -= OnSSHOutput; _serverProcess.ErrorDataReceived -= OnSSHOutput;