Skip to content

Commit 2a33528

Browse files
authored
Fix unexpected sshd process exit by restarting it. (#33)
1 parent 5938f87 commit 2a33528

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/ES.SFTP.Host/SSH/SSHService.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ public class SSHService : IHostedService, INotificationHandler<ConfigurationChan
2525
private readonly IMediator _mediator;
2626
private bool _loggingIgnoreNoIdentificationString;
2727
private Process _serverProcess;
28+
private Action _serviceProcessExitAction;
2829

2930

3031
public SSHService(ILogger<SSHService> logger, IMediator mediator)
@@ -163,6 +164,21 @@ private async Task UpdateHostKeyFiles()
163164
private async Task StartOpenSSH()
164165
{
165166
_logger.LogInformation("Starting 'sshd' process");
167+
_serviceProcessExitAction = () =>
168+
{
169+
_logger.LogWarning("'sshd' process has stopped. Restarting process.");
170+
RestartService().Wait();
171+
};
172+
173+
void ListenForExit()
174+
{
175+
//Use this approach since the Exited event does not trigger on process crash
176+
Task.Run(() =>
177+
{
178+
_serverProcess.WaitForExit();
179+
_serviceProcessExitAction?.Invoke();
180+
});
181+
}
166182
_serverProcess = new Process
167183
{
168184
StartInfo =
@@ -180,6 +196,7 @@ private async Task StartOpenSSH()
180196
_serverProcess.OutputDataReceived += OnSSHOutput;
181197
_serverProcess.ErrorDataReceived += OnSSHOutput;
182198
_serverProcess.Start();
199+
ListenForExit();
183200
_serverProcess.BeginOutputReadLine();
184201
_serverProcess.BeginErrorReadLine();
185202
await _mediator.Publish(new ServerStartupEvent());
@@ -198,6 +215,7 @@ private async Task StopOpenSSH(bool force = false)
198215
if (_serverProcess != null)
199216
{
200217
_logger.LogDebug("Stopping 'sshd' process");
218+
_serviceProcessExitAction = null;
201219
_serverProcess.Kill(true);
202220
_serverProcess.OutputDataReceived -= OnSSHOutput;
203221
_serverProcess.ErrorDataReceived -= OnSSHOutput;

0 commit comments

Comments
 (0)