Browse Source

优化网络状态监控:1. 将操作类型参数改为布尔类型 2. 优化启动和停止操作的检查逻辑 3. 改进日志记录

master
root 2 days ago
parent
commit
8aaef24b48
  1. 3
      CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs
  2. 50
      CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs
  3. 4
      CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs
  4. 71
      CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs

3
CoreAgent.Domain/Interfaces/Network/INetworkStatusMonitor.cs

@ -16,7 +16,8 @@ public interface INetworkStatusMonitor
public Task<NetworkStatusCheckResult> CheckAllEndPointsStatusAsync(
NetworkIPEndPointCollection endPoints,
NetworkConfigType configType,
int? timeoutSeconds = null);
int? timeoutSeconds = null,
bool isStartOperation = true);
/// <summary>
/// 检查 RAN 端点状态

50
CoreAgent.Infrastructure/Contexts/CellularNetworkContext.cs

@ -3,6 +3,7 @@ using CoreAgent.Domain.Interfaces.Network;
using CoreAgent.Domain.Models.Network;
using CoreAgent.Domain.Models.System;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
namespace CoreAgent.Infrastructure.Contexts;
@ -21,6 +22,7 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
private bool _isInitialized;
private readonly INetworkIPEndPointManager _networkIPEndPointManager;
private NetworkConfigType _currentConfigType;
private readonly ILogger<CellularNetworkContext> _logger;
/// <summary>
/// 获取取消令牌源
@ -45,7 +47,8 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
public CellularNetworkContext(
IOptions<NetworkCommandConfig> networkCommandConfig,
IOptions<AppSettings> appSettings,
INetworkIPEndPointManager networkIPEndPointManager)
INetworkIPEndPointManager networkIPEndPointManager,
ILogger<CellularNetworkContext> logger)
{
_isDisposed = false;
_isInitialized = false;
@ -53,6 +56,7 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
_networkCommandConfig = networkCommandConfig?.Value ?? throw new ArgumentNullException(nameof(networkCommandConfig));
_appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings));
_networkIPEndPointManager = networkIPEndPointManager ?? throw new ArgumentNullException(nameof(networkIPEndPointManager));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_currentConfigType = NetworkConfigType.None;
}
@ -206,23 +210,53 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable
{
if (_isDisposed)
{
_logger.LogWarning("尝试重置已释放的 CellularNetworkContext");
throw new ObjectDisposedException(nameof(CellularNetworkContext));
}
if (!_isInitialized)
{
_logger.LogInformation("CellularNetworkContext 未初始化,跳过重置操作");
return;
}
lock (_lock)
{
_token.Cancel();
_token = new CancellationTokenSource();
_neConfigKey = string.Empty;
_isInitialized = false;
_networkState = new CellularNetworkState(string.Empty);
_networkIPEndPointManager.Clear();
_currentConfigType = NetworkConfigType.None;
try
{
if (_token != null && !_token.IsCancellationRequested)
{
_logger.LogDebug("正在取消当前的 CancellationTokenSource");
_token.Cancel();
}
}
catch (ObjectDisposedException ex)
{
_logger.LogWarning(ex, "CancellationTokenSource 已被释放");
}
catch (Exception ex)
{
_logger.LogError(ex, "取消操作时发生异常");
}
finally
{
try
{
_token?.Dispose();
_token = new CancellationTokenSource();
_neConfigKey = string.Empty;
_isInitialized = false;
_networkState = new CellularNetworkState(string.Empty);
_networkIPEndPointManager.Clear();
_currentConfigType = NetworkConfigType.None;
_logger.LogInformation("CellularNetworkContext 重置完成");
}
catch (Exception ex)
{
_logger.LogError(ex, "重置 CellularNetworkContext 状态时发生异常");
throw;
}
}
}
}

4
CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs

