Skip to content

Commit

Permalink
Fix unexpected sshd process exit by restarting it. (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
winromulus authored Jun 30, 2020
1 parent 5938f87 commit 2a33528
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/ES.SFTP.Host/SSH/SSHService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public class SSHService : IHostedService, INotificationHandler<ConfigurationChan
private readonly IMediator _mediator;
private bool _loggingIgnoreNoIdentificationString;
private Process _serverProcess;
private Action _serviceProcessExitAction;


public SSHService(ILogger<SSHService> logger, IMediator mediator)
Expand Down Expand Up @@ -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 =
Expand All @@ -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());
Expand All @@ -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;
Expand Down

0 comments on commit 2a33528

Please sign in to comment.