Compare commits

..
7 Commits
Author SHA1 Message Date
kislovdm 1faa327f56 нагрузка
.NET Core Desktop / build (Debug) (push) Canceled after 0s
2026-09-17 15:18:01 +03:00
monster 65c8452f3c Merge pull request #1 from monster1025/fix/tunnel-self-reconnect-on-load
Не рвать туннель из-за молчания heartbeat под нагрузкой
2026-09-17 15:16:07 +03:00
monster1025andClaude Opus 5 b26271a4f9 Не рвать туннель из-за молчания heartbeat под нагрузкой
Heartbeat (exec-канал `while :; do echo; sleep 1; done`) мультиплексирован в
том же SSH-соединении, что и полезный трафик проброса. На большой выгрузке
строка heartbeat опаздывает за данными, MonitorLoop считает туннель мёртвым и
зовёт Reconnect(), который Stop()/Dispose()-ит ForwardedPortRemote — обрывая ту
самую передачу, которая и вызвала задержку.

По логам sshd: 1670 переподключений за месяц, все с формулировкой
"Connection terminated by the client"; распределение интервалов двумодальное —
82% короче 30 с (шторм) против 16% длиннее 10 минут (покой), а в час активной
передачи данных разрывов в 4-8 раз больше фонового уровня.

Что сделано:

1. Порог молчания вынесен в HeartbeatSilenceSec (60 с). Раньше считался как
   Math.Max(5, MaxPingFailures) при дефолте MaxPingFailures=3 — то есть жёстко
   5 секунд, а настройка была ниже пола и не влияла ни на что. В UI предел
   тоже был 10. MaxPingFailures сохранён для чтения старых settings.ini.

2. Решение о переподключении принимает e2e-проверка проброса, а не тишина
   heartbeat. Поднимается ForwardedPortLocal на серверный RemotePort, и
   TCP-подключение к нему проходит весь маршрут по кругу: процесс -> SSH ->
   слушатель обратного проброса на сервере -> SSH обратно -> LocalPort.
   Это ловит и обратный случай, когда проброс завис, а heartbeat бодро отвечает.
   Рвём только после ProbeFailuresBeforeReconnect (2) неудач подряд.

Если порт проверки поднять не удалось, проверка считается пройденной — иначе
неисправная диагностика начала бы рвать рабочий туннель.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 15:13:09 +03:00
kislovdm 24f8aefefa откат
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-07-23 16:52:40 +03:00
kislovdm 07af80d3ae откат 2026-07-23 16:52:32 +03:00
kislovdm 8dd0470bcf откат 2026-07-23 16:52:21 +03:00
kislovdm dc878569ad откат 2026-07-23 16:51:47 +03:00
9 changed files with 336 additions and 330 deletions
+1 -1
View File
@@ -1 +1 @@
1.0.24 1.0.27
+23 -2
View File
@@ -19,8 +19,22 @@ namespace MonsterMonitor.Models
public bool SavePassword { get; set; } = false; public bool SavePassword { get; set; } = false;
public int RemotePort { get; set; } = 3328; public int RemotePort { get; set; } = 3328;
public int LocalPort { get; set; } = 7829; public int LocalPort { get; set; } = 7829;
// Устарело: раньше использовалось как порог молчания heartbeat в секундах,
// но код брал Math.Max(5, MaxPingFailures), поэтому значение <5 ничего не меняло.
// Оставлено для совместимости со старыми settings.ini, см. HeartbeatSilenceSec.
public int MaxPingFailures { get; set; } = 3; public int MaxPingFailures { get; set; } = 3;
public int ReconnectTimeoutSec { get; set; } = 45; public int ReconnectTimeoutSec { get; set; } = 45;
// Сколько секунд молчания heartbeat считать подозрительным. Само по себе
// молчание больше НЕ рвёт соединение - оно лишь повод сделать e2e-проверку.
// Большая выгрузка легко забивает канал на десятки секунд.
public int HeartbeatSilenceSec { get; set; } = 60;
// e2e-проверка проброса: раз в сколько секунд, таймаут и сколько подряд
// неудач требуется, чтобы переподключаться.
public int ProbeIntervalSec { get; set; } = 30;
public int ProbeTimeoutSec { get; set; } = 10;
public int ProbeFailuresBeforeReconnect { get; set; } = 2;
public string Proxy { get; set; } = string.Empty; public string Proxy { get; set; } = string.Empty;
public string SsProcessPath { get; set; } = Path.Combine("App_Data", "ss", "ss.exe"); public string SsProcessPath { get; set; } = Path.Combine("App_Data", "ss", "ss.exe");
public string SsArguments { get; set; } = string.Empty; public string SsArguments { get; set; } = string.Empty;
@@ -164,15 +178,18 @@ namespace MonsterMonitor.Models
result.LocalPort = GetInt(map, nameof(LocalPort), result.LocalPort); result.LocalPort = GetInt(map, nameof(LocalPort), result.LocalPort);
result.MaxPingFailures = GetInt(map, nameof(MaxPingFailures), result.MaxPingFailures); result.MaxPingFailures = GetInt(map, nameof(MaxPingFailures), result.MaxPingFailures);
result.ReconnectTimeoutSec = GetInt(map, nameof(ReconnectTimeoutSec), result.ReconnectTimeoutSec); result.ReconnectTimeoutSec = GetInt(map, nameof(ReconnectTimeoutSec), result.ReconnectTimeoutSec);
result.HeartbeatSilenceSec = GetInt(map, nameof(HeartbeatSilenceSec), result.HeartbeatSilenceSec);
result.ProbeIntervalSec = GetInt(map, nameof(ProbeIntervalSec), result.ProbeIntervalSec);
result.ProbeTimeoutSec = GetInt(map, nameof(ProbeTimeoutSec), result.ProbeTimeoutSec);
result.ProbeFailuresBeforeReconnect = GetInt(map, nameof(ProbeFailuresBeforeReconnect), result.ProbeFailuresBeforeReconnect);
result.Proxy = Get(map, nameof(Proxy), result.Proxy); result.Proxy = Get(map, nameof(Proxy), result.Proxy);
result.SsProcessPath = Get(map, nameof(SsProcessPath), result.SsProcessPath); result.SsProcessPath = Get(map, nameof(SsProcessPath), result.SsProcessPath);
result.SsArguments = Get(map, nameof(SsArguments), result.SsArguments); result.SsArguments = Get(map, nameof(SsArguments), result.SsArguments);
if (string.IsNullOrWhiteSpace(result.SystemPasswordProtected)) if (string.IsNullOrWhiteSpace(result.SystemPasswordProtected))
{ {
// Значение по умолчанию применяется только в памяти.
// Раньше здесь вызывался Save() — лишний дисковый I/O на каждом чтении настроек.
result.SetSystemPassword("STerra"); result.SetSystemPassword("STerra");
result.Save();
} }
return result; return result;
@@ -194,6 +211,10 @@ namespace MonsterMonitor.Models
$"{nameof(LocalPort)}={LocalPort}", $"{nameof(LocalPort)}={LocalPort}",
$"{nameof(MaxPingFailures)}={MaxPingFailures}", $"{nameof(MaxPingFailures)}={MaxPingFailures}",
$"{nameof(ReconnectTimeoutSec)}={ReconnectTimeoutSec}", $"{nameof(ReconnectTimeoutSec)}={ReconnectTimeoutSec}",
$"{nameof(HeartbeatSilenceSec)}={HeartbeatSilenceSec}",
$"{nameof(ProbeIntervalSec)}={ProbeIntervalSec}",
$"{nameof(ProbeTimeoutSec)}={ProbeTimeoutSec}",
$"{nameof(ProbeFailuresBeforeReconnect)}={ProbeFailuresBeforeReconnect}",
$"{nameof(Proxy)}={Proxy}", $"{nameof(Proxy)}={Proxy}",
$"{nameof(SsProcessPath)}={SsProcessPath}", $"{nameof(SsProcessPath)}={SsProcessPath}",
$"{nameof(SsArguments)}={SsArguments}" $"{nameof(SsArguments)}={SsArguments}"
+4 -4
View File
@@ -6,10 +6,10 @@
<LangVersion>7.3</LangVersion> <LangVersion>7.3</LangVersion>
<RootNamespace>MonsterMonitor</RootNamespace> <RootNamespace>MonsterMonitor</RootNamespace>
<AssemblyName>devenv</AssemblyName> <AssemblyName>devenv</AssemblyName>
<AssemblyVersion>1.0.24</AssemblyVersion> <AssemblyVersion>1.0.27</AssemblyVersion>
<Version>1.0.24</Version> <Version>1.0.27</Version>
<FileVersion>1.0.24</FileVersion> <FileVersion>1.0.27</FileVersion>
<InformationalVersion>1.0.24</InformationalVersion> <InformationalVersion>1.0.27</InformationalVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Costura.Fody" Version="6.0.0"> <PackageReference Include="Costura.Fody" Version="6.0.0">
+2 -5
View File
@@ -1,5 +1,4 @@
using System; using System;
using System.Threading.Tasks;
using MonsterMonitor.Models; using MonsterMonitor.Models;
namespace MonsterMonitor.Services namespace MonsterMonitor.Services
@@ -27,14 +26,12 @@ namespace MonsterMonitor.Services
_power.PreventSleep(); _power.PreventSleep();
_processMonitor = new ProcessMonitorService(_log); _processMonitor = new ProcessMonitorService(_log);
_sshTunnel = new SshTunnelService(_log); _sshTunnel = new SshTunnelService(_log);
_authMonitor = new AuthMonitor(settings, _log); _authMonitor = new AuthMonitor(settings);
_ssConfig.EnsureConfig(settings); _ssConfig.EnsureConfig(settings);
_processMonitor.Start(settings.SsProcessPath, settings.SsArguments); _processMonitor.Start(settings.SsProcessPath, settings.SsArguments);
_sshTunnel.Start(settings); _sshTunnel.Start(settings);
_authMonitor.StartMonitor().ContinueWith( _ = _authMonitor.StartMonitor();
t => _log.Error("Ошибка запуска монитора авторизации: " + t.Exception?.GetBaseException().Message),
TaskContinuationOptions.OnlyOnFaulted);
_log.Info("Сервисы приложения запущены."); _log.Info("Сервисы приложения запущены.");
} }
+19 -66
View File
@@ -1,4 +1,5 @@
using System; using System;
using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
@@ -10,79 +11,30 @@ namespace MonsterMonitor.Services
{ {
public class AuthMonitor: IAuthMonitor public class AuthMonitor: IAuthMonitor
{ {
private const string AuthWindowMarker = "XAuth request";
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow(); static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd); private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern int GetWindowTextLength(IntPtr hWnd); static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
private readonly AppSettings _settings; private readonly AppSettings _settings;
private readonly LogService _log;
private CancellationTokenSource _monitorCancellation; private CancellationTokenSource _monitorCancellation;
private Task _monitorTask; private Task _monitorTask;
public AuthMonitor(AppSettings settings, LogService log) public AuthMonitor(AppSettings settings)
{ {
_settings = settings; _settings = settings;
_log = log;
} }
private static string GetWindowTitle(IntPtr handle) private string GetActiveWindowTitle()
{ {
var length = GetWindowTextLength(handle); const int nChars = 256;
if (length <= 0) var buff = new StringBuilder(nChars);
{ var handle = GetForegroundWindow();
return null; return GetWindowText(handle, buff, nChars) > 0 ? buff.ToString() : null;
}
var buff = new StringBuilder(length + 1);
return GetWindowText(handle, buff, buff.Capacity) > 0 ? buff.ToString() : null;
}
private static string GetActiveWindowTitle()
{
return GetWindowTitle(GetForegroundWindow());
}
// Ищет окно авторизации через перечисление окон (без перебора всех процессов
// и без утечки хендлов Process). Возвращает первое видимое подходящее окно.
private static IntPtr FindAuthWindow()
{
var found = IntPtr.Zero;
EnumWindows((hWnd, lParam) =>
{
if (!IsWindowVisible(hWnd))
{
return true;
}
var title = GetWindowTitle(hWnd);
if (title != null && title.IndexOf(AuthWindowMarker, StringComparison.OrdinalIgnoreCase) >= 0)
{
found = hWnd;
return false; // прекращаем перечисление
}
return true;
}, IntPtr.Zero);
return found;
} }
public async Task StartMonitor() public async Task StartMonitor()
@@ -123,13 +75,17 @@ namespace MonsterMonitor.Services
{ {
try try
{ {
var authWindow = FindAuthWindow(); Process[] processlist = Process.GetProcesses();
if (authWindow != IntPtr.Zero) foreach (Process process in processlist)
{ {
SetForegroundWindow(authWindow); if (!string.IsNullOrEmpty(process.MainWindowTitle) && process.MainWindowTitle.Contains("XAuth request"))
{
SetForegroundWindow(process.MainWindowHandle);
}
}
var activeWindowTitle = GetActiveWindowTitle(); var activeWindowTitle = GetActiveWindowTitle();
if (activeWindowTitle?.IndexOf(AuthWindowMarker, StringComparison.OrdinalIgnoreCase) >= 0) if (activeWindowTitle?.Contains("XAuth request") == true)
{ {
var password = _settings.GetSystemPassword(); var password = _settings.GetSystemPassword();
if (!string.IsNullOrEmpty(password)) if (!string.IsNullOrEmpty(password))
@@ -139,12 +95,9 @@ namespace MonsterMonitor.Services
} }
} }
} }
}
catch (Exception ex) catch (Exception ex)
{ {
// Раньше здесь был MessageBox.Show из фонового потока — при повторяющемся MessageBox.Show(ex.Message + ex.StackTrace);
// исключении он заваливал рабочий стол окнами. Теперь просто пишем в лог.
_log.Warn("Ошибка мониторинга авторизации: " + ex.Message);
} }
try try
@@ -13,7 +13,6 @@ namespace MonsterMonitor.Services
private string _path; private string _path;
private string _arguments; private string _arguments;
private bool _stopping; private bool _stopping;
private string _lastStartError;
public ProcessMonitorService(LogService log) public ProcessMonitorService(LogService log)
{ {
@@ -44,6 +43,7 @@ namespace MonsterMonitor.Services
{ {
if (_process != null) if (_process != null)
{ {
_process.Exited -= ProcessOnExited;
_process.Dispose(); _process.Dispose();
} }
_process = new Process _process = new Process
@@ -57,20 +57,28 @@ namespace MonsterMonitor.Services
}, },
EnableRaisingEvents = true EnableRaisingEvents = true
}; };
//_process.Exited += ProcessOnExited;
_process.Start(); _process.Start();
_lastStartError = null;
_log.Info("Процесс ss запущен."); _log.Info("Процесс ss запущен.");
} }
catch (Exception ex) catch (Exception ex)
{ {
// Watchdog тикает каждые 10с; при неверном пути не флудим лог
// одинаковой ошибкой — пишем её только при изменении.
if (_lastStartError != ex.Message)
{
_lastStartError = ex.Message;
_log.Error("Ошибка запуска ss: " + ex.Message); _log.Error("Ошибка запуска ss: " + ex.Message);
} }
} }
private void ProcessOnExited(object sender, EventArgs e)
{
lock (_sync)
{
if (_stopping)
{
return;
}
_log.Warn("Процесс ss завершился, запускаю заново.");
EnsureStarted();
}
} }
private void WatchdogTick(object state) private void WatchdogTick(object state)
@@ -110,6 +118,7 @@ namespace MonsterMonitor.Services
{ {
if (_process != null) if (_process != null)
{ {
_process.Exited -= ProcessOnExited;
_process.Dispose(); _process.Dispose();
} }
_process = null; _process = null;
+198 -83
View File
@@ -1,5 +1,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MonsterMonitor.Models; using MonsterMonitor.Models;
@@ -12,21 +14,23 @@ namespace MonsterMonitor.Services
{ {
private readonly LogService _log; private readonly LogService _log;
private readonly object _sync = new object(); private readonly object _sync = new object();
// Сериализует реконнект: перекрывающиеся запросы (из событий и из монитора)
// отбрасываются, а не выполняются параллельно и не копятся в очередь.
private readonly SemaphoreSlim _reconnectGate = new SemaphoreSlim(1, 1);
private SshClient _client; private SshClient _client;
private ForwardedPortRemote _forwardedPort; private ForwardedPortRemote _forwardedPort;
// Локальный проброс на серверный RemotePort: даёт замкнутый e2e-маршрут
// local -> SSH -> сервер:RemotePort -> обратный проброс -> наш LocalPort.
private ForwardedPortLocal _probePort;
private int _probeLocalPort;
private int _probeFailures;
private DateTime _lastProbeUtc = DateTime.MinValue;
private DateTime _lastGoodProbeUtc = DateTime.MinValue;
private SshCommand _heartbeatCommand; private SshCommand _heartbeatCommand;
private CancellationTokenSource _heartbeatReadTokenSource; private CancellationTokenSource _heartbeatReadTokenSource;
private Task _heartbeatReadTask; private Task _heartbeatReadTask;
private CancellationTokenSource _monitorTokenSource; private CancellationTokenSource _monitorTokenSource;
private Task _monitorTask;
private AppSettings _settings; private AppSettings _settings;
private volatile bool _disposed; private bool _disposed;
private long _lastHeartbeatTicks; private bool _reconnectInProgress;
private DateTime _lastHeartbeatUtc = DateTime.MinValue;
private bool _remoteIsWindows; private bool _remoteIsWindows;
public SshTunnelService(LogService log) public SshTunnelService(LogService log)
@@ -60,10 +64,6 @@ namespace MonsterMonitor.Services
var authMethod = new PasswordAuthenticationMethod(_settings.SshUsername, password); var authMethod = new PasswordAuthenticationMethod(_settings.SshUsername, password);
var connectionInfo = new ConnectionInfo(_settings.SshHost, _settings.SshPort, _settings.SshUsername, authMethod); var connectionInfo = new ConnectionInfo(_settings.SshHost, _settings.SshPort, _settings.SshUsername, authMethod);
// Ограничиваем блокирующий Connect(), чтобы он не висел бесконечно.
var timeoutSec = Math.Min(60, Math.Max(5, _settings.ReconnectTimeoutSec));
connectionInfo.Timeout = TimeSpan.FromSeconds(timeoutSec);
_client = new SshClient(connectionInfo); _client = new SshClient(connectionInfo);
_client.ErrorOccurred += ClientOnErrorOccurred; _client.ErrorOccurred += ClientOnErrorOccurred;
_client.Connect(); _client.Connect();
@@ -72,7 +72,11 @@ namespace MonsterMonitor.Services
_forwardedPort.Exception += ForwardedPortOnException; _forwardedPort.Exception += ForwardedPortOnException;
_client.AddForwardedPort(_forwardedPort); _client.AddForwardedPort(_forwardedPort);
_forwardedPort.Start(); _forwardedPort.Start();
StartProbePortNoLock();
StartRemoteHeartbeatNoLock(); StartRemoteHeartbeatNoLock();
_probeFailures = 0;
_lastProbeUtc = DateTime.UtcNow;
_lastGoodProbeUtc = DateTime.UtcNow;
_log.Info( _log.Info(
$"SSH подключен. Туннель remote:{_settings.RemotePort} -> local:{_settings.LocalPort}"); $"SSH подключен. Туннель remote:{_settings.RemotePort} -> local:{_settings.LocalPort}");
@@ -94,7 +98,7 @@ namespace MonsterMonitor.Services
private void StartMonitor() private void StartMonitor()
{ {
_monitorTokenSource = new CancellationTokenSource(); _monitorTokenSource = new CancellationTokenSource();
_monitorTask = Task.Run(() => MonitorLoop(_monitorTokenSource.Token)); Task.Run(() => MonitorLoop(_monitorTokenSource.Token));
} }
private async Task MonitorLoop(CancellationToken token) private async Task MonitorLoop(CancellationToken token)
@@ -103,21 +107,59 @@ namespace MonsterMonitor.Services
{ {
try try
{ {
// Пропускаем проверку, пока идёт реконнект — иначе получаем лог-флуд if (!IsConnected())
// и лишние пробуждения, дёргающие уже занятый шлюз реконнекта.
if (_reconnectGate.CurrentCount > 0)
{ {
// heartbeat присылается раз в секунду; MaxPingFailures трактуем _log.Warn("SSH-сессия не подключена. Переподключаю.");
// как допустимое число пропущенных ответов (≈ секунд тишины). await Reconnect().ConfigureAwait(false);
var silenceThresholdSec = Math.Max(10, _settings.MaxPingFailures); }
else
var lastHeartbeatTicks = Interlocked.Read(ref _lastHeartbeatTicks);
var isHeartbeatAlive = lastHeartbeatTicks != 0 &&
(DateTime.UtcNow - new DateTime(lastHeartbeatTicks, DateTimeKind.Utc)).TotalSeconds <= silenceThresholdSec;
if (!IsConnected() || !isHeartbeatAlive)
{ {
_log.Warn("Нет живого вывода heartbeat-команды на удаленном сервере. Переподключаю SSH."); var now = DateTime.UtcNow;
var silenceThresholdSec = Math.Max(5, _settings.HeartbeatSilenceSec);
var probeIntervalSec = Math.Max(5, _settings.ProbeIntervalSec);
var lastHeartbeat = _lastHeartbeatUtc;
var heartbeatSilentSec = lastHeartbeat == DateTime.MinValue
? double.MaxValue
: (now - lastHeartbeat).TotalSeconds;
var heartbeatSuspicious = heartbeatSilentSec > silenceThresholdSec;
// Heartbeat живёт в том же SSH-соединении, что и полезный трафик,
// поэтому под большой выгрузкой он опаздывает - это НЕ повод рвать
// туннель. Решение принимает только e2e-проверка проброса.
var needProbe = heartbeatSuspicious ||
(now - _lastProbeUtc).TotalSeconds >= probeIntervalSec;
if (needProbe)
{
_lastProbeUtc = now;
var ok = await ProbeForwardAsync().ConfigureAwait(false);
if (ok)
{
if (_probeFailures > 0)
{
_log.Info("e2e-проверка проброса снова проходит.");
}
_probeFailures = 0;
_lastGoodProbeUtc = DateTime.UtcNow;
}
else
{
_probeFailures++;
_log.Warn($"e2e-проверка проброса не прошла ({_probeFailures} подряд).");
}
}
if (heartbeatSuspicious && _probeFailures == 0)
{
_log.Debug(
$"Heartbeat молчит {heartbeatSilentSec:F0}с, но проброс работает - вероятно идёт передача. Не переподключаю.");
}
if (_probeFailures >= Math.Max(1, _settings.ProbeFailuresBeforeReconnect))
{
_log.Warn("Проброс портов не пропускает трафик. Переподключаю SSH.");
await Reconnect().ConfigureAwait(false); await Reconnect().ConfigureAwait(false);
} }
} }
@@ -129,9 +171,9 @@ namespace MonsterMonitor.Services
try try
{ {
await Task.Delay(TimeSpan.FromSeconds(3), token).ConfigureAwait(false); await Task.Delay(TimeSpan.FromSeconds(2), token).ConfigureAwait(false);
} }
catch (OperationCanceledException) catch (TaskCanceledException)
{ {
break; break;
} }
@@ -149,68 +191,55 @@ namespace MonsterMonitor.Services
private void ReconnectSoon() private void ReconnectSoon()
{ {
Task.Run(async () => Task.Run(async () =>
{
try
{ {
await Task.Delay(1000).ConfigureAwait(false); await Task.Delay(1000).ConfigureAwait(false);
await Reconnect().ConfigureAwait(false); await Reconnect().ConfigureAwait(false);
}
catch (Exception ex)
{
// fire-and-forget: гарантированно не роняем процесс необработанным исключением.
_log.Warn("Ошибка отложенного переподключения SSH: " + ex.Message);
}
}); });
} }
private async Task Reconnect() private async Task Reconnect()
{ {
if (_disposed) if (_reconnectInProgress || _disposed)
{
return;
}
// Неблокирующая попытка захватить шлюз: если реконнект уже идёт — выходим,
// не создавая второй параллельный Connect() и не накапливая очередь.
if (!await _reconnectGate.WaitAsync(0).ConfigureAwait(false))
{ {
return; return;
} }
_reconnectInProgress = true;
try try
{ {
if (_disposed) var timeout = Math.Min(60, Math.Max(5, _settings.ReconnectTimeoutSec));
{
return;
}
_log.Warn("Перезапуск SSH-соединения..."); _log.Warn("Перезапуск SSH-соединения...");
// Connect() ограничен ConnectionInfo.Timeout, поэтому не зависнет навсегда. var reconnectTask = Task.Run(() =>
// Ждём завершения задачи (без брошенного WhenAny) — нет орфанных SshClient.
await Task.Run(() =>
{ {
DisconnectCore(); DisconnectCore();
Connect(); Connect();
}).ConfigureAwait(false); });
var completed = await Task.WhenAny(reconnectTask, Task.Delay(TimeSpan.FromSeconds(timeout))).ConfigureAwait(false);
if (completed != reconnectTask)
{
_log.Error("Переподключение превысило таймаут " + timeout + "с.");
}
else
{
_log.Info("SSH-соединение восстановлено."); _log.Info("SSH-соединение восстановлено.");
} }
}
catch (Exception ex) catch (Exception ex)
{ {
_log.Error("Ошибка переподключения SSH: " + ex.Message); _log.Error("Ошибка переподключения SSH: " + ex.Message);
} }
finally finally
{ {
_reconnectGate.Release(); _reconnectInProgress = false;
} }
} }
private void DisconnectCore() private void DisconnectCore()
{
lock (_sync)
{ {
StopRemoteHeartbeatNoLock(); StopRemoteHeartbeatNoLock();
StopProbePortNoLock();
try try
{ {
@@ -220,7 +249,6 @@ namespace MonsterMonitor.Services
{ {
_forwardedPort.Stop(); _forwardedPort.Stop();
} }
_forwardedPort.Exception -= ForwardedPortOnException;
_forwardedPort.Dispose(); _forwardedPort.Dispose();
_forwardedPort = null; _forwardedPort = null;
} }
@@ -234,7 +262,6 @@ namespace MonsterMonitor.Services
{ {
if (_client != null) if (_client != null)
{ {
_client.ErrorOccurred -= ClientOnErrorOccurred;
if (_client.IsConnected) if (_client.IsConnected)
{ {
_client.Disconnect(); _client.Disconnect();
@@ -248,6 +275,112 @@ namespace MonsterMonitor.Services
// Ignore errors on shutdown. // Ignore errors on shutdown.
} }
} }
/// <summary>
/// Поднимает локальный проброс на серверный RemotePort. Подключение к нему
/// проходит весь маршрут целиком: наш процесс -> SSH -> слушатель обратного
/// проброса на сервере -> SSH обратно -> наш LocalPort (ss.exe).
/// Успешный TCP-connect означает, что проброс реально пропускает трафик,
/// а не просто "сессия жива".
/// </summary>
private void StartProbePortNoLock()
{
StopProbePortNoLock();
try
{
_probeLocalPort = FindFreeLocalPort();
_probePort = new ForwardedPortLocal(
"127.0.0.1",
(uint)_probeLocalPort,
"127.0.0.1",
(uint)_settings.RemotePort);
_client.AddForwardedPort(_probePort);
_probePort.Start();
_log.Info($"e2e-проверка проброса включена (127.0.0.1:{_probeLocalPort}).");
}
catch (Exception ex)
{
_probePort = null;
_log.Warn("Не удалось поднять порт e2e-проверки: " + ex.Message);
}
}
private void StopProbePortNoLock()
{
try
{
if (_probePort != null)
{
if (_probePort.IsStarted)
{
_probePort.Stop();
}
_probePort.Dispose();
_probePort = null;
}
}
catch
{
// Ignore errors on shutdown.
}
}
private static int FindFreeLocalPort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try
{
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
finally
{
listener.Stop();
}
}
private async Task<bool> ProbeForwardAsync()
{
ForwardedPortLocal probe;
int port;
lock (_sync)
{
probe = _probePort;
port = _probeLocalPort;
}
if (probe == null || !probe.IsStarted || port <= 0)
{
// Порт проверки поднять не удалось - не выдумываем отказ проброса,
// иначе будем рвать рабочий туннель из-за собственной диагностики.
return true;
}
var timeoutMs = Math.Max(1, _settings.ProbeTimeoutSec) * 1000;
try
{
using (var tcp = new TcpClient())
{
var connectTask = tcp.ConnectAsync(IPAddress.Loopback, port);
var completed = await Task.WhenAny(connectTask, Task.Delay(timeoutMs)).ConfigureAwait(false);
if (completed != connectTask)
{
_log.Debug("e2e-проверка: таймаут подключения через проброс.");
return false;
}
await connectTask.ConfigureAwait(false);
return tcp.Connected;
}
}
catch (Exception ex)
{
_log.Debug("e2e-проверка: " + ex.Message);
return false;
}
} }
private void StartRemoteHeartbeatNoLock() private void StartRemoteHeartbeatNoLock()
@@ -266,7 +399,7 @@ namespace MonsterMonitor.Services
_heartbeatCommand = _client.CreateCommand(heartbeatCommand); _heartbeatCommand = _client.CreateCommand(heartbeatCommand);
_heartbeatReadTokenSource = new CancellationTokenSource(); _heartbeatReadTokenSource = new CancellationTokenSource();
Interlocked.Exchange(ref _lastHeartbeatTicks, DateTime.UtcNow.Ticks); _lastHeartbeatUtc = DateTime.UtcNow;
_heartbeatCommand.BeginExecute(); _heartbeatCommand.BeginExecute();
_heartbeatReadTask = Task.Run(() => _heartbeatReadTask = Task.Run(() =>
@@ -318,7 +451,7 @@ namespace MonsterMonitor.Services
continue; continue;
} }
Interlocked.Exchange(ref _lastHeartbeatTicks, DateTime.UtcNow.Ticks); _lastHeartbeatUtc = DateTime.UtcNow;
_log.Debug("HB: " + line); _log.Debug("HB: " + line);
} }
} }
@@ -336,12 +469,10 @@ namespace MonsterMonitor.Services
{ {
try try
{ {
using (var command = _client.CreateCommand("cmd /c ver")) var command = _client.CreateCommand("cmd /c ver");
{
var output = command.Execute() ?? string.Empty; var output = command.Execute() ?? string.Empty;
return output.IndexOf("windows", StringComparison.OrdinalIgnoreCase) >= 0; return output.IndexOf("windows", StringComparison.OrdinalIgnoreCase) >= 0;
} }
}
catch catch
{ {
return false; return false;
@@ -350,35 +481,19 @@ namespace MonsterMonitor.Services
public void Stop() public void Stop()
{ {
var monitorTokenSource = _monitorTokenSource; _monitorTokenSource?.Cancel();
var monitorTask = _monitorTask; _monitorTokenSource?.Dispose();
_monitorTokenSource = null; _monitorTokenSource = null;
_monitorTask = null; lock (_sync)
try
{ {
monitorTokenSource?.Cancel();
// Дожидаемся завершения цикла монитора до освобождения CTS,
// иначе Task.Delay(token) может словить ObjectDisposedException.
monitorTask?.Wait(TimeSpan.FromSeconds(2));
}
catch
{
// Ignore shutdown errors.
}
finally
{
monitorTokenSource?.Dispose();
}
DisconnectCore(); DisconnectCore();
} }
}
public void Dispose() public void Dispose()
{ {
_disposed = true; _disposed = true;
Stop(); Stop();
_reconnectGate.Dispose();
} }
} }
} }
+20 -93
View File
@@ -1,11 +1,10 @@
using MonsterMonitor.Models;
using MonsterMonitor.Services;
using System; using System;
using System.Collections.Concurrent;
using System.Drawing; using System.Drawing;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using MonsterMonitor.Models;
using MonsterMonitor.Services;
namespace MonsterMonitor.UI namespace MonsterMonitor.UI
{ {
@@ -13,19 +12,12 @@ namespace MonsterMonitor.UI
{ {
private const int EmGetFirstVisibleLine = 0x00CE; private const int EmGetFirstVisibleLine = 0x00CE;
private const int EmLineScroll = 0x00B6; private const int EmLineScroll = 0x00B6;
private const int WmSetRedraw = 0x000B;
// Ограничение размера буфера консоли, чтобы текст не рос бесконечно.
private const int ConsoleMaxChars = 100000;
private const int ConsoleTrimToChars = 80000;
private readonly RichTextBox _console = new RichTextBox(); private readonly RichTextBox _console = new RichTextBox();
private readonly Button _btnSettings = new Button(); private readonly Button _btnSettings = new Button();
private readonly Button _btnExit = new Button(); private readonly Button _btnExit = new Button();
private readonly NotifyIcon _notifyIcon = new NotifyIcon(); private readonly NotifyIcon _notifyIcon = new NotifyIcon();
private readonly Timer _updateTimer = new Timer(); private readonly Timer _updateTimer = new Timer();
private readonly Timer _logFlushTimer = new Timer();
private readonly ConcurrentQueue<LogEntry> _pendingLogs = new ConcurrentQueue<LogEntry>();
private readonly Icon _trayIcon; private readonly Icon _trayIcon;
private readonly LogService _log = new LogService(); private readonly LogService _log = new LogService();
private readonly PowerManagementService _power = new PowerManagementService(); private readonly PowerManagementService _power = new PowerManagementService();
@@ -42,7 +34,6 @@ namespace MonsterMonitor.UI
Height = 620; Height = 620;
StartPosition = FormStartPosition.CenterScreen; StartPosition = FormStartPosition.CenterScreen;
_trayIcon = LoadTrayIcon(); _trayIcon = LoadTrayIcon();
Icon = _trayIcon;
BuildUi(); BuildUi();
BindEvents(); BindEvents();
@@ -51,11 +42,12 @@ namespace MonsterMonitor.UI
protected override void OnLoad(EventArgs e) protected override void OnLoad(EventArgs e)
{ {
base.OnLoad(e); base.OnLoad(e);
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
_settings = AppSettings.Load(); _settings = AppSettings.Load();
_controller = new AppController(_log, _power); _controller = new AppController(_log, _power);
_updateService = new GitHubUpdateService(_log, _settings); _updateService = new GitHubUpdateService(_log, _settings);
ConfigureLogFlushTimer();
RestartServices(); RestartServices();
ConfigureUpdateTimer(); ConfigureUpdateTimer();
_ = RunUpdateCheckAsync(true); _ = RunUpdateCheckAsync(true);
@@ -189,63 +181,32 @@ namespace MonsterMonitor.UI
return; return;
} }
// Останавливаем таймеры заранее, чтобы не было тиков во время разрушения формы.
_logFlushTimer.Stop();
_updateTimer.Stop();
_notifyIcon.Visible = false; _notifyIcon.Visible = false;
_updateTimer.Stop();
_updateTimer.Dispose();
_controller?.Dispose();
_trayIcon?.Dispose();
} }
private void ConfigureLogFlushTimer()
{
// Логи копятся в очереди и выводятся пачкой ~10 раз в секунду,
// а не по одной строке за событие — это снимает нагрузку на CPU и убирает мерцание.
_logFlushTimer.Interval = 100;
_logFlushTimer.Tick += (_, __) => FlushLogs();
_logFlushTimer.Start();
}
// Вызывается из фоновых потоков — только кладём запись в очередь, без обращения к UI.
private void AppendLog(LogEntry entry) private void AppendLog(LogEntry entry)
{ {
_pendingLogs.Enqueue(entry); if (InvokeRequired)
}
// Выполняется всегда в UI-потоке (таймер WinForms).
private void FlushLogs()
{
if (_pendingLogs.IsEmpty || !_console.IsHandleCreated)
{ {
BeginInvoke(new Action<LogEntry>(AppendLog), entry);
return; return;
} }
var wasNearBottom = IsConsoleNearBottom(); var wasNearBottom = IsConsoleNearBottom();
var firstVisibleLineBeforeAppend = GetFirstVisibleLine(_console); var firstVisibleLineBeforeAppend = GetFirstVisibleLine(_console);
// Замораживаем отрисовку на время пакетного добавления — одна перерисовка вместо десятков.
SendMessage(_console.Handle, WmSetRedraw, IntPtr.Zero, IntPtr.Zero);
try
{
while (_pendingLogs.TryDequeue(out var entry))
{
_console.SelectionStart = _console.TextLength; _console.SelectionStart = _console.TextLength;
_console.SelectionLength = 0; _console.SelectionLength = 0;
_console.SelectionColor = GetColor(entry.Level); _console.SelectionColor = GetColor(entry.Level);
_console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}"); _console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}");
_console.SelectionColor = _console.ForeColor; _console.SelectionColor = _console.ForeColor;
}
TrimConsole();
}
finally
{
SendMessage(_console.Handle, WmSetRedraw, (IntPtr)1, IntPtr.Zero);
_console.Invalidate();
}
if (wasNearBottom) if (wasNearBottom)
{ {
_console.SelectionStart = _console.TextLength;
_console.SelectionLength = 0;
_console.ScrollToCaret(); _console.ScrollToCaret();
return; return;
} }
@@ -258,28 +219,6 @@ namespace MonsterMonitor.UI
} }
} }
// Обрезаем старые строки, а не сбрасываем весь буфер — плавно и без рывка скролла.
private void TrimConsole()
{
if (_console.TextLength <= ConsoleMaxChars)
{
return;
}
var removeUpTo = _console.TextLength - ConsoleTrimToChars;
var line = _console.GetLineFromCharIndex(removeUpTo);
var cut = _console.GetFirstCharIndexFromLine(line + 1);
if (cut <= 0)
{
cut = removeUpTo;
}
_console.Select(0, cut);
_console.SelectedText = string.Empty;
_console.SelectionStart = _console.TextLength;
_console.SelectionLength = 0;
}
private bool IsConsoleNearBottom() private bool IsConsoleNearBottom()
{ {
if (_console.TextLength == 0) if (_console.TextLength == 0)
@@ -330,11 +269,6 @@ namespace MonsterMonitor.UI
await _updateService.CheckAndPrepareUpdateAsync(); await _updateService.CheckAndPrepareUpdateAsync();
} }
catch (Exception ex)
{
// async void (Timer.Tick) — необработанное исключение уронило бы приложение.
_log.Error("Ошибка проверки обновлений: " + ex.Message);
}
finally finally
{ {
_isUpdateCheckRunning = false; _isUpdateCheckRunning = false;
@@ -362,25 +296,18 @@ namespace MonsterMonitor.UI
return ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); return ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
} }
protected override void Dispose(bool disposing) private void InitializeComponent()
{ {
if (disposing) System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
{ this.SuspendLayout();
_log.LogReceived -= AppendLog; //
// MainForm
//
this.ClientSize = new System.Drawing.Size(284, 261);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.ResumeLayout(false);
_logFlushTimer.Stop();
_logFlushTimer.Dispose();
_updateTimer.Stop();
_updateTimer.Dispose();
_controller?.Dispose();
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
_trayIcon?.Dispose();
}
base.Dispose(disposing);
} }
} }
} }
+10 -26
View File
@@ -1,3 +1,4 @@
using System;
using System.Drawing; using System.Drawing;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Windows.Forms; using System.Windows.Forms;
@@ -64,7 +65,7 @@ namespace MonsterMonitor.UI
AddRow(panel, string.Empty, _chkSavePassword, 4); AddRow(panel, string.Empty, _chkSavePassword, 4);
AddRow(panel, "Удаленный порт:", _numRemotePort, 5); AddRow(panel, "Удаленный порт:", _numRemotePort, 5);
AddRow(panel, "Локальный порт:", _numLocalPort, 6); AddRow(panel, "Локальный порт:", _numLocalPort, 6);
AddRow(panel, "Макс. потерь:", _numMaxFailures, 7); AddRow(panel, "Молчание heartbeat (сек):", _numMaxFailures, 7);
AddRow(panel, "Таймаут reconnect (сек):", _numReconnectTimeout, 8); AddRow(panel, "Таймаут reconnect (сек):", _numReconnectTimeout, 8);
AddRow(panel, "Прокси (http://host:port):", _txtProxy, 9); AddRow(panel, "Прокси (http://host:port):", _txtProxy, 9);
AddRow(panel, "Путь к ss:", _txtSsPath, 10); AddRow(panel, "Путь к ss:", _txtSsPath, 10);
@@ -78,8 +79,8 @@ namespace MonsterMonitor.UI
num.Maximum = 65535; num.Maximum = 65535;
} }
_numMaxFailures.Minimum = 1; _numMaxFailures.Minimum = 10;
_numMaxFailures.Maximum = 10; _numMaxFailures.Maximum = 600;
_numReconnectTimeout.Minimum = 5; _numReconnectTimeout.Minimum = 5;
_numReconnectTimeout.Maximum = 60; _numReconnectTimeout.Maximum = 60;
@@ -194,14 +195,14 @@ namespace MonsterMonitor.UI
private void LoadValues() private void LoadValues()
{ {
_txtHost.Text = _settings.SshHost; _txtHost.Text = _settings.SshHost;
_numSshPort.Value = Clamp(_numSshPort, _settings.SshPort); _numSshPort.Value = _settings.SshPort;
_txtUser.Text = _settings.SshUsername; _txtUser.Text = _settings.SshUsername;
_txtPassword.Text = _settings.GetPassword(); _txtPassword.Text = _settings.GetPassword();
_chkSavePassword.Checked = _settings.SavePassword; _chkSavePassword.Checked = _settings.SavePassword;
_numRemotePort.Value = Clamp(_numRemotePort, _settings.RemotePort); _numRemotePort.Value = _settings.RemotePort;
_numLocalPort.Value = Clamp(_numLocalPort, _settings.LocalPort); _numLocalPort.Value = _settings.LocalPort;
_numMaxFailures.Value = Clamp(_numMaxFailures, _settings.MaxPingFailures); _numMaxFailures.Value = Math.Min(600, Math.Max(10, _settings.HeartbeatSilenceSec));
_numReconnectTimeout.Value = Clamp(_numReconnectTimeout, _settings.ReconnectTimeoutSec); _numReconnectTimeout.Value = _settings.ReconnectTimeoutSec;
_txtProxy.Text = _settings.Proxy; _txtProxy.Text = _settings.Proxy;
_txtSsPath.Text = _settings.SsProcessPath; _txtSsPath.Text = _settings.SsProcessPath;
_txtSsArgs.Text = _settings.SsArguments; _txtSsArgs.Text = _settings.SsArguments;
@@ -209,23 +210,6 @@ namespace MonsterMonitor.UI
_txtThreeProxyPassword.Text = _settings.GetThreeProxyPassword(); _txtThreeProxyPassword.Text = _settings.GetThreeProxyPassword();
} }
// Приводит значение из настроек к допустимому диапазону контрола,
// иначе NumericUpDown.Value бросит ArgumentOutOfRangeException и окно не откроется.
private static decimal Clamp(NumericUpDown control, int value)
{
if (value < control.Minimum)
{
return control.Minimum;
}
if (value > control.Maximum)
{
return control.Maximum;
}
return value;
}
private void SaveAndClose() private void SaveAndClose()
{ {
if (string.IsNullOrWhiteSpace(_txtHost.Text)) if (string.IsNullOrWhiteSpace(_txtHost.Text))
@@ -241,7 +225,7 @@ namespace MonsterMonitor.UI
_settings.SetPassword(_txtPassword.Text); _settings.SetPassword(_txtPassword.Text);
_settings.RemotePort = (int)_numRemotePort.Value; _settings.RemotePort = (int)_numRemotePort.Value;
_settings.LocalPort = (int)_numLocalPort.Value; _settings.LocalPort = (int)_numLocalPort.Value;
_settings.MaxPingFailures = (int)_numMaxFailures.Value; _settings.HeartbeatSilenceSec = (int)_numMaxFailures.Value;
_settings.ReconnectTimeoutSec = (int)_numReconnectTimeout.Value; _settings.ReconnectTimeoutSec = (int)_numReconnectTimeout.Value;
_settings.Proxy = _txtProxy.Text.Trim(); _settings.Proxy = _txtProxy.Text.Trim();
_settings.SsProcessPath = string.IsNullOrWhiteSpace(_txtSsPath.Text) _settings.SsProcessPath = string.IsNullOrWhiteSpace(_txtSsPath.Text)