@ -215,7 +215,7 @@ public class CellularNetworkService : ICellularNetworkService
// 6. 检查网络端点连接状态
_logger.LogInformation("开始检查所有网络端点的连接状态");
var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, _context.CurrentConfigType);
var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, _context.CurrentConfigType, isStartOperation:false);
if (statusCheckResult.IsSuccess)
{
_logger.LogWarning("网络端点仍然处于连接状态,停止操作失败");
@ -288,7 +288,7 @@ public class CellularNetworkService : ICellularNetworkService
// 8. 检查网络端点连接状态
_logger.LogInformation("开始检查所有网络端点的连接状态");
var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, enableResult.ConfigType);
var statusCheckResult = await _statusMonitor.CheckAllEndPointsStatusAsync(endPoints, enableResult.ConfigType, isStartOperation:true);
if (!statusCheckResult.IsSuccess)
{
var errorMessage = string.Join("; ", statusCheckResult.ErrorMessage);

71
CoreAgent.Infrastructure/Services/Network/NetworkStatusMonitor.cs

@ -34,11 +34,13 @@ public class NetworkStatusMonitor : INetworkStatusMonitor
/// <param name="endPoints">网络端点信息</param>
/// <param name="configType">网络配置类型</param>
/// <param name="timeoutSeconds">超时时间(秒),默认30秒</param>
/// <param name="isStartOperation">是否为启动操作,true表示启动操作,false表示停止操作</param>
/// <returns>检查结果</returns>
public async Task<NetworkStatusCheckResult> CheckAllEndPointsStatusAsync(
NetworkIPEndPointCollection endPoints,
NetworkConfigType configType,
int? timeoutSeconds = null)
int? timeoutSeconds = null,
bool isStartOperation = true)
{
var result = new NetworkStatusCheckResult();
var startTime = DateTime.Now;
@ -46,43 +48,72 @@ public class NetworkStatusMonitor : INetworkStatusMonitor
try
{
_logger.LogInformation("开始检查网络端点状态,配置类型: {ConfigType}, 超时时间: {TimeoutSeconds}秒",
configType, timeout.TotalSeconds);
_logger.LogInformation("开始检查网络端点状态,配置类型: {ConfigType}, 操作类型: {OperationType}, 超时时间: {TimeoutSeconds}秒",
configType, isStartOperation ? "Start" : "Stop", timeout.TotalSeconds);
// 先执行一次检查
var checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType);
result.IsSuccess = checkResults.All(r => r.IsSuccess);
// 如果检查失败,进入重试循环
while (!result.IsSuccess && DateTime.Now - startTime < timeout)
// 根据操作类型采用不同的检查策略
if (isStartOperation)
{
var failedEndpoints = checkResults.Where(r => !r.IsSuccess)
.Select(r => $"{r.ComAddr}: {r.ErrorMessage}");
var errorMessage = string.Join("; ", failedEndpoints);
_logger.LogWarning("网络端点状态检查未通过,失败端点: {FailedEndpoints},将在1秒后重试,已耗时: {ElapsedTime}秒",
errorMessage, (DateTime.Now - startTime).TotalSeconds);
await Task.Delay(1000); // 等待1秒后重试
// 重试检查
checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType);
// Start 操作:所有端点必须成功
result.IsSuccess = checkResults.All(r => r.IsSuccess);
// 如果检查失败,进入重试循环
while (!result.IsSuccess && DateTime.Now - startTime < timeout)
{
var failedEndpoints = checkResults.Where(r => !r.IsSuccess)
.Select(r => $"{r.ComAddr}: {r.ErrorMessage}");
var errorMessage = string.Join("; ", failedEndpoints);
_logger.LogWarning("网络端点状态检查未通过,失败端点: {FailedEndpoints},将在1秒后重试,已耗时: {ElapsedTime}秒",
errorMessage, (DateTime.Now - startTime).TotalSeconds);
await Task.Delay(1000); // 等待1秒后重试
// 重试检查
checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType);
result.IsSuccess = checkResults.All(r => r.IsSuccess);
}
}
else
{
// Stop 操作:所有端点必须失败
result.IsSuccess = checkResults.All(r => !r.IsSuccess);
// 如果检查未失败,进入重试循环
while (!result.IsSuccess && DateTime.Now - startTime < timeout)
{
var activeEndpoints = checkResults.Where(r => r.IsSuccess)
.Select(r => r.ComAddr);
var errorMessage = string.Join("; ", activeEndpoints);
_logger.LogWarning("网络端点仍然处于活动状态: {ActiveEndpoints},将在1秒后重试,已耗时: {ElapsedTime}秒",
errorMessage, (DateTime.Now - startTime).TotalSeconds);
await Task.Delay(1000); // 等待1秒后重试
// 重试检查
checkResults = await CheckEndPointsByConfigTypeAsync(endPoints, configType);
result.IsSuccess = checkResults.All(r => !r.IsSuccess);
}
}
if (!result.IsSuccess)
{
result.ErrorMessage = new string[] { $"检查超时,已超过{timeout.TotalSeconds}秒" };
_logger.LogWarning("网络端点状态检查超时,配置类型: {ConfigType}", configType);
_logger.LogWarning("网络端点状态检查超时,配置类型: {ConfigType}, 操作类型: {OperationType}",
configType, isStartOperation ? "Start" : "Stop");
}
else
{
_logger.LogInformation("网络端点状态检查成功,配置类型: {ConfigType}, 耗时: {ElapsedTime}秒",
configType, (DateTime.Now - startTime).TotalSeconds);
_logger.LogInformation("网络端点状态检查成功,配置类型: {ConfigType}, 操作类型: {OperationType}, 耗时: {ElapsedTime}秒",
configType, isStartOperation ? "Start" : "Stop", (DateTime.Now - startTime).TotalSeconds);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "检查网络端点状态时发生错误,配置类型: {ConfigType}", configType);
_logger.LogError(ex, "检查网络端点状态时发生错误,配置类型: {ConfigType}, 操作类型: {OperationType}",
configType, isStartOperation ? "Start" : "Stop");
result.IsSuccess = false;
result.ErrorMessage = new string[] { $"检查过程发生异常: {ex.Message}" };
}

Loading…
Cancel
Save