Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7db3401799 | ||
|
|
2da1eac443 | ||
|
|
dc92c80b43 | ||
|
|
724644c8eb | ||
|
|
23768dbe0e | ||
|
|
ace23b954e | ||
|
|
a4fc8c047a | ||
|
|
5a2639f96c | ||
|
|
fbd94ae1e6 | ||
|
|
cf01546b0b | ||
|
|
ec80bea024 | ||
|
|
b88006f02d | ||
|
|
c5ac1681f2 | ||
|
|
06f2ebb1ac | ||
|
|
9912ca8ba4 | ||
|
|
427f16cde0 | ||
|
|
fe8abb589f | ||
|
|
ae787373dc |
@@ -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
@@ -1 +1 @@
|
|||||||
1.0.8
|
1.0.24
|
||||||
|
|||||||
@@ -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`.
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ namespace MonsterMonitor.Models
|
|||||||
public int LocalPort { get; set; } = 7829;
|
public int LocalPort { get; set; } = 7829;
|
||||||
public int MaxPingFailures { get; set; } = 3;
|
public int MaxPingFailures { get; set; } = 3;
|
||||||
public int ReconnectTimeoutSec { get; set; } = 45;
|
public int ReconnectTimeoutSec { get; set; } = 45;
|
||||||
|
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,13 +164,15 @@ 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.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;
|
||||||
@@ -191,6 +194,7 @@ namespace MonsterMonitor.Models
|
|||||||
$"{nameof(LocalPort)}={LocalPort}",
|
$"{nameof(LocalPort)}={LocalPort}",
|
||||||
$"{nameof(MaxPingFailures)}={MaxPingFailures}",
|
$"{nameof(MaxPingFailures)}={MaxPingFailures}",
|
||||||
$"{nameof(ReconnectTimeoutSec)}={ReconnectTimeoutSec}",
|
$"{nameof(ReconnectTimeoutSec)}={ReconnectTimeoutSec}",
|
||||||
|
$"{nameof(Proxy)}={Proxy}",
|
||||||
$"{nameof(SsProcessPath)}={SsProcessPath}",
|
$"{nameof(SsProcessPath)}={SsProcessPath}",
|
||||||
$"{nameof(SsArguments)}={SsArguments}"
|
$"{nameof(SsArguments)}={SsArguments}"
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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.8</AssemblyVersion>
|
<AssemblyVersion>1.0.24</AssemblyVersion>
|
||||||
<Version>1.0.8</Version>
|
<Version>1.0.24</Version>
|
||||||
<FileVersion>1.0.8</FileVersion>
|
<FileVersion>1.0.24</FileVersion>
|
||||||
<InformationalVersion>1.0.8</InformationalVersion>
|
<InformationalVersion>1.0.24</InformationalVersion>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Costura.Fody" Version="6.0.0">
|
<PackageReference Include="Costura.Fody" Version="6.0.0">
|
||||||
|
|||||||
@@ -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
|
||||||
|
{
|
||||||
|
// Если не удалось отправить сигнал, просто завершаем второй инстанс.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using MonsterMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
|
|
||||||
namespace MonsterMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
@@ -10,6 +11,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 +27,14 @@ 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);
|
||||||
|
|
||||||
_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(
|
||||||
|
t => _log.Error("Ошибка запуска монитора авторизации: " + t.Exception?.GetBaseException().Message),
|
||||||
|
TaskContinuationOptions.OnlyOnFaulted);
|
||||||
|
|
||||||
_log.Info("Сервисы приложения запущены.");
|
_log.Info("Сервисы приложения запущены.");
|
||||||
}
|
}
|
||||||
@@ -38,6 +44,9 @@ namespace MonsterMonitor.Services
|
|||||||
_sshTunnel?.Dispose();
|
_sshTunnel?.Dispose();
|
||||||
_sshTunnel = null;
|
_sshTunnel = null;
|
||||||
|
|
||||||
|
_authMonitor?.StopMonitor();
|
||||||
|
_authMonitor = null;
|
||||||
|
|
||||||
_processMonitor?.Dispose();
|
_processMonitor?.Dispose();
|
||||||
_processMonitor = null;
|
_processMonitor = null;
|
||||||
|
|
||||||
|
|||||||
@@ -1,76 +1,160 @@
|
|||||||
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.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
using MonsterMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
|
|
||||||
namespace MonsterMonitor.Services
|
namespace MonsterMonitor.Services
|
||||||
{
|
{
|
||||||
public class AuthMonitor: IAuthMonitor
|
public class AuthMonitor : IAuthMonitor
|
||||||
{
|
{
|
||||||
|
private const string AuthWindowMarker = "XAuth request";
|
||||||
|
|
||||||
[DllImport("user32.dll")]
|
[DllImport("user32.dll")]
|
||||||
static extern IntPtr GetForegroundWindow();
|
private 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")]
|
||||||
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
|
private static extern int GetWindowTextLength(IntPtr hWnd);
|
||||||
|
|
||||||
|
[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 Task _monitorTask;
|
||||||
|
|
||||||
public AuthMonitor(AppSettings settings)
|
public AuthMonitor(AppSettings settings, LogService log)
|
||||||
{
|
{
|
||||||
_settings = settings;
|
_settings = settings;
|
||||||
|
_log = log;
|
||||||
}
|
}
|
||||||
|
|
||||||
private string GetActiveWindowTitle()
|
private static string GetWindowTitle(IntPtr handle)
|
||||||
{
|
{
|
||||||
const int nChars = 256;
|
var length = GetWindowTextLength(handle);
|
||||||
var buff = new StringBuilder(nChars);
|
if (length <= 0)
|
||||||
var handle = GetForegroundWindow();
|
{
|
||||||
return GetWindowText(handle, buff, nChars) > 0 ? buff.ToString() : null;
|
return 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()
|
||||||
{
|
{
|
||||||
_ = 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
|
||||||
{
|
{
|
||||||
Process[] processlist = Process.GetProcesses();
|
var authWindow = FindAuthWindow();
|
||||||
foreach (Process process in processlist)
|
if (authWindow != IntPtr.Zero)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(process.MainWindowTitle) && process.MainWindowTitle.Contains("XAuth request"))
|
SetForegroundWindow(authWindow);
|
||||||
{
|
|
||||||
SetForegroundWindow(process.MainWindowHandle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var activeWindowTitle = GetActiveWindowTitle();
|
var activeWindowTitle = GetActiveWindowTitle();
|
||||||
if (activeWindowTitle?.Contains("XAuth request") == true)
|
if (activeWindowTitle?.IndexOf(AuthWindowMarker, StringComparison.OrdinalIgnoreCase) >= 0)
|
||||||
{
|
|
||||||
var password = _settings.GetSystemPassword();
|
|
||||||
if (!string.IsNullOrEmpty(password))
|
|
||||||
{
|
{
|
||||||
SendKeys.SendWait(password);
|
var password = _settings.GetSystemPassword();
|
||||||
SendKeys.SendWait("{ENTER}");
|
if (!string.IsNullOrEmpty(password))
|
||||||
|
{
|
||||||
|
SendKeys.SendWait(password);
|
||||||
|
SendKeys.SendWait("{ENTER}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
MessageBox.Show(ex.Message + ex.StackTrace);
|
// Раньше здесь был MessageBox.Show из фонового потока — при повторяющемся
|
||||||
|
// исключении он заваливал рабочий стол окнами. Теперь просто пишем в лог.
|
||||||
|
_log.Warn("Ошибка мониторинга авторизации: " + ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(3), token);
|
||||||
|
}
|
||||||
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,5 +162,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 +
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ 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)
|
||||||
{
|
{
|
||||||
@@ -43,7 +44,6 @@ namespace MonsterMonitor.Services
|
|||||||
{
|
{
|
||||||
if (_process != null)
|
if (_process != null)
|
||||||
{
|
{
|
||||||
_process.Exited -= ProcessOnExited;
|
|
||||||
_process.Dispose();
|
_process.Dispose();
|
||||||
}
|
}
|
||||||
_process = new Process
|
_process = new Process
|
||||||
@@ -57,27 +57,19 @@ 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)
|
||||||
{
|
{
|
||||||
_log.Error("Ошибка запуска ss: " + ex.Message);
|
// Watchdog тикает каждые 10с; при неверном пути не флудим лог
|
||||||
}
|
// одинаковой ошибкой — пишем её только при изменении.
|
||||||
}
|
if (_lastStartError != ex.Message)
|
||||||
|
|
||||||
private void ProcessOnExited(object sender, EventArgs e)
|
|
||||||
{
|
|
||||||
lock (_sync)
|
|
||||||
{
|
|
||||||
if (_stopping)
|
|
||||||
{
|
{
|
||||||
return;
|
_lastStartError = ex.Message;
|
||||||
|
_log.Error("Ошибка запуска ss: " + ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
_log.Warn("Процесс ss завершился, запускаю заново.");
|
|
||||||
EnsureStarted();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,7 +110,6 @@ namespace MonsterMonitor.Services
|
|||||||
{
|
{
|
||||||
if (_process != null)
|
if (_process != null)
|
||||||
{
|
{
|
||||||
_process.Exited -= ProcessOnExited;
|
|
||||||
_process.Dispose();
|
_process.Dispose();
|
||||||
}
|
}
|
||||||
_process = null;
|
_process = null;
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ namespace MonsterMonitor.Services
|
|||||||
|
|
||||||
var config = "users admin:CL:" + password + "\r\n" +
|
var config = "users admin:CL:" + password + "\r\n" +
|
||||||
"auth strong\r\n" +
|
"auth strong\r\n" +
|
||||||
|
"maxconn 2000\r\n" +
|
||||||
$"socks -i127.0.0.1 -p{port}";
|
$"socks -i127.0.0.1 -p{port}";
|
||||||
|
|
||||||
var configPath = GetConfigPath();
|
var configPath = GetConfigPath();
|
||||||
|
|||||||
@@ -12,16 +12,21 @@ 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;
|
||||||
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 bool _disposed;
|
private volatile bool _disposed;
|
||||||
private bool _reconnectInProgress;
|
private long _lastHeartbeatTicks;
|
||||||
private DateTime _lastHeartbeatUtc = DateTime.MinValue;
|
|
||||||
private bool _remoteIsWindows;
|
private bool _remoteIsWindows;
|
||||||
|
|
||||||
public SshTunnelService(LogService log)
|
public SshTunnelService(LogService log)
|
||||||
@@ -32,7 +37,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();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,6 +60,10 @@ 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();
|
||||||
@@ -76,7 +94,7 @@ namespace MonsterMonitor.Services
|
|||||||
private void StartMonitor()
|
private void StartMonitor()
|
||||||
{
|
{
|
||||||
_monitorTokenSource = new CancellationTokenSource();
|
_monitorTokenSource = new CancellationTokenSource();
|
||||||
Task.Run(() => MonitorLoop(_monitorTokenSource.Token));
|
_monitorTask = Task.Run(() => MonitorLoop(_monitorTokenSource.Token));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task MonitorLoop(CancellationToken token)
|
private async Task MonitorLoop(CancellationToken token)
|
||||||
@@ -85,18 +103,23 @@ namespace MonsterMonitor.Services
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var silenceThresholdSec = Math.Max(
|
// Пропускаем проверку, пока идёт реконнект — иначе получаем лог-флуд
|
||||||
5,
|
// и лишние пробуждения, дёргающие уже занятый шлюз реконнекта.
|
||||||
_settings.MaxPingFailures);
|
if (_reconnectGate.CurrentCount > 0)
|
||||||
|
|
||||||
var lastHeartbeat = _lastHeartbeatUtc;
|
|
||||||
var isHeartbeatAlive = lastHeartbeat != DateTime.MinValue &&
|
|
||||||
(DateTime.UtcNow - lastHeartbeat).TotalSeconds <= silenceThresholdSec;
|
|
||||||
|
|
||||||
if (!IsConnected() || !isHeartbeatAlive)
|
|
||||||
{
|
{
|
||||||
_log.Warn("Нет живого вывода heartbeat-команды на удаленном сервере. Переподключаю SSH.");
|
// heartbeat присылается раз в секунду; MaxPingFailures трактуем
|
||||||
await Reconnect().ConfigureAwait(false);
|
// как допустимое число пропущенных ответов (≈ секунд тишины).
|
||||||
|
var silenceThresholdSec = Math.Max(10, _settings.MaxPingFailures);
|
||||||
|
|
||||||
|
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.");
|
||||||
|
await Reconnect().ConfigureAwait(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -106,9 +129,9 @@ namespace MonsterMonitor.Services
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await Task.Delay(TimeSpan.FromSeconds(2), token).ConfigureAwait(false);
|
await Task.Delay(TimeSpan.FromSeconds(3), token).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (TaskCanceledException)
|
catch (OperationCanceledException)
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -127,39 +150,51 @@ namespace MonsterMonitor.Services
|
|||||||
{
|
{
|
||||||
Task.Run(async () =>
|
Task.Run(async () =>
|
||||||
{
|
{
|
||||||
await Task.Delay(1000).ConfigureAwait(false);
|
try
|
||||||
await Reconnect().ConfigureAwait(false);
|
{
|
||||||
|
await Task.Delay(1000).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 (_reconnectInProgress || _disposed)
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Неблокирующая попытка захватить шлюз: если реконнект уже идёт — выходим,
|
||||||
|
// не создавая второй параллельный Connect() и не накапливая очередь.
|
||||||
|
if (!await _reconnectGate.WaitAsync(0).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_reconnectInProgress = true;
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var timeout = Math.Min(60, Math.Max(5, _settings.ReconnectTimeoutSec));
|
if (_disposed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
_log.Warn("Перезапуск SSH-соединения...");
|
_log.Warn("Перезапуск SSH-соединения...");
|
||||||
|
|
||||||
var reconnectTask = Task.Run(() =>
|
// Connect() ограничен ConnectionInfo.Timeout, поэтому не зависнет навсегда.
|
||||||
|
// Ждём завершения задачи (без брошенного WhenAny) — нет орфанных SshClient.
|
||||||
|
await Task.Run(() =>
|
||||||
{
|
{
|
||||||
DisconnectCore();
|
DisconnectCore();
|
||||||
Connect();
|
Connect();
|
||||||
});
|
}).ConfigureAwait(false);
|
||||||
|
|
||||||
var completed = await Task.WhenAny(reconnectTask, Task.Delay(TimeSpan.FromSeconds(timeout))).ConfigureAwait(false);
|
_log.Info("SSH-соединение восстановлено.");
|
||||||
if (completed != reconnectTask)
|
|
||||||
{
|
|
||||||
_log.Error("Переподключение превысило таймаут " + timeout + "с.");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_log.Info("SSH-соединение восстановлено.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -167,46 +202,51 @@ namespace MonsterMonitor.Services
|
|||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
_reconnectInProgress = false;
|
_reconnectGate.Release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void DisconnectCore()
|
private void DisconnectCore()
|
||||||
{
|
{
|
||||||
StopRemoteHeartbeatNoLock();
|
lock (_sync)
|
||||||
|
{
|
||||||
|
StopRemoteHeartbeatNoLock();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
|
||||||
if (_forwardedPort != null)
|
|
||||||
{
|
{
|
||||||
if (_forwardedPort.IsStarted)
|
if (_forwardedPort != null)
|
||||||
{
|
{
|
||||||
_forwardedPort.Stop();
|
if (_forwardedPort.IsStarted)
|
||||||
|
{
|
||||||
|
_forwardedPort.Stop();
|
||||||
|
}
|
||||||
|
_forwardedPort.Exception -= ForwardedPortOnException;
|
||||||
|
_forwardedPort.Dispose();
|
||||||
|
_forwardedPort = null;
|
||||||
}
|
}
|
||||||
_forwardedPort.Dispose();
|
|
||||||
_forwardedPort = null;
|
|
||||||
}
|
}
|
||||||
}
|
catch
|
||||||
catch
|
{
|
||||||
{
|
// Ignore errors on shutdown.
|
||||||
// Ignore errors on shutdown.
|
}
|
||||||
}
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
|
||||||
if (_client != null)
|
|
||||||
{
|
{
|
||||||
if (_client.IsConnected)
|
if (_client != null)
|
||||||
{
|
{
|
||||||
_client.Disconnect();
|
_client.ErrorOccurred -= ClientOnErrorOccurred;
|
||||||
|
if (_client.IsConnected)
|
||||||
|
{
|
||||||
|
_client.Disconnect();
|
||||||
|
}
|
||||||
|
_client.Dispose();
|
||||||
|
_client = null;
|
||||||
}
|
}
|
||||||
_client.Dispose();
|
|
||||||
_client = null;
|
|
||||||
}
|
}
|
||||||
}
|
catch
|
||||||
catch
|
{
|
||||||
{
|
// Ignore errors on shutdown.
|
||||||
// Ignore errors on shutdown.
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,7 +266,7 @@ namespace MonsterMonitor.Services
|
|||||||
|
|
||||||
_heartbeatCommand = _client.CreateCommand(heartbeatCommand);
|
_heartbeatCommand = _client.CreateCommand(heartbeatCommand);
|
||||||
_heartbeatReadTokenSource = new CancellationTokenSource();
|
_heartbeatReadTokenSource = new CancellationTokenSource();
|
||||||
_lastHeartbeatUtc = DateTime.UtcNow;
|
Interlocked.Exchange(ref _lastHeartbeatTicks, DateTime.UtcNow.Ticks);
|
||||||
_heartbeatCommand.BeginExecute();
|
_heartbeatCommand.BeginExecute();
|
||||||
|
|
||||||
_heartbeatReadTask = Task.Run(() =>
|
_heartbeatReadTask = Task.Run(() =>
|
||||||
@@ -278,7 +318,7 @@ namespace MonsterMonitor.Services
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
_lastHeartbeatUtc = DateTime.UtcNow;
|
Interlocked.Exchange(ref _lastHeartbeatTicks, DateTime.UtcNow.Ticks);
|
||||||
_log.Debug("HB: " + line);
|
_log.Debug("HB: " + line);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -296,9 +336,11 @@ namespace MonsterMonitor.Services
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var command = _client.CreateCommand("cmd /c ver");
|
using (var command = _client.CreateCommand("cmd /c ver"))
|
||||||
var output = command.Execute() ?? string.Empty;
|
{
|
||||||
return output.IndexOf("windows", StringComparison.OrdinalIgnoreCase) >= 0;
|
var output = command.Execute() ?? string.Empty;
|
||||||
|
return output.IndexOf("windows", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -308,19 +350,35 @@ namespace MonsterMonitor.Services
|
|||||||
|
|
||||||
public void Stop()
|
public void Stop()
|
||||||
{
|
{
|
||||||
_monitorTokenSource?.Cancel();
|
var monitorTokenSource = _monitorTokenSource;
|
||||||
_monitorTokenSource?.Dispose();
|
var monitorTask = _monitorTask;
|
||||||
_monitorTokenSource = null;
|
_monitorTokenSource = null;
|
||||||
lock (_sync)
|
_monitorTask = null;
|
||||||
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
DisconnectCore();
|
monitorTokenSource?.Cancel();
|
||||||
|
// Дожидаемся завершения цикла монитора до освобождения CTS,
|
||||||
|
// иначе Task.Delay(token) может словить ObjectDisposedException.
|
||||||
|
monitorTask?.Wait(TimeSpan.FromSeconds(2));
|
||||||
}
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Ignore shutdown errors.
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
monitorTokenSource?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
DisconnectCore();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
_disposed = true;
|
_disposed = true;
|
||||||
Stop();
|
Stop();
|
||||||
|
_reconnectGate.Dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,31 @@
|
|||||||
using System;
|
|
||||||
using System.Drawing;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using System.Windows.Forms;
|
|
||||||
using MonsterMonitor.Models;
|
using MonsterMonitor.Models;
|
||||||
using MonsterMonitor.Services;
|
using MonsterMonitor.Services;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Drawing;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace MonsterMonitor.UI
|
namespace MonsterMonitor.UI
|
||||||
{
|
{
|
||||||
public sealed class MainForm : Form
|
public sealed class MainForm : Form
|
||||||
{
|
{
|
||||||
|
private const int EmGetFirstVisibleLine = 0x00CE;
|
||||||
|
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();
|
||||||
@@ -30,6 +42,7 @@ namespace MonsterMonitor.UI
|
|||||||
Height = 620;
|
Height = 620;
|
||||||
StartPosition = FormStartPosition.CenterScreen;
|
StartPosition = FormStartPosition.CenterScreen;
|
||||||
_trayIcon = LoadTrayIcon();
|
_trayIcon = LoadTrayIcon();
|
||||||
|
Icon = _trayIcon;
|
||||||
|
|
||||||
BuildUi();
|
BuildUi();
|
||||||
BindEvents();
|
BindEvents();
|
||||||
@@ -38,12 +51,11 @@ 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);
|
_updateService = new GitHubUpdateService(_log, _settings);
|
||||||
|
ConfigureLogFlushTimer();
|
||||||
RestartServices();
|
RestartServices();
|
||||||
ConfigureUpdateTimer();
|
ConfigureUpdateTimer();
|
||||||
_ = RunUpdateCheckAsync(true);
|
_ = RunUpdateCheckAsync(true);
|
||||||
@@ -135,6 +147,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;
|
||||||
@@ -150,29 +189,117 @@ namespace MonsterMonitor.UI
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_notifyIcon.Visible = false;
|
// Останавливаем таймеры заранее, чтобы не было тиков во время разрушения формы.
|
||||||
|
_logFlushTimer.Stop();
|
||||||
_updateTimer.Stop();
|
_updateTimer.Stop();
|
||||||
_updateTimer.Dispose();
|
_notifyIcon.Visible = false;
|
||||||
_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)
|
||||||
{
|
{
|
||||||
if (InvokeRequired)
|
_pendingLogs.Enqueue(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Выполняется всегда в UI-потоке (таймер WinForms).
|
||||||
|
private void FlushLogs()
|
||||||
|
{
|
||||||
|
if (_pendingLogs.IsEmpty || !_console.IsHandleCreated)
|
||||||
{
|
{
|
||||||
BeginInvoke(new Action<LogEntry>(AppendLog), entry);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var wasNearBottom = IsConsoleNearBottom();
|
||||||
|
var firstVisibleLineBeforeAppend = GetFirstVisibleLine(_console);
|
||||||
|
|
||||||
|
// Замораживаем отрисовку на время пакетного добавления — одна перерисовка вместо десятков.
|
||||||
|
SendMessage(_console.Handle, WmSetRedraw, IntPtr.Zero, IntPtr.Zero);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (_pendingLogs.TryDequeue(out var entry))
|
||||||
|
{
|
||||||
|
_console.SelectionStart = _console.TextLength;
|
||||||
|
_console.SelectionLength = 0;
|
||||||
|
_console.SelectionColor = GetColor(entry.Level);
|
||||||
|
_console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}");
|
||||||
|
_console.SelectionColor = _console.ForeColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
TrimConsole();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
SendMessage(_console.Handle, WmSetRedraw, (IntPtr)1, IntPtr.Zero);
|
||||||
|
_console.Invalidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasNearBottom)
|
||||||
|
{
|
||||||
|
_console.SelectionStart = _console.TextLength;
|
||||||
|
_console.SelectionLength = 0;
|
||||||
|
_console.ScrollToCaret();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var firstVisibleLineAfterAppend = GetFirstVisibleLine(_console);
|
||||||
|
var linesToRestore = firstVisibleLineBeforeAppend - firstVisibleLineAfterAppend;
|
||||||
|
if (linesToRestore != 0)
|
||||||
|
{
|
||||||
|
SendMessage(_console.Handle, EmLineScroll, IntPtr.Zero, (IntPtr)linesToRestore);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Обрезаем старые строки, а не сбрасываем весь буфер — плавно и без рывка скролла.
|
||||||
|
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.SelectionStart = _console.TextLength;
|
||||||
_console.SelectionLength = 0;
|
_console.SelectionLength = 0;
|
||||||
_console.SelectionColor = GetColor(entry.Level);
|
|
||||||
_console.AppendText($"[{entry.Timestamp:HH:mm:ss}] [{entry.Level}] {entry.Message}{Environment.NewLine}");
|
|
||||||
_console.SelectionColor = _console.ForeColor;
|
|
||||||
_console.ScrollToCaret();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
@@ -203,6 +330,11 @@ 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;
|
||||||
@@ -230,18 +362,25 @@ namespace MonsterMonitor.UI
|
|||||||
return ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
|
return ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void InitializeComponent()
|
protected override void Dispose(bool disposing)
|
||||||
{
|
{
|
||||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
|
if (disposing)
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,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 +31,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 +48,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));
|
||||||
@@ -65,10 +66,11 @@ namespace MonsterMonitor.UI
|
|||||||
AddRow(panel, "Локальный порт:", _numLocalPort, 6);
|
AddRow(panel, "Локальный порт:", _numLocalPort, 6);
|
||||||
AddRow(panel, "Макс. потерь:", _numMaxFailures, 7);
|
AddRow(panel, "Макс. потерь:", _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 })
|
||||||
{
|
{
|
||||||
@@ -93,7 +95,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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,20 +194,38 @@ namespace MonsterMonitor.UI
|
|||||||
private void LoadValues()
|
private void LoadValues()
|
||||||
{
|
{
|
||||||
_txtHost.Text = _settings.SshHost;
|
_txtHost.Text = _settings.SshHost;
|
||||||
_numSshPort.Value = _settings.SshPort;
|
_numSshPort.Value = Clamp(_numSshPort, _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 = _settings.RemotePort;
|
_numRemotePort.Value = Clamp(_numRemotePort, _settings.RemotePort);
|
||||||
_numLocalPort.Value = _settings.LocalPort;
|
_numLocalPort.Value = Clamp(_numLocalPort, _settings.LocalPort);
|
||||||
_numMaxFailures.Value = _settings.MaxPingFailures;
|
_numMaxFailures.Value = Clamp(_numMaxFailures, _settings.MaxPingFailures);
|
||||||
_numReconnectTimeout.Value = _settings.ReconnectTimeoutSec;
|
_numReconnectTimeout.Value = Clamp(_numReconnectTimeout, _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();
|
||||||
_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))
|
||||||
@@ -223,6 +243,7 @@ namespace MonsterMonitor.UI
|
|||||||
_settings.LocalPort = (int)_numLocalPort.Value;
|
_settings.LocalPort = (int)_numLocalPort.Value;
|
||||||
_settings.MaxPingFailures = (int)_numMaxFailures.Value;
|
_settings.MaxPingFailures = (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();
|
||||||
|
|||||||
Reference in New Issue
Block a user