Compare commits

..
20 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
kislovdm 724644c8eb ++ 2026-04-30 12:55:19 +03:00
kislovdm 23768dbe0e Исправление скрола логов
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-30 12:33:00 +03:00
kislovdm ace23b954e auth
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:46:52 +03:00
kislovdm a4fc8c047a auth
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:44:48 +03:00
kislovdm 5a2639f96c reconnect
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:37:43 +03:00
kislovdm fbd94ae1e6 readme
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:25:02 +03:00
kislovdm cf01546b0b maxconn
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:19:18 +03:00
kislovdm ec80bea024 maxconn
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:14:42 +03:00
kislovdm b88006f02d maxconn
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:11:03 +03:00
kislovdm c5ac1681f2 maxconn
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:04:30 +03:00
kislovdm 06f2ebb1ac maxconn
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 01:02:02 +03:00
kislovdm 9912ca8ba4 maxconn
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 00:57:20 +03:00
kislovdm 427f16cde0 maxconn
.NET Core Desktop / build (Debug) (push) Has been cancelled
2026-04-27 00:53:56 +03:00
13 changed files with 541 additions and 50 deletions
+2 -2
View File
@@ -43,7 +43,7 @@ jobs:
id: create_release id: create_release
uses: actions/create-release@v1 uses: actions/create-release@v1
env: env:
GITHUB_TOKEN: ${{ secrets.CUSTOM_GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
tag_name: ${{ github.ref }} tag_name: ${{ github.ref }}
release_name: ${{ github.ref }} release_name: ${{ github.ref }}
@@ -54,7 +54,7 @@ jobs:
id: upload-release-asset id: upload-release-asset
uses: actions/upload-release-asset@v1 uses: actions/upload-release-asset@v1
env: env:
GITHUB_TOKEN: ${{ secrets.CUSTOM_GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: /app/MonsterMonitor.zip asset_path: /app/MonsterMonitor.zip
+1 -1
View File
@@ -1 +1 @@
1.0.10 1.0.27
+79 -1
View File
@@ -1 +1,79 @@
"# monster_monitor_v2" # Monster Monitor v2
Windows-приложение (WinForms, .NET Framework 4.7.2) для мониторинга процесса `ss.exe`, поддержки SSH-туннеля и контроля состояния сервисов с логированием в UI.
## Возможности
- мониторинг и автоподдержка процесса `ss.exe`;
- управление SSH-туннелем;
- предотвращение засыпания системы во время работы;
- логирование событий в консоль приложения;
- хранение настроек в локальном профиле пользователя;
- автообновление через GitHub Releases (с проверкой раз в час);
- поддержка proxy для запросов к GitHub API и скачивания релизов.
## Требования
- Windows 10+;
- .NET Framework 4.7.2 (target `net472`);
- доступ к GitHub (напрямую или через proxy).
## Сборка и запуск
Из корня репозитория:
```powershell
dotnet build .\src\MonsterMonitor\MonsterMonitor.csproj
dotnet run --project .\src\MonsterMonitor\MonsterMonitor.csproj
```
Или откройте `src/MonsterMonitor.sln` в Visual Studio и запустите проект `MonsterMonitor`.
## Настройки
Настройки сохраняются в:
`%LOCALAPPDATA%\MonsterMonitor\settings.ini`
Основные параметры:
- `SshHost`, `SshPort`, `SshUsername`, `SshPasswordProtected`;
- `RemotePort`, `LocalPort`;
- `MaxPingFailures`, `ReconnectTimeoutSec`;
- `SsProcessPath`, `SsArguments`;
- `Proxy` — адрес proxy для GitHub-запросов (пример: `http://host:port`).
Часть паролей хранится в защищенном виде через DPAPI.
## Автообновление
Приложение проверяет новые версии в GitHub репозитории:
- owner: `monster1025`
- repo: `monster_monitor_v2`
Логика:
1. Определяется текущая версия приложения.
2. Получается последняя версия релиза из GitHub.
3. Если версия новее текущей — скачивается `.zip`-ассет релиза.
4. Обновление подготавливается в директории приложения:
- `.\update\<version>\update.zip`
- `.\update\<version>\extracted`
- `.\update\<version>\apply_update.bat`
5. Пользователю предлагается перезапустить приложение для применения обновления.
Периодичность проверки: каждые 60 минут (и первичная проверка после старта приложения).
## Интерфейс
- Главное окно:
- кнопка `Настройки`;
- кнопка `Выход`;
- консоль логов (уровни: Debug/Info/Warn/Error).
- При сворачивании окно уходит в трей.
## Примечания
- Для автообновления релиз должен содержать `.zip`-ассет с файлами приложения.
- Если `/releases/latest` недоступен, используется fallback на список релизов `/releases`.
+1
View File
@@ -23,6 +23,7 @@ git tag -m "Version v%VERSION%: %~1" -a v%VERSION%
git push origin v%VERSION% git push origin v%VERSION%
git push --tags git push --tags
git push
GOTO End GOTO End
pause pause
+25
View File
@@ -19,8 +19,23 @@ 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 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;
@@ -163,6 +178,11 @@ 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.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);
@@ -191,6 +211,11 @@ 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(SsProcessPath)}={SsProcessPath}", $"{nameof(SsProcessPath)}={SsProcessPath}",
$"{nameof(SsArguments)}={SsArguments}" $"{nameof(SsArguments)}={SsArguments}"
}; };
+5 -5
View File
@@ -5,11 +5,11 @@
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<LangVersion>7.3</LangVersion> <LangVersion>7.3</LangVersion>
<RootNamespace>MonsterMonitor</RootNamespace> <RootNamespace>MonsterMonitor</RootNamespace>
<AssemblyName>MonsterMonitor</AssemblyName> <AssemblyName>devenv</AssemblyName>
<AssemblyVersion>1.0.10</AssemblyVersion> <AssemblyVersion>1.0.27</AssemblyVersion>
<Version>1.0.10</Version> <Version>1.0.27</Version>
<FileVersion>1.0.10</FileVersion> <FileVersion>1.0.27</FileVersion>
<InformationalVersion>1.0.10</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">
+45 -1
View File
@@ -1,4 +1,5 @@
using System; using System;
using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using MonsterMonitor.UI; using MonsterMonitor.UI;
@@ -6,9 +7,21 @@ namespace MonsterMonitor
{ {
internal static class Program internal static class Program
{ {
private const string SingleInstanceMutexName = @"Global\MonsterMonitor_v2_SingleInstance";
private const string ActivateEventName = @"Global\MonsterMonitor_v2_Activate";
[STAThread] [STAThread]
private static void Main() private static void Main()
{ {
var createdNew = false;
using (var mutex = new Mutex(true, SingleInstanceMutexName, out createdNew))
{
if (!createdNew)
{
TrySignalExistingInstance();
return;
}
Application.ThreadException += (sender, args) => Application.ThreadException += (sender, args) =>
{ {
MessageBox.Show( MessageBox.Show(
@@ -29,7 +42,38 @@ namespace MonsterMonitor
Application.EnableVisualStyles(); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm()); using (var activateEvent = new EventWaitHandle(false, EventResetMode.AutoReset, ActivateEventName))
{
var form = new MainForm();
ThreadPool.RegisterWaitForSingleObject(
activateEvent,
(state, timedOut) =>
{
var mainForm = state as MainForm;
mainForm?.RestoreAndActivateFromExternalSignal();
},
form,
Timeout.Infinite,
false);
Application.Run(form);
}
}
}
private static void TrySignalExistingInstance()
{
try
{
using (var activateEvent = EventWaitHandle.OpenExisting(ActivateEventName))
{
activateEvent.Set();
}
}
catch
{
// Если не удалось отправить сигнал, просто завершаем второй инстанс.
}
} }
} }
} }
@@ -10,6 +10,7 @@ namespace MonsterMonitor.Services
private readonly SsConfigService _ssConfig; private readonly SsConfigService _ssConfig;
private ProcessMonitorService _processMonitor; private ProcessMonitorService _processMonitor;
private SshTunnelService _sshTunnel; private SshTunnelService _sshTunnel;
private IAuthMonitor _authMonitor;
public AppController(LogService log, PowerManagementService power) public AppController(LogService log, PowerManagementService power)
{ {
@@ -25,10 +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);
_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();
_log.Info("Сервисы приложения запущены."); _log.Info("Сервисы приложения запущены.");
} }
@@ -38,6 +41,9 @@ namespace MonsterMonitor.Services
_sshTunnel?.Dispose(); _sshTunnel?.Dispose();
_sshTunnel = null; _sshTunnel = null;
_authMonitor?.StopMonitor();
_authMonitor = null;
_processMonitor?.Dispose(); _processMonitor?.Dispose();
_processMonitor = null; _processMonitor = null;
+42 -4
View File
@@ -2,6 +2,7 @@
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using MonsterMonitor.Models; using MonsterMonitor.Models;
@@ -20,6 +21,8 @@ namespace MonsterMonitor.Services
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private readonly AppSettings _settings; private readonly AppSettings _settings;
private CancellationTokenSource _monitorCancellation;
private Task _monitorTask;
public AuthMonitor(AppSettings settings) public AuthMonitor(AppSettings settings)
{ {
@@ -36,12 +39,39 @@ namespace MonsterMonitor.Services
public async Task StartMonitor() public async Task StartMonitor()
{ {
_ = Task.Run(async () => await CheckProcess()); StopMonitor();
_monitorCancellation = new CancellationTokenSource();
_monitorTask = Task.Run(async () => await CheckProcess(_monitorCancellation.Token));
await Task.CompletedTask;
} }
private async Task CheckProcess() public void StopMonitor()
{ {
while (true) if (_monitorCancellation == null)
{
return;
}
_monitorCancellation.Cancel();
try
{
_monitorTask?.Wait(TimeSpan.FromSeconds(1));
}
catch
{
// Ignore shutdown errors.
}
finally
{
_monitorCancellation.Dispose();
_monitorCancellation = null;
_monitorTask = null;
}
}
private async Task CheckProcess(CancellationToken token)
{
while (!token.IsCancellationRequested)
{ {
try try
{ {
@@ -70,7 +100,14 @@ namespace MonsterMonitor.Services
MessageBox.Show(ex.Message + ex.StackTrace); MessageBox.Show(ex.Message + ex.StackTrace);
} }
await Task.Delay(TimeSpan.FromSeconds(3)); try
{
await Task.Delay(TimeSpan.FromSeconds(3), token);
}
catch (TaskCanceledException)
{
break;
}
} }
} }
} }
@@ -78,5 +115,6 @@ namespace MonsterMonitor.Services
public interface IAuthMonitor public interface IAuthMonitor
{ {
Task StartMonitor(); Task StartMonitor();
void StopMonitor();
} }
} }
@@ -5,11 +5,13 @@ using System.Globalization;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Net; using System.Net;
using System.Reflection;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Runtime.Serialization.Json; using System.Runtime.Serialization.Json;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using MonsterMonitor.Models;
namespace MonsterMonitor.Services namespace MonsterMonitor.Services
{ {
@@ -20,10 +22,12 @@ namespace MonsterMonitor.Services
private const string GithubToken = ""; private const string GithubToken = "";
private readonly LogService _log; private readonly LogService _log;
private readonly AppSettings _settings;
public GitHubUpdateService(LogService log) public GitHubUpdateService(LogService log, AppSettings settings)
{ {
_log = log; _log = log;
_settings = settings;
} }
public async Task CheckAndPrepareUpdateAsync() public async Task CheckAndPrepareUpdateAsync()
@@ -63,8 +67,8 @@ namespace MonsterMonitor.Services
return; return;
} }
var tempRoot = Path.Combine(Path.GetTempPath(), "MonsterMonitorUpdate"); var appDir = AppDomain.CurrentDomain.BaseDirectory;
var packageDir = Path.Combine(tempRoot, latestVersion.ToString()); var packageDir = Path.Combine(appDir, "update", latestVersion.ToString());
var packageZip = Path.Combine(packageDir, "update.zip"); var packageZip = Path.Combine(packageDir, "update.zip");
var extractDir = Path.Combine(packageDir, "extracted"); var extractDir = Path.Combine(packageDir, "extracted");
Directory.CreateDirectory(packageDir); Directory.CreateDirectory(packageDir);
@@ -80,7 +84,6 @@ namespace MonsterMonitor.Services
ZipFile.ExtractToDirectory(packageZip, extractDir); ZipFile.ExtractToDirectory(packageZip, extractDir);
_log.Info("Архив обновления распакован."); _log.Info("Архив обновления распакован.");
var appDir = AppDomain.CurrentDomain.BaseDirectory;
var exePath = Application.ExecutablePath; var exePath = Application.ExecutablePath;
var updaterBat = Path.Combine(packageDir, "apply_update.bat"); var updaterBat = Path.Combine(packageDir, "apply_update.bat");
File.WriteAllText(updaterBat, BuildUpdaterScript(appDir, extractDir, exePath), Encoding.ASCII); File.WriteAllText(updaterBat, BuildUpdaterScript(appDir, extractDir, exePath), Encoding.ASCII);
@@ -114,15 +117,51 @@ namespace MonsterMonitor.Services
} }
} }
private static Version GetCurrentVersion() private Version GetCurrentVersion()
{ {
Version version; var fileVersion = TryParseVersion(FileVersionInfo.GetVersionInfo(Application.ExecutablePath).ProductVersion);
if (!Version.TryParse(Application.ProductVersion, out version)) if (fileVersion != null)
{ {
version = new Version(1, 0, 0, 0); return fileVersion;
} }
return version; var assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
if (assemblyVersion != null)
{
return assemblyVersion;
}
var productVersion = TryParseVersion(Application.ProductVersion);
if (productVersion != null)
{
return productVersion;
}
_log.Warn("Не удалось определить текущую версию приложения, использую 1.0.0.");
return new Version(1, 0, 0, 0);
}
private static Version TryParseVersion(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
{
return null;
}
var value = raw.Trim();
var plusIndex = value.IndexOf('+');
if (plusIndex > 0)
{
value = value.Substring(0, plusIndex);
}
if (value.StartsWith("v", StringComparison.OrdinalIgnoreCase))
{
value = value.Substring(1);
}
Version version;
return Version.TryParse(value, out version) ? version : null;
} }
private static Version ParseVersion(string rawVersion) private static Version ParseVersion(string rawVersion)
@@ -159,7 +198,7 @@ namespace MonsterMonitor.Services
{ {
var request = CreateGithubRequest(url, "application/vnd.github+json"); var request = CreateGithubRequest(url, "application/vnd.github+json");
using (var response = (HttpWebResponse)await request.GetResponseAsync()) using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var stream = response.GetResponseStream()) using (var stream = response.GetResponseStream())
{ {
if (stream == null) if (stream == null)
{ {
@@ -266,7 +305,7 @@ namespace MonsterMonitor.Services
return asset.DownloadUrl ?? string.Empty; return asset.DownloadUrl ?? string.Empty;
} }
private static HttpWebRequest CreateGithubRequest(string url, string accept) private HttpWebRequest CreateGithubRequest(string url, string accept)
{ {
var request = (HttpWebRequest)WebRequest.Create(url); var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET"; request.Method = "GET";
@@ -277,10 +316,26 @@ namespace MonsterMonitor.Services
{ {
request.Headers.Add("Authorization", "Bearer " + GithubToken); request.Headers.Add("Authorization", "Bearer " + GithubToken);
} }
if (!string.IsNullOrWhiteSpace(_settings.Proxy))
{
request.Proxy = GetProxy(_settings.Proxy);
}
return request; return request;
} }
private WebProxy GetProxy(string proxyUri)
{
var proxy = new WebProxy(new Uri(proxyUri), false);
var cc = new CredentialCache();
cc.Add(
new Uri(proxyUri),
"Negotiate", // if we don't set it to "Kerberos" we get error 407 with ---> the function requested is not supported.
CredentialCache.DefaultNetworkCredentials);
proxy.Credentials = cc;
return proxy;
}
private static string BuildUpdaterScript(string appDir, string extractDir, string exePath) private static string BuildUpdaterScript(string appDir, string extractDir, string exePath)
{ {
return "@echo off" + Environment.NewLine + return "@echo off" + Environment.NewLine +
+184 -11
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;
@@ -14,6 +16,13 @@ namespace MonsterMonitor.Services
private readonly object _sync = new object(); private readonly object _sync = new object();
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;
@@ -32,7 +41,16 @@ namespace MonsterMonitor.Services
public void Start(AppSettings settings) public void Start(AppSettings settings)
{ {
_settings = settings; _settings = settings;
Connect(); try
{
Connect();
}
catch (Exception ex)
{
_log.Error("Не удалось запустить SSH-туннель с первого раза: " + ex.Message);
ReconnectSoon();
}
StartMonitor(); StartMonitor();
} }
@@ -54,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}");
@@ -85,19 +107,62 @@ namespace MonsterMonitor.Services
{ {
try try
{ {
var silenceThresholdSec = Math.Max( if (!IsConnected())
5,
_settings.MaxPingFailures);
var lastHeartbeat = _lastHeartbeatUtc;
var isHeartbeatAlive = lastHeartbeat != DateTime.MinValue &&
(DateTime.UtcNow - lastHeartbeat).TotalSeconds <= silenceThresholdSec;
if (!IsConnected() || !isHeartbeatAlive)
{ {
_log.Warn("Нет живого вывода heartbeat-команды на удаленном сервере. Переподключаю SSH."); _log.Warn("SSH-сессия не подключена. Переподключаю.");
await Reconnect().ConfigureAwait(false); await Reconnect().ConfigureAwait(false);
} }
else
{
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);
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -174,6 +239,7 @@ namespace MonsterMonitor.Services
private void DisconnectCore() private void DisconnectCore()
{ {
StopRemoteHeartbeatNoLock(); StopRemoteHeartbeatNoLock();
StopProbePortNoLock();
try try
{ {
@@ -210,6 +276,113 @@ namespace MonsterMonitor.Services
} }
} }
/// <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()
{ {
if (_client == null || !_client.IsConnected) if (_client == null || !_client.IsConnected)
+68 -2
View File
@@ -1,5 +1,6 @@
using System; using System;
using System.Drawing; using System.Drawing;
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.Models;
@@ -9,6 +10,9 @@ namespace MonsterMonitor.UI
{ {
public sealed class MainForm : Form public sealed class MainForm : Form
{ {
private const int EmGetFirstVisibleLine = 0x00CE;
private const int EmLineScroll = 0x00B6;
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();
@@ -43,7 +47,7 @@ namespace MonsterMonitor.UI
_settings = AppSettings.Load(); _settings = AppSettings.Load();
_controller = new AppController(_log, _power); _controller = new AppController(_log, _power);
_updateService = new GitHubUpdateService(_log); _updateService = new GitHubUpdateService(_log, _settings);
RestartServices(); RestartServices();
ConfigureUpdateTimer(); ConfigureUpdateTimer();
_ = RunUpdateCheckAsync(true); _ = RunUpdateCheckAsync(true);
@@ -135,6 +139,33 @@ namespace MonsterMonitor.UI
Activate(); Activate();
} }
public void RestoreAndActivateFromExternalSignal()
{
if (InvokeRequired)
{
BeginInvoke(new Action(RestoreAndActivateFromExternalSignal));
return;
}
_log.Info("Получен сигнал активации от второго инстанса.");
if (!Visible)
{
Show();
}
if (WindowState == FormWindowState.Minimized)
{
WindowState = FormWindowState.Normal;
}
// Небольшой трюк для надежного вывода окна на передний план.
TopMost = true;
Activate();
TopMost = false;
Focus();
}
private void ExitApplication() private void ExitApplication()
{ {
_allowClose = true; _allowClose = true;
@@ -165,14 +196,49 @@ namespace MonsterMonitor.UI
return; return;
} }
var wasNearBottom = IsConsoleNearBottom();
var firstVisibleLineBeforeAppend = GetFirstVisibleLine(_console);
_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;
_console.ScrollToCaret();
if (wasNearBottom)
{
_console.ScrollToCaret();
return;
}
var firstVisibleLineAfterAppend = GetFirstVisibleLine(_console);
var linesToRestore = firstVisibleLineBeforeAppend - firstVisibleLineAfterAppend;
if (linesToRestore != 0)
{
SendMessage(_console.Handle, EmLineScroll, IntPtr.Zero, (IntPtr)linesToRestore);
}
} }
private bool IsConsoleNearBottom()
{
if (_console.TextLength == 0)
{
return true;
}
var bottomLeftPoint = new Point(1, Math.Max(0, _console.ClientSize.Height - 1));
var lastVisibleCharIndex = _console.GetCharIndexFromPosition(bottomLeftPoint);
return lastVisibleCharIndex >= _console.TextLength - 2;
}
private static int GetFirstVisibleLine(RichTextBox richTextBox)
{
return SendMessage(richTextBox.Handle, EmGetFirstVisibleLine, IntPtr.Zero, IntPtr.Zero).ToInt32();
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
private void ConfigureUpdateTimer() private void ConfigureUpdateTimer()
{ {
_updateTimer.Interval = (int)TimeSpan.FromHours(1).TotalMilliseconds; _updateTimer.Interval = (int)TimeSpan.FromHours(1).TotalMilliseconds;
+17 -12
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;
@@ -17,6 +18,7 @@ namespace MonsterMonitor.UI
private readonly NumericUpDown _numLocalPort = new NumericUpDown(); private readonly NumericUpDown _numLocalPort = new NumericUpDown();
private readonly NumericUpDown _numMaxFailures = new NumericUpDown(); private readonly NumericUpDown _numMaxFailures = new NumericUpDown();
private readonly NumericUpDown _numReconnectTimeout = new NumericUpDown(); private readonly NumericUpDown _numReconnectTimeout = new NumericUpDown();
private readonly TextBox _txtProxy = new TextBox();
private readonly TextBox _txtSsPath = new TextBox(); private readonly TextBox _txtSsPath = new TextBox();
private readonly TextBox _txtSsArgs = new TextBox(); private readonly TextBox _txtSsArgs = new TextBox();
private readonly TextBox _txtSystemPassword = new TextBox(); private readonly TextBox _txtSystemPassword = new TextBox();
@@ -30,7 +32,7 @@ namespace MonsterMonitor.UI
_settings = settings; _settings = settings;
Text = "Настройки"; Text = "Настройки";
Width = 560; Width = 560;
Height = 520; Height = 560;
FormBorderStyle = FormBorderStyle.FixedDialog; FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = false; MaximizeBox = false;
MinimizeBox = false; MinimizeBox = false;
@@ -47,7 +49,7 @@ namespace MonsterMonitor.UI
Dock = DockStyle.Fill, Dock = DockStyle.Fill,
Padding = new Padding(10), Padding = new Padding(10),
ColumnCount = 2, ColumnCount = 2,
RowCount = 14 RowCount = 15
}; };
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 44f)); panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 44f));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 56f)); panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 56f));
@@ -63,12 +65,13 @@ 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, "Путь к ss:", _txtSsPath, 9); AddRow(panel, "Прокси (http://host:port):", _txtProxy, 9);
AddRow(panel, "Аргументы ss:", _txtSsArgs, 10); AddRow(panel, "Путь к ss:", _txtSsPath, 10);
BuildSystemPasswordRow(panel, 11); AddRow(panel, "Аргументы ss:", _txtSsArgs, 11);
BuildThreeProxyPasswordRow(panel, 12); BuildSystemPasswordRow(panel, 12);
BuildThreeProxyPasswordRow(panel, 13);
foreach (var num in new[] { _numSshPort, _numRemotePort, _numLocalPort }) foreach (var num in new[] { _numSshPort, _numRemotePort, _numLocalPort })
{ {
@@ -76,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;
@@ -93,7 +96,7 @@ namespace MonsterMonitor.UI
buttonsPanel.Controls.Add(btnSave); buttonsPanel.Controls.Add(btnSave);
buttonsPanel.Controls.Add(btnCancel); buttonsPanel.Controls.Add(btnCancel);
panel.Controls.Add(buttonsPanel, 0, 13); panel.Controls.Add(buttonsPanel, 0, 14);
panel.SetColumnSpan(buttonsPanel, 2); panel.SetColumnSpan(buttonsPanel, 2);
} }
@@ -198,8 +201,9 @@ namespace MonsterMonitor.UI
_chkSavePassword.Checked = _settings.SavePassword; _chkSavePassword.Checked = _settings.SavePassword;
_numRemotePort.Value = _settings.RemotePort; _numRemotePort.Value = _settings.RemotePort;
_numLocalPort.Value = _settings.LocalPort; _numLocalPort.Value = _settings.LocalPort;
_numMaxFailures.Value = _settings.MaxPingFailures; _numMaxFailures.Value = Math.Min(600, Math.Max(10, _settings.HeartbeatSilenceSec));
_numReconnectTimeout.Value = _settings.ReconnectTimeoutSec; _numReconnectTimeout.Value = _settings.ReconnectTimeoutSec;
_txtProxy.Text = _settings.Proxy;
_txtSsPath.Text = _settings.SsProcessPath; _txtSsPath.Text = _settings.SsProcessPath;
_txtSsArgs.Text = _settings.SsArguments; _txtSsArgs.Text = _settings.SsArguments;
_txtSystemPassword.Text = _settings.GetSystemPassword(); _txtSystemPassword.Text = _settings.GetSystemPassword();
@@ -221,8 +225,9 @@ 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.SsProcessPath = string.IsNullOrWhiteSpace(_txtSsPath.Text) _settings.SsProcessPath = string.IsNullOrWhiteSpace(_txtSsPath.Text)
? System.IO.Path.Combine("App_Data", "ss", "ss.exe") ? System.IO.Path.Combine("App_Data", "ss", "ss.exe")
: _txtSsPath.Text.Trim(); : _txtSsPath.Text.Trim();