Skip to content

Commit 21fd349

Browse files
committed
fix(connection): harden SSH tunnel recovery
Co-authored-by: Copilot App <[email protected]> Copilot-Session: 7b9bc681-ce19-4a8b-b06c-94efb63a5f9f
1 parent 0fa8a2e commit 21fd349

8 files changed

Lines changed: 430 additions & 49 deletions

File tree

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -884,7 +884,8 @@ public async Task<bool> RecoverSshTunnelAsync(SshTunnelExit tunnelExit)
884884
try
885885
{
886886
var activeGateway = _registry.GetActive();
887-
if (activeGateway?.SshTunnel != tunnelExit.Tunnel ||
887+
if (tunnelExit.Owner != SshTunnelOwner.GatewayConnectionManager ||
888+
activeGateway?.SshTunnel != tunnelExit.Tunnel ||
888889
!IsAutomaticReconnectAllowed(activeGateway.Id) ||
889890
_tunnelManager?.IsRestartPending(tunnelExit) != true)
890891
{
@@ -907,6 +908,8 @@ public async Task<bool> RecoverSshTunnelAsync(SshTunnelExit tunnelExit)
907908

908909
await ConnectCoreAsync(activeGateway.Id, "reconnect");
909910
return _stateMachine.Current.OperatorState is not RoleConnectionState.Error
911+
&& _registry.GetById(activeGateway.Id) is not null
912+
&& _tunnelManager?.IsActive == true
910913
&& string.Equals(_registry.ActiveGatewayId, activeGateway.Id, StringComparison.Ordinal);
911914
}
912915
finally
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
namespace OpenClaw.Connection;
2+
3+
public sealed class SshTunnelRecoveryBudget
4+
{
5+
private static readonly TimeSpan AttemptWindow = TimeSpan.FromMinutes(5);
6+
private static readonly TimeSpan[] RetryDelays =
7+
[
8+
TimeSpan.FromSeconds(3),
9+
TimeSpan.FromSeconds(10),
10+
TimeSpan.FromSeconds(30)
11+
];
12+
13+
private readonly object _gate = new();
14+
private readonly Queue<DateTimeOffset> _attempts = new();
15+
private SshTunnelConfig? _tunnel;
16+
private SshTunnelOwner _owner;
17+
18+
public bool TryReserve(
19+
SshTunnelExit tunnelExit,
20+
DateTimeOffset now,
21+
out TimeSpan delay)
22+
{
23+
lock (_gate)
24+
{
25+
if (!Equals(_tunnel, tunnelExit.Tunnel) || _owner != tunnelExit.Owner)
26+
{
27+
_attempts.Clear();
28+
_tunnel = tunnelExit.Tunnel;
29+
_owner = tunnelExit.Owner;
30+
}
31+
32+
while (_attempts.TryPeek(out var attempt) && now - attempt >= AttemptWindow)
33+
_attempts.Dequeue();
34+
35+
if (_attempts.Count >= RetryDelays.Length)
36+
{
37+
delay = TimeSpan.Zero;
38+
return false;
39+
}
40+
41+
delay = RetryDelays[_attempts.Count];
42+
_attempts.Enqueue(now);
43+
return true;
44+
}
45+
}
46+
47+
public void ReportRecovered(SshTunnelExit tunnelExit)
48+
{
49+
lock (_gate)
50+
{
51+
if (!Equals(_tunnel, tunnelExit.Tunnel) || _owner != tunnelExit.Owner)
52+
return;
53+
54+
ResetLocked();
55+
}
56+
}
57+
58+
public void Reset()
59+
{
60+
lock (_gate)
61+
ResetLocked();
62+
}
63+
64+
private void ResetLocked()
65+
{
66+
_attempts.Clear();
67+
_tunnel = null;
68+
_owner = SshTunnelOwner.Unspecified;
69+
}
70+
}

‎src/OpenClaw.Connection/SshTunnelService.cs‎

Lines changed: 96 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public sealed class SshTunnelService : ISshTunnelManager
1515
private Process? _process;
1616
private bool _processStarted;
1717
private SshTunnelConfig? _currentConfig;
18+
private SshTunnelOwner _currentOwner;
1819
private string? _lastSpec;
1920
private long _lifecycleGeneration;
2021

@@ -98,30 +99,72 @@ public bool IsRestartPending(SshTunnelExit tunnelExit)
9899
{
99100
return tunnelExit.Generation == _lifecycleGeneration &&
100101
Equals(_currentConfig, tunnelExit.Tunnel) &&
102+
tunnelExit.Owner == _currentOwner &&
101103
!IsRunningLocked() &&
102104
Status == TunnelStatus.Restarting;
103105
}
104106
}
105107

108+
public bool TryMarkRecoveryFailed(SshTunnelExit tunnelExit, string reason)
109+
{
110+
lock (_stateLock)
111+
{
112+
if (!IsRestartPendingLocked(tunnelExit))
113+
return false;
114+
115+
Status = TunnelStatus.Failed;
116+
LastError = reason;
117+
return true;
118+
}
119+
}
120+
121+
public bool TryRestart(SshTunnelExit tunnelExit)
122+
{
123+
lock (_operationLock)
124+
{
125+
lock (_stateLock)
126+
{
127+
if (!IsRestartPendingLocked(tunnelExit))
128+
return false;
129+
}
130+
131+
EnsureStartedCore(tunnelExit.Tunnel, tunnelExit.Owner);
132+
return true;
133+
}
134+
}
135+
106136
public void EnsureStarted(string user, string host, int remotePort, int localPort)
107137
=> EnsureStarted(user, host, remotePort, localPort, includeBrowserProxyForward: false);
108138

109139
public void EnsureStarted(string user, string host, int remotePort, int localPort, bool includeBrowserProxyForward)
110140
=> EnsureStarted(user, host, remotePort, localPort, includeBrowserProxyForward, sshPort: 22);
111141

112142
public void EnsureStarted(string user, string host, int remotePort, int localPort, bool includeBrowserProxyForward, int sshPort)
143+
=> EnsureStartedCore(
144+
new SshTunnelConfig(user, host, remotePort, localPort, includeBrowserProxyForward, sshPort),
145+
SshTunnelOwner.Settings);
146+
147+
private void EnsureStartedCore(SshTunnelConfig tunnel, SshTunnelOwner owner)
113148
{
114149
lock (_operationLock)
115150
{
116-
user = user.Trim();
117-
host = host.Trim();
118-
119-
var spec = BuildSpec(user, host, remotePort, localPort, includeBrowserProxyForward, sshPort);
151+
var user = tunnel.User.Trim();
152+
var host = tunnel.Host.Trim();
153+
tunnel = tunnel with { User = user, Host = host };
154+
155+
var spec = BuildSpec(
156+
user,
157+
host,
158+
tunnel.RemotePort,
159+
tunnel.LocalPort,
160+
tunnel.IncludeBrowserProxyForward,
161+
tunnel.SshPort);
120162

121163
lock (_stateLock)
122164
{
123165
if (IsRunningLocked() && string.Equals(_lastSpec, spec, StringComparison.Ordinal))
124166
{
167+
_currentOwner = ResolveOwnerForReuse(_currentOwner, owner);
125168
Status = TunnelStatus.Up;
126169
return;
127170
}
@@ -132,7 +175,7 @@ public void EnsureStarted(string user, string host, int remotePort, int localPor
132175
{
133176
Status = TunnelStatus.Starting;
134177
}
135-
StartProcess(user, host, remotePort, localPort, includeBrowserProxyForward, sshPort, spec);
178+
StartProcess(tunnel, owner, spec);
136179
}
137180
}
138181

@@ -156,6 +199,7 @@ private void StopLocked()
156199
_process = null;
157200
_processStarted = false;
158201
_currentConfig = null;
202+
_currentOwner = SshTunnelOwner.Unspecified;
159203
_lastSpec = null;
160204
CurrentBrowserProxyLocalPort = 0;
161205
CurrentBrowserProxyRemotePort = 0;
@@ -200,22 +244,14 @@ public void ResetNotConfigured()
200244
}
201245
}
202246

203-
private void StartProcess(
204-
string user,
205-
string host,
206-
int remotePort,
207-
int localPort,
208-
bool includeBrowserProxyForward,
209-
int sshPort,
210-
string spec)
247+
private void StartProcess(SshTunnelConfig tunnel, SshTunnelOwner owner, string spec)
211248
{
212-
var tunnel = new SshTunnelConfig(
213-
user,
214-
host,
215-
remotePort,
216-
localPort,
217-
includeBrowserProxyForward,
218-
sshPort);
249+
var user = tunnel.User;
250+
var host = tunnel.Host;
251+
var remotePort = tunnel.RemotePort;
252+
var localPort = tunnel.LocalPort;
253+
var includeBrowserProxyForward = tunnel.IncludeBrowserProxyForward;
254+
var sshPort = tunnel.SshPort;
219255
var psi = new ProcessStartInfo
220256
{
221257
FileName = "ssh",
@@ -250,13 +286,23 @@ private void StartProcess(
250286

251287
process.Exited += (_, _) =>
252288
{
253-
var exitCode = process.ExitCode;
254289
SshTunnelExit? tunnelExit = null;
255290
lock (_stateLock)
256291
{
257292
if (generation == _lifecycleGeneration &&
258293
ReferenceEquals(_process, process))
259294
{
295+
int exitCode;
296+
try
297+
{
298+
exitCode = process.ExitCode;
299+
}
300+
catch (Exception ex)
301+
{
302+
_logger.Debug($"Ignoring SSH tunnel exit after process disposal: {ex.Message}");
303+
return;
304+
}
305+
260306
LastError = $"SSH tunnel exited unexpectedly with code {exitCode}.";
261307
StartedAtUtc = null;
262308
Status = TunnelStatus.Failed;
@@ -265,17 +311,17 @@ private void StartProcess(
265311
_lastSpec = null;
266312
CurrentBrowserProxyLocalPort = 0;
267313
CurrentBrowserProxyRemotePort = 0;
268-
tunnelExit = new SshTunnelExit(exitCode, tunnel, generation);
314+
tunnelExit = new SshTunnelExit(exitCode, tunnel, generation, _currentOwner);
269315
}
270316
}
271317

272318
if (tunnelExit == null)
273319
{
274-
_logger.Debug($"Ignoring stale SSH tunnel exit (code {exitCode})");
320+
_logger.Debug("Ignoring stale SSH tunnel exit");
275321
return;
276322
}
277323

278-
_logger.Warn($"SSH tunnel exited unexpectedly (code {exitCode})");
324+
_logger.Warn($"SSH tunnel exited unexpectedly (code {tunnelExit.ExitCode})");
279325
try { process.Dispose(); }
280326
catch (Exception disposeEx) { _logger.Debug($"SshTunnelService: process dispose after unexpected exit failed: {disposeEx.Message}"); }
281327
TunnelExited?.Invoke(this, tunnelExit);
@@ -287,6 +333,7 @@ private void StartProcess(
287333
_process = process;
288334
_processStarted = false;
289335
_currentConfig = tunnel;
336+
_currentOwner = owner;
290337
_lastSpec = spec;
291338
}
292339

@@ -337,6 +384,7 @@ private void StartProcess(
337384
_process = null;
338385
_processStarted = false;
339386
_currentConfig = null;
387+
_currentOwner = SshTunnelOwner.Unspecified;
340388
_lastSpec = null;
341389
}
342390
}
@@ -374,6 +422,20 @@ private void StartProcess(
374422

375423
private bool IsRunningLocked() => _processStarted && _process is { HasExited: false };
376424

425+
private bool IsRestartPendingLocked(SshTunnelExit tunnelExit) =>
426+
tunnelExit.Generation == _lifecycleGeneration &&
427+
Equals(_currentConfig, tunnelExit.Tunnel) &&
428+
tunnelExit.Owner == _currentOwner &&
429+
!IsRunningLocked() &&
430+
Status == TunnelStatus.Restarting;
431+
432+
internal static SshTunnelOwner ResolveOwnerForReuse(
433+
SshTunnelOwner currentOwner,
434+
SshTunnelOwner requestedOwner) =>
435+
currentOwner == SshTunnelOwner.GatewayConnectionManager
436+
? currentOwner
437+
: requestedOwner;
438+
377439
private void MarkRestartingLocked(int exitCode)
378440
{
379441
Status = TunnelStatus.Restarting;
@@ -390,7 +452,7 @@ public void Dispose()
390452

391453
public Task<string> StartAsync(SshTunnelConfig config, CancellationToken ct)
392454
{
393-
EnsureStarted(config.User, config.Host, config.RemotePort, config.LocalPort, config.IncludeBrowserProxyForward, config.SshPort);
455+
EnsureStartedCore(config, SshTunnelOwner.GatewayConnectionManager);
394456
var localUrl = $"ws://localhost:{config.LocalPort}";
395457
return Task.FromResult(localUrl);
396458
}
@@ -405,4 +467,12 @@ public Task StopAsync()
405467
public sealed record SshTunnelExit(
406468
int ExitCode,
407469
SshTunnelConfig Tunnel,
408-
long Generation);
470+
long Generation,
471+
SshTunnelOwner Owner = SshTunnelOwner.Unspecified);
472+
473+
public enum SshTunnelOwner
474+
{
475+
Unspecified = 0,
476+
Settings,
477+
GatewayConnectionManager
478+
}

0 commit comments

Comments
 (0